Az - Ferramentas de Enumeração
Reading time: 14 minutes
tip
Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE)
Aprenda e pratique Hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Confira os planos de assinatura!
- Junte-se ao 💬 grupo do Discord ou ao grupo do telegram ou siga-nos no Twitter 🐦 @hacktricks_live.
- Compartilhe truques de hacking enviando PRs para o HackTricks e HackTricks Cloud repositórios do github.
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 documentação:
- Instale
brew
se 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
Ferramentas Principais de Enumeração
az cli
Interface de Linha de Comando do Azure (CLI) é uma ferramenta multiplataforma escrita em Python para gerenciar e administrar (a maioria) dos recursos do Azure e do Entra ID. Ela se conecta ao Azure e executa comandos administrativos via linha de comando ou scripts.
Siga este link para as instruções de instalação¡.
Os comandos na Azure CLI são estruturados usando um padrão de: az <serviço> <ação> <parâmetros>
Debug | 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 verificar todas as requisições que ela está enviando manualmente, você pode fazer:
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
Az PowerShell
Azure PowerShell é um módulo com cmdlets para gerenciar recursos do Azure diretamente da linha de comando do PowerShell.
Siga este link para as instruções de instalação.
Os comandos no Módulo AZ do Azure PowerShell são estruturados como: <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 fazer um MitM na ferramenta e verificar todas as requisições que ela está enviando manualmente, 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 permite o acesso a todas as APIs do Microsoft Graph, incluindo serviços como SharePoint, Exchange e Outlook, usando um único endpoint. Ele suporta PowerShell 7+, autenticação moderna via MSAL, identidades externas e consultas avançadas. Com foco no acesso de menor privilégio, garante operações seguras e recebe atualizações regulares para alinhar-se com os últimos recursos da API do Microsoft Graph.
Siga este link para as instruções de instalação.
Os comandos no Microsoft Graph PowerShell são estruturados como: <Action>-Mg<Service> <parameters>
Depurar o 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 obsoleto, faz parte do Azure PowerShell para gerenciar recursos do Azure AD. Ele fornece cmdlets para tarefas como gerenciar usuários, grupos e registros de aplicativos no Entra ID.
tip
Isso é substituído pelo Microsoft Graph PowerShell
Siga este link para as instruções de instalação.
Ferramentas de Reconhecimento e Conformidade Automatizadas
turbot azure plugins
O Turbot com steampipe e powerpipe permite coletar informações do Azure e Entra ID e realizar verificações de conformidade e encontrar configurações incorretas. Os módulos do Azure atualmente mais recomendados para execução 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, endurecimento e prontidão forense em AWS, Azure, Google Cloud e Kubernetes.
Basicamente, permitiria que executássemos centenas de verificações em um ambiente Azure para encontrar configurações de segurança incorretas e reunir os resultados em json (e outros formatos de texto) ou verificá-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
Ele permite realizar revisões de configuração de segurança de assinaturas do Azure e do Microsoft Entra ID automaticamente.
Os relatórios em HTML são armazenados dentro do diretório ./monkey-reports
na 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
O Scout Suite coleta 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 em 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 script do powershell que ajuda você a visualizar todos os recursos e permissões dentro de um Grupo de Gerenciamento e do tenant Entra ID e encontrar configurações de segurança incorretas.
Funciona usando o módulo Az PowerShell, 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 de Pós-Exploração Automatizadas
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
# 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
Inicie a BloodHound web com curl -L https://ghst.ly/getbhce | docker compose -f - up
e importe o arquivo output.json
.
Em seguida, na aba EXPLORE, na seção CYPHER, você pode ver um ícone de pasta que contém consultas pré-construídas.
MicroBurst
MicroBurst inclui funções e scripts que suportam a descoberta de Serviços Azure, auditoria de configurações fracas e ações de pós-exploração, como extração de credenciais. É destinado a ser usado durante testes de penetração onde o Azure está em uso.
Import-Module .\MicroBurst.psm1
Import-Module .\Get-AzureDomainInfo.ps1
Get-AzureDomainInfo -folder MicroBurst -Verbose
PowerZure
PowerZure foi criado a partir da necessidade de um framework que possa realizar tanto reconhecimento quanto exploração do Azure, EntraID e os recursos associados.
Ele usa o módulo Az PowerShell, portanto, qualquer autenticação suportada por esta ferramenta é suportada pela ferramenta.
# 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 é um conjunto de ferramentas de pós-exploração para interagir com a Microsoft Graph API. Ele fornece várias ferramentas para realizar reconhecimento, persistência e pilhagem de dados de uma conta 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 cria um “gráfico de ataque” dos recursos em uma assinatura Azure. Ele permite que equipes vermelhas e pentesters visualizem a superfície de ataque e as oportunidades de pivô dentro de um inquilino, e potencializa seus defensores para rapidamente se orientar e priorizar o trabalho de resposta a incidentes.
Infelizmente, parece estar desatualizado.
# 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)
tip
Aprenda e pratique Hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Aprenda e pratique Hacking GCP: HackTricks Training GCP Red Team Expert (GRTE)
Aprenda e pratique Hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Confira os planos de assinatura!
- Junte-se ao 💬 grupo do Discord ou ao grupo do telegram ou siga-nos no Twitter 🐦 @hacktricks_live.
- Compartilhe truques de hacking enviando PRs para o HackTricks e HackTricks Cloud repositórios do github.