Files
hacktricks-cloud/src/pentesting-cloud/azure-security/az-enumeration-tools.md

17 KiB

Az - Herramientas de Enumeración

{{#include ../../banners/hacktricks-training.md}}

Instalar PowerShell en Linux

Tip

En Linux necesitarás instalar PowerShell Core:

sudo apt-get update
sudo apt-get install -y wget apt-transport-https software-properties-common

# Ubuntu 20.04
wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb

# Update repos
sudo apt-get update
sudo add-apt-repository universe

# Install & start powershell
sudo apt-get install -y powershell
pwsh

# Az cli
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

Instalar PowerShell en MacOS

Instrucciones de la documentación:

  1. Instala brew si aún no está instalado:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  1. Instala la última versión estable de PowerShell:
brew install powershell/tap/powershell
  1. Ejecutar PowerShell:
pwsh
  1. Actualización:
brew update
brew upgrade powershell

Herramientas Principales de Enumeración

az cli

Interfaz de Línea de Comandos de Azure (CLI) es una herramienta multiplataforma escrita en Python para gestionar y administrar (la mayoría de) los recursos de Azure y Entra ID. Se conecta a Azure y ejecuta comandos administrativos a través de la línea de comandos o scripts.

Sigue este enlace para las instrucciones de instalación¡.

Los comandos en Azure CLI están estructurados utilizando un patrón de: az <servicio> <acción> <parámetros>

Depurar | MitM az cli

Usando el parámetro --debug es posible ver todas las solicitudes que la herramienta az está enviando:

az account management-group list --output table --debug

Para realizar un MitM a la herramienta y verificar todas las solicitudes que está enviando manualmente, puedes hacer:

{{#tabs }} {{#tab name="Bash" }}

export ADAL_PYTHON_SSL_NO_VERIFY=1
export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
export HTTPS_PROXY="http://127.0.0.1:8080"
export HTTP_PROXY="http://127.0.0.1:8080"

# If this is not enough
# Download the certificate from Burp and convert it into .pem format
# And export the following env variable
openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM
export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem

{{#endtab }}

{{#tab name="CMD" }}

set ADAL_PYTHON_SSL_NO_VERIFY=1
set AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
set HTTPS_PROXY="http://127.0.0.1:8080"
set HTTP_PROXY="http://127.0.0.1:8080"

# If this is not enough
# Download the certificate from Burp and convert it into .pem format
# And export the following env variable
openssl x509 -in cacert.der -inform DER -out cacert.pem -outform PEM
set REQUESTS_CA_BUNDLE=C:\Users\user\Downloads\cacert.pem

{{#endtab }}

{{#tab name="PS" }}

$env:ADAL_PYTHON_SSL_NO_VERIFY=1
$env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1
$env:HTTPS_PROXY="http://127.0.0.1:8080"
$env:HTTP_PROXY="http://127.0.0.1:8080"

{{#endtab }} {{#endtabs }}

Az PowerShell

Azure PowerShell es un módulo con cmdlets para gestionar recursos de Azure directamente desde la línea de comandos de PowerShell.

Sigue este enlace para las instrucciones de instalación.

Los comandos en el módulo AZ de Azure PowerShell están estructurados como: <Action>-Az<Service> <parameters>

Debug | MitM Az PowerShell

Usando el parámetro -Debug es posible ver todas las solicitudes que la herramienta está enviando:

Get-AzResourceGroup -Debug

Para realizar un MitM a la herramienta y ver todas las solicitudes que está enviando manualmente, puedes establecer las variables de entorno HTTPS_PROXY y HTTP_PROXY de acuerdo con la documentación.

Microsoft Graph PowerShell

Microsoft Graph PowerShell es un SDK multiplataforma que permite el acceso a todas las API de Microsoft Graph, incluidos servicios como SharePoint, Exchange y Outlook, utilizando un único punto final. Soporta PowerShell 7+, autenticación moderna a través de MSAL, identidades externas y consultas avanzadas. Con un enfoque en el acceso de menor privilegio, garantiza operaciones seguras y recibe actualizaciones regulares para alinearse con las últimas características de la API de Microsoft Graph.

Sigue este enlace para las instrucciones de instalación.

Los comandos en Microsoft Graph PowerShell están estructurados como: <Action>-Mg<Service> <parameters>

Depurar Microsoft Graph PowerShell

Usando el parámetro -Debug es posible ver todas las solicitudes que la herramienta está enviando:

Get-MgUser -Debug

AzureAD Powershell

El módulo de Azure Active Directory (AD), ahora obsoleto, es parte de Azure PowerShell para gestionar recursos de Azure AD. Proporciona cmdlets para tareas como gestionar usuarios, grupos y registros de aplicaciones en Entra ID.

Tip

Esto es reemplazado por Microsoft Graph PowerShell

Sigue este enlace para las instrucciones de instalación.

Herramientas de Reconocimiento Automatizado y Cumplimiento

turbot azure plugins

Turbot con steampipe y powerpipe permite recopilar información de Azure y Entra ID y realizar verificaciones de cumplimiento y encontrar configuraciones incorrectas. Los módulos de Azure actualmente más recomendados para ejecutar son:

# Install
brew install turbot/tap/powerpipe
brew install turbot/tap/steampipe
steampipe plugin install azure
steampipe plugin install azuread

# Config creds via env vars or az cli default creds will be used
export AZURE_ENVIRONMENT="AZUREPUBLICCLOUD"
export AZURE_TENANT_ID="<tenant-id>"
export AZURE_SUBSCRIPTION_ID="<subscription-id>"
export AZURE_CLIENT_ID="<client-id>"
export AZURE_CLIENT_SECRET="<secret>"

# Run steampipe-mod-azure-insights
cd /tmp
mkdir dashboards
cd dashboards
powerpipe mod init
powerpipe mod install github.com/turbot/steampipe-mod-azure-insights
steampipe service start
powerpipe server
# Go to http://localhost:9033 in a browser

Prowler

Prowler es una herramienta de seguridad de código abierto para realizar evaluaciones de las mejores prácticas de seguridad en AWS, Azure, Google Cloud y Kubernetes, auditorías, respuesta a incidentes, monitoreo continuo, endurecimiento y preparación forense.

Básicamente, nos permitiría ejecutar cientos de verificaciones en un entorno de Azure para encontrar configuraciones de seguridad incorrectas y recopilar los resultados en json (y otros formatos de texto) o verificarlos en la web.

# Create a application with Reader role and set the tenant ID, client ID and secret in prowler so it access the app

# Launch web with docker-compose
export DOCKER_DEFAULT_PLATFORM=linux/amd64
curl -LO https://raw.githubusercontent.com/prowler-cloud/prowler/refs/heads/master/docker-compose.yml
curl -LO https://raw.githubusercontent.com/prowler-cloud/prowler/refs/heads/master/.env
## If using an old docker-compose version, change the "env_file" params to: env_file: ".env"
docker compose up -d
# Access the web and configure the access to run a scan from it

# Prowler cli
python3 -m pip install prowler --break-system-packages
docker run --rm toniblyx/prowler:v4-latest azure --list-checks
docker run --rm toniblyx/prowler:v4-latest azure --list-services
docker run --rm toniblyx/prowler:v4-latest azure --list-compliance
docker run --rm -e "AZURE_CLIENT_ID=<client-id>" -e "AZURE_TENANT_ID=<tenant-id>" -e "AZURE_CLIENT_SECRET=<secret>" toniblyx/prowler:v4-latest azure --sp-env-auth
## It also support other authentication types, check: prowler azure --help

Monkey365

Permite realizar revisiones de la configuración de seguridad de suscripciones de Azure y Microsoft Entra ID automáticamente.

Los informes en HTML se almacenan dentro del directorio ./monkey-reports dentro de la carpeta del repositorio de github.

git clone https://github.com/silverhack/monkey365
Get-ChildItem -Recurse monkey365 | Unblock-File
cd monkey365
Import-Module ./monkey365
mkdir /tmp/monkey365-scan
cd /tmp/monkey365-scan

Get-Help Invoke-Monkey365
Get-Help Invoke-Monkey365 -Detailed

# Scan with user creds (browser will be run)
Invoke-Monkey365 -TenantId <tenant-id> -Instance Azure -Collect All -ExportTo HTML

# Scan with App creds
$SecureClientSecret = ConvertTo-SecureString "<secret>" -AsPlainText -Force
Invoke-Monkey365 -TenantId <tenant-id> -ClientId <client-id> -ClientSecret $SecureClientSecret -Instance Azure -Collect All -ExportTo HTML

ScoutSuite

Scout Suite recopila datos de configuración para inspección manual y destaca áreas de riesgo. Es una herramienta de auditoría de seguridad multi-nube, que permite la evaluación de la postura de seguridad de los entornos en la nube.

virtualenv -p python3 venv
source venv/bin/activate
pip install scoutsuite
scout --help

# Use --cli flag to use az cli credentials
# Use --user-account to have scout prompt for user credentials
# Use --user-account-browser to launch a browser to login
# Use --service-principal to have scout prompt for app credentials

python scout.py azure --cli

Azure-MG-Sub-Governance-Reporting

Es un script de PowerShell que te ayuda a visualizar todos los recursos y permisos dentro de un Grupo de Gestión y el inquilino de Entra ID y encontrar configuraciones de seguridad incorrectas.

Funciona utilizando el módulo Az PowerShell, por lo que cualquier autenticación soportada por esta herramienta es soportada por la herramienta.

import-module Az
.\AzGovVizParallel.ps1 -ManagementGroupId <management-group-id> [-SubscriptionIdWhitelist <subscription-id>]

Herramientas de Post-Explotación Automatizadas

ROADRecon

La enumeración de ROADRecon ofrece información sobre la configuración de Entra ID, como usuarios, grupos, roles, políticas de acceso condicional...

cd ROADTools
pipenv shell
# Login with user creds
roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!"
# Login with app creds
roadrecon auth --as-app --client "<client-id>" --password "<secret>" --tenant "<tenant-id>"
roadrecon gather
roadrecon gui

AzureHound

# Launch AzureHound
## Login with app secret
azurehound -a "<client-id>" -s "<secret>" --tenant "<tenant-id>" list -o ./output.json
## Login with user creds
azurehound -u "<user-email>" -p "<password>" --tenant "<tenant-id>" list -o ./output.json

Lanza la BloodHound web con curl -L https://ghst.ly/getbhce | docker compose -f - up e importa el archivo output.json.

Luego, en la pestaña EXPLORE, en la sección CYPHER puedes ver un ícono de carpeta que contiene consultas predefinidas.

MicroBurst

MicroBurst incluye funciones y scripts que soportan el descubrimiento de servicios de Azure, auditoría de configuraciones débiles y acciones de post explotación como el volcado de credenciales. Está destinado a ser utilizado durante pruebas de penetración donde se utiliza Azure.

Import-Module .\MicroBurst.psm1
Import-Module .\Get-AzureDomainInfo.ps1
Get-AzureDomainInfo -folder MicroBurst -Verbose

PowerZure

PowerZure fue creado por la necesidad de un marco que pueda realizar tanto reconocimiento como explotación de Azure, EntraID y los recursos asociados.

Utiliza el módulo Az PowerShell, por lo que cualquier autenticación soportada por esta herramienta es soportada por la herramienta.

# Login
Import-Module Az
Connect-AzAccount

# Clone and import PowerZure
git clone https://github.com/hausec/PowerZure
cd PowerZure
ipmo ./Powerzure.psd1
Invoke-Powerzure -h # Check all the options

# Info Gathering (read)
Get-AzureCurrentUser # Get current user
Get-AzureTarget # What can you access to
Get-AzureUser -All # Get all users
Get-AzureSQLDB -All # Get all SQL DBs
Get-AzureAppOwner # Owners of apps in Entra
Show-AzureStorageContent -All # List containers, shared and tables
Show-AzureKeyVaultContent -All # List all contents in key vaults


# Operational (write)
Set-AzureUserPassword -Password <password> -Username <username> # Change password
Set-AzureElevatedPrivileges # Get permissions from Global Administrator in EntraID to User Access Administrator in Azure RBAC.
New-AzureBackdoor -Username <username> -Password <password>
Invoke-AzureRunCommand -Command <command> -VMName <vmname>
[...]

GraphRunner

GraphRunner es un conjunto de herramientas de post-explotación para interactuar con la API de Microsoft Graph. Proporciona varias herramientas para realizar reconocimiento, persistencia y saqueo de datos de una cuenta de Microsoft Entra ID (Azure AD).

#A good place to start is to authenticate with the Get-GraphTokens module. This module will launch a device-code login, allowing you to authenticate the session from a browser session. Access and refresh tokens will be written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)
Import-Module .\GraphRunner.ps1
Get-GraphTokens

#This module gathers information about the tenant including the primary contact info, directory sync settings, and user settings such as if users have the ability to create apps, create groups, or consent to apps.
Invoke-GraphRecon -Tokens $tokens -PermissionEnum

#A module to dump conditional access policies from a tenant.
Invoke-GraphRecon -Tokens $tokens -PermissionEnum

#A module to dump conditional access policies from a tenant.
Invoke-DumpCAPS -Tokens $tokens -ResolveGuids

#This module helps identify malicious app registrations. It will dump a list of Azure app registrations from the tenant including permission scopes and users that have consented to the apps. Additionally, it will list external apps that are not owned by the current tenant or by Microsoft's main app tenant. This is a good way to find third-party external apps that users may have consented to.
Invoke-DumpApps -Tokens $tokens

#Gather the full list of users from the directory.
Get-AzureADUsers -Tokens $tokens -OutFile users.txt

#Create a list of security groups along with their members.
Get-SecurityGroups -AccessToken $tokens.access_token

#Gets groups that may be able to be modified by the current user
Get-UpdatableGroups -Tokens $tokens

#Finds dynamic groups and displays membership rules
Get-DynamicGroups -Tokens $tokens

#Gets a list of SharePoint site URLs visible to the current user
Get-SharePointSiteURLs -Tokens $tokens

#This module attempts to locate mailboxes in a tenant that have allowed other users to read them. By providing a userlist the module will attempt to access the inbox of each user and display if it was successful. The access token needs to be scoped to Mail.Read.Shared or Mail.ReadWrite.Shared for this to work.
Invoke-GraphOpenInboxFinder -Tokens $tokens -Userlist users.txt

#This module attempts to gather a tenant ID associated with a domain.
Get-TenantID -Domain

#Runs Invoke-GraphRecon, Get-AzureADUsers, Get-SecurityGroups, Invoke-DumpCAPS, Invoke-DumpApps, and then uses the default_detectors.json file to search with Invoke-SearchMailbox, Invoke-SearchSharePointAndOneDrive, and Invoke-SearchTeams.
Invoke-GraphRunner -Tokens $tokens

Stormspotter

Stormspotter crea un “gráfico de ataque” de los recursos en una suscripción de Azure. Permite a los equipos rojos y pentesters visualizar la superficie de ataque y las oportunidades de pivote dentro de un inquilino, y potencia a tus defensores para orientarse y priorizar rápidamente el trabajo de respuesta a incidentes.

Desafortunadamente, parece no estar mantenido.

# Start Backend
cd stormspotter\backend\
pipenv shell
python ssbackend.pyz

# Start Front-end
cd stormspotter\frontend\dist\spa\
quasar.cmd serve -p 9091 --history

# Run Stormcollector
cd stormspotter\stormcollector\
pipenv shell
az login -u test@corp.onmicrosoft.com -p Welcome2022!
python stormspotter\stormcollector\sscollector.pyz cli
# This will generate a .zip file to upload in the frontend (127.0.0.1:9091)

{{#include ../../banners/hacktricks-training.md}}