22 KiB
Az - Ferramentas de Enumeração
{{#include ../../banners/hacktricks-training.md}}
Instalar PowerShell no Linux
Tip
No Linux você precisará instalar o 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 no MacOS
Instruções da documentation:
- Instale
brewse ainda não estiver instalado:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Instale a versão estável mais recente do PowerShell:
brew install powershell/tap/powershell
- Execute o PowerShell:
pwsh
- Atualização:
brew update
brew upgrade powershell
Principais Ferramentas de Enumeração
az cli
Azure Command-Line Interface (CLI) é uma ferramenta multiplataforma escrita em Python para gerenciar e administrar (a maioria dos) recursos do Azure e Entra ID. Ela conecta-se ao Azure e executa comandos administrativos via linha de comando ou scripts.
Siga este link para as installation instructions¡.
Os comandos no Azure CLI são estruturados seguindo o padrão: az <service> <action> <parameters>
Depuração | MitM az cli
Usando o parâmetro --debug é possível ver todas as requisições que a ferramenta az está enviando:
az account management-group list --output table --debug
Para fazer um MitM na ferramenta e check all the requests que ela está enviando manualmente, você pode:
{{#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 é um módulo com cmdlets para gerenciar recursos do Azure diretamente a partir da linha de comando do PowerShell.
Siga este link para as installation instructions.
Os comandos no Azure PowerShell AZ Module são estruturados assim: <Action>-Az<Service> <parameters>
Debug | MitM Az PowerShell
Usando o parâmetro -Debug é possível ver todas as requisições que a ferramenta está enviando:
Get-AzResourceGroup -Debug
Para realizar um MitM na ferramenta e ver manualmente todas as requisições que ela está enviando, você pode definir as variáveis de ambiente HTTPS_PROXY e HTTP_PROXY de acordo com a docs.
Microsoft Graph PowerShell
Microsoft Graph PowerShell é um SDK multiplataforma que possibilita o acesso a todas as Microsoft Graph APIs, incluindo serviços como SharePoint, Exchange e Outlook, usando um único endpoint. Suporta PowerShell 7+, autenticação moderna via MSAL, identidades externas e consultas avançadas. Com foco no princípio do menor privilégio, assegura operações seguras e recebe atualizações regulares para alinhar-se com os recursos mais recentes da Microsoft Graph API.
Follow this link for the installation instructions.
Commands in Microsoft Graph PowerShell are structured like: <Action>-Mg<Service> <parameters>
Depuração do Microsoft Graph PowerShell
Usando o parâmetro -Debug é possível ver todas as requisições que a ferramenta está enviando:
Get-MgUser -Debug
AzureAD Powershell
O módulo Azure Active Directory (AD), agora descontinuado, faz parte do Azure PowerShell para gerenciar recursos do Azure AD. Ele fornece cmdlets para tarefas como gerenciar usuários, grupos e application registrations no Entra ID.
Tip
Isso foi substituído por Microsoft Graph PowerShell
Siga este link para as installation instructions.
Automated Recon & Compliance Tools
turbot azure plugins
Turbot com steampipe e powerpipe permite coletar informações do Azure e Entra ID e executar verificações de conformidade e encontrar misconfigurations. Os módulos Azure atualmente mais recomendados para executar são:
- https://github.com/turbot/steampipe-mod-azure-compliance
- https://github.com/turbot/steampipe-mod-azure-insights
- https://github.com/turbot/steampipe-mod-azuread-insights
# 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 é uma ferramenta de segurança Open Source para realizar avaliações de melhores práticas de segurança, auditorias, resposta a incidentes, monitoramento contínuo, hardening e forensics readiness para AWS, Azure, Google Cloud e Kubernetes.
Basicamente permite executar centenas de verificações em um ambiente Azure para encontrar misconfigurações de segurança e coletar os resultados em json (e outros formatos de texto) ou visualizá-los na 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 revisões automáticas de configurações de segurança de assinaturas do Azure e do Microsoft Entra ID.
Os relatórios HTML são armazenados no diretório ./monkey-reports dentro da pasta do repositório do 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
ScoutSuite reúne dados de configuração para inspeção manual e destaca áreas de risco. É uma ferramenta de auditoria de segurança multi-cloud que permite a avaliação da postura de segurança de ambientes na nuvem.
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
É um powershell script que ajuda a visualizar todos os recursos e permissões dentro de um Management Group e do Entra ID tenant e a encontrar misconfigurações de segurança.
Ele funciona usando o Az PowerShell module, então qualquer autenticação suportada por esta ferramenta é suportada pela ferramenta.
import-module Az
.\AzGovVizParallel.ps1 -ManagementGroupId <management-group-id> [-SubscriptionIdWhitelist <subscription-id>]
Ferramentas automatizadas de pós-exploração
ROADRecon
A enumeração do ROADRecon oferece informações sobre a configuração do Entra ID, como usuários, grupos, funções, políticas de acesso 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
AzureHound é o coletor do BloodHound para Microsoft Entra ID e Azure. É um único binário Go estático para Windows/Linux/macOS que se comunica diretamente com:
- Microsoft Graph (Entra ID directory, M365) e
- Azure Resource Manager (ARM) control plane (subscriptions, resource groups, compute, storage, key vault, app services, AKS, etc.)
Principais características
- Executa de qualquer lugar na internet pública contra as APIs do tenant (não requer acesso à rede interna)
- Gera JSON para ingestão pelo BloodHound CE para visualizar caminhos de ataque através de identidades e recursos na nuvem
- User-Agent padrão observado: azurehound/v2.x.x
Opções de autenticação
- Nome de usuário + senha: -u -p
- Refresh token: --refresh-token
- JSON Web Token (token de acesso): --jwt
- Segredo do service principal: -a -s
- Certificado do service principal: -a --cert <cert.pem> --key <key.pem> [--keypass ]
Exemplos
# Full tenant collection to file using different auth flows
## User creds
azurehound list -u "<user>@<tenant>" -p "<pass>" -t "<tenant-id|domain>" -o ./output.json
## Use an access token (JWT) from az cli for Graph
JWT=$(az account get-access-token --resource https://graph.microsoft.com -o tsv --query accessToken)
azurehound list --jwt "$JWT" -t "<tenant-id>" -o ./output.json
## Use a refresh token (e.g., from device code flow)
azurehound list --refresh-token "<refresh_token>" -t "<tenant-id>" -o ./output.json
## Service principal secret
azurehound list -a "<client-id>" -s "<secret>" -t "<tenant-id>" -o ./output.json
## Service principal certificate
azurehound list -a "<client-id>" --cert "/path/cert.pem" --key "/path/key.pem" -t "<tenant-id>" -o ./output.json
# Targeted discovery
azurehound list users -t "<tenant-id>" -o users.json
azurehound list groups -t "<tenant-id>" -o groups.json
azurehound list roles -t "<tenant-id>" -o roles.json
azurehound list role-assignments -t "<tenant-id>" -o role-assignments.json
# Azure resources via ARM
azurehound list subscriptions -t "<tenant-id>" -o subs.json
azurehound list resource-groups -t "<tenant-id>" -o rgs.json
azurehound list virtual-machines -t "<tenant-id>" -o vms.json
azurehound list key-vaults -t "<tenant-id>" -o kv.json
azurehound list storage-accounts -t "<tenant-id>" -o sa.json
azurehound list storage-containers -t "<tenant-id>" -o containers.json
azurehound list web-apps -t "<tenant-id>" -o webapps.json
azurehound list function-apps -t "<tenant-id>" -o funcapps.json
What gets queried
- Graph endpoints (examples):
- /v1.0/organization, /v1.0/users, /v1.0/groups, /v1.0/roleManagement/directory/roleDefinitions, directoryRoles, owners/members
- ARM endpoints (examples):
- management.azure.com/subscriptions/.../providers/Microsoft.Storage/storageAccounts
- .../Microsoft.KeyVault/vaults, .../Microsoft.Compute/virtualMachines, .../Microsoft.Web/sites, .../Microsoft.ContainerService/managedClusters
Preflight behavior and endpoints
- Cada azurehound list