Skip to content

10 / 13Network and compute

Azure Virtual Machines security hardening

Harden Azure VMs: Trusted Launch, no public IPs, JIT and Bastion access, Entra ID login, encryption at host, Update Manager patching and Defender for Servers.

Service
Virtual Machines
Category
Network and compute
Baseline
11 controls
Updated
Published on 12 min read
On this page

Virtual machines carry the oldest attack surface in Azure: an operating system with open ports, local accounts, unpatched packages and, more and more often, a managed identity that can call Azure APIs. Left at defaults, the usual failure is not exotic: RDP or SSH exposed to the internet and brute forced within hours, a missing patch on an internet-facing service, or a Contributor somewhere in the subscription using Run Command to execute code as root or SYSTEM without ever logging in. A hardened VM is the sum of three layers: the platform settings Azure controls (boot integrity, disk encryption, network exposure), how people and tools get in, and the guest OS configuration and patch level. This page covers the first two in depth and the guest layer at the level of Azure tooling; for the OS itself, apply the CIS benchmark for your distribution or Windows version. Controls map to the Microsoft cloud security benchmark (MCSB) security baselines for Linux and Windows virtual machines.

Baseline controls

Plain CIS numbers refer to the CIS Microsoft Azure Foundations Benchmark v7.0.0; numbers marked Compute refer to the CIS Microsoft Azure Compute Services Benchmark v2.0.1.

ControlWhyHow to checkID
Trusted LaunchBlocks boot kits, enables boot integrity monitoringaz vm show --query securityProfileMCSB PV-4 / CIS Azure Compute 2.0.1 20.10
No public IP on VMsRemoves direct internet exposure of the OSPolicy "Network interfaces should not have public IPs"MCSB NS-2
JIT or Bastion for admin accessNo standing open 22 or 3389Defender for Cloud JIT recommendationMCSB PA-2 / CIS 7.1.1, 7.1.5, 8.4.1
Entra ID login, local admin as break-glassCentral revocation, MFA and Conditional Accessaz vm extension list shows AADSSHLoginForLinux or AADLoginForWindowsMCSB IM-1, PA-1 / CIS Compute 20.9
Restrict Run Command and extensionsContributor equals code execution as rootRole assignments with runCommand/actionMCSB PA-7 / CIS Compute 20.6
Encryption at host, CMK where requiredCovers temp disks and caches, not only managed disksaz vm show --query securityProfile.encryptionAtHostMCSB DP-4, DP-5 / CIS Compute 20.11, 20.2
Patching with Update ManagerMissing patches are the top VM entry pointResource Graph patchassessmentresourcesMCSB PV-6 / CIS 8.1.11
Machine configuration baselineAudits OS settings from AzurePolicy compliance of the compute baselineMCSB PV-3
Defender for ServersEDR and vulnerability scanning on every VMaz security pricing show -n VirtualMachinesMCSB ES-1, PV-5 / CIS 8.1.3.1, 8.1.3.2, 8.1.3.3
Scoped managed identityAny process on the VM can get its tokenRole assignments of the VM principalMCSB IM-3
Azure BackupRecovery after ransomware or a bad changePolicy "Azure Backup should be enabled for Virtual Machines"MCSB BR-1

Trusted Launch and secure VM definition

Create VMs with Trusted Launch, no public IP, no password authentication and a managed identity only if the workload needs one:

bash
az vm create \
  --resource-group rg-app1 --name vm-app1-01 \
  --image Ubuntu2404 --size Standard_D2s_v5 \
  --vnet-name vnet-app1 --subnet snet-app \
  --public-ip-address "" --nsg "" \
  --security-type TrustedLaunch --enable-secure-boot true --enable-vtpm true \
  --encryption-at-host true \
  --admin-username azureops --generate-ssh-keys \
  --authentication-type ssh \
  --patch-mode AutomaticByPlatform

Trusted Launch combines Secure Boot, a virtual TPM and boot integrity monitoring in Defender for Cloud. It protects against boot kits and kernel-mode rootkits and gives you measured boot. It is the default security type for new Gen2 VMs created in the portal and recent CLI versions, so the risk is mostly templates and old modules that still set securityType to Standard. Existing Gen1 and Gen2 VMs can be upgraded to Trusted Launch after a deallocation; Gen1 needs a disk conversion first, so test that on a copy.

Check one VM:

bash
az vm show -g rg-app1 -n vm-app1-01 \
  --query "securityProfile.{type:securityType, secureBoot:uefiSettings.secureBootEnabled, vtpm:uefiSettings.vTpmEnabled}"

Find all VMs without it in Resource Graph:

KQL
resources
| where type == "microsoft.compute/virtualmachines"
| extend secType = tostring(properties.securityProfile.securityType)
| where secType !in ("TrustedLaunch", "ConfidentialVM")
| project name, resourceGroup, subscriptionId, secType

Enforce

Encode the definition in Bicep or Terraform modules, then back it with policy. Useful built-ins: "Virtual Machine should have TrustedLaunch enabled", "Disks and OS image should support TrustedLaunch", "Linux virtual machines should use Secure Boot" and "Secure Boot should be enabled on supported Windows virtual machines". The DeployIfNotExists definitions "Configure supported virtual machines to automatically enable vTPM" and "Configure supported Linux virtual machines to automatically enable Secure Boot" fix supported VMs in place. Assign them at a management group as described on the Azure Policy page.

No public IP on VMs

--public-ip-address "" and --nsg "" in the command above create a VM with no public IP and no per-NIC NSG; the subnet NSG governs traffic, and inbound internet traffic arrives through a load balancer, Application Gateway or Front Door that you control. Network segmentation, NSG design and Bastion deployment are on the Virtual Network page.

Find VMs that still have a public IP:

KQL
resources
| where type == "microsoft.network/networkinterfaces"
| mv-expand ipconfig = properties.ipConfigurations
| where isnotempty(ipconfig.properties.publicIPAddress.id)
| project nic = name, vm = tostring(properties.virtualMachine.id), pip = tostring(ipconfig.properties.publicIPAddress.id)

Assign "Network interfaces should not have public IPs" with the Deny effect on landing zones that should never face the internet, and keep internet-facing workloads in a separate management group with its own exemptions. Defender for Cloud also raises "All network ports should be restricted on network security groups associated to your virtual machine" for overly open NSGs.

Just-in-time access and Azure Bastion

Prefer Azure Bastion for interactive administration: users connect through the portal or az network bastion ssh, nothing listens on the VM's public side, and the Standard or Premium SKU supports native client connections and session recording (Premium).

If administrators must reach VMs directly, never leave 22 or 3389 open. Just-in-time (JIT) VM access, part of Microsoft Defender for Servers Plan 2, keeps an NSG deny rule on management ports and inserts a temporary allow rule for the requester's IP, then removes it. Enable it per VM in Defender for Cloud > Workload protections > Just-in-time VM access, or with Az PowerShell:

PowerShell
$policy = @(@{
  id = "/subscriptions/<sub-id>/resourceGroups/rg-app1/providers/Microsoft.Compute/virtualMachines/vm-app1-01"
  ports = @(@{
    number = 22; protocol = "TCP";
    allowedSourceAddressPrefix = @("203.0.113.0/24");
    maxRequestAccessDuration = "PT3H"
  })
})

Set-AzJitNetworkAccessPolicy -Kind "Basic" -Location "westeurope" `
  -Name "default" -ResourceGroupName "rg-app1" -VirtualMachine $policy

Request access for one hour from a single address:

PowerShell
$req = @{
  id = "/subscriptions/<sub-id>/resourceGroups/rg-app1/providers/Microsoft.Compute/virtualMachines/vm-app1-01"
  ports = @(@{ number = 22; endTimeUtc = (Get-Date).AddHours(1).ToUniversalTime().ToString("o");
               allowedSourceAddressPrefix = @("203.0.113.25") })
}
Start-AzJitNetworkAccessPolicy `
  -ResourceId "/subscriptions/<sub-id>/resourceGroups/rg-app1/providers/Microsoft.Security/locations/westeurope/jitNetworkAccessPolicies/default" `
  -VirtualMachine $req

Requesting access needs Microsoft.Security/locations/jitNetworkAccessPolicies/initiate/action, so operators can get a custom role with that action and VM read, and nothing else. Every request lands in the activity log. Audit coverage with the built-in "Management ports of virtual machines should be protected with just-in-time network access control".

Microsoft Entra ID login and local accounts

Local admin accounts and SSH keys scattered on laptops are hard to revoke when someone leaves. Use Entra ID authentication instead:

bash
# Linux
az vm extension set --publisher Microsoft.Azure.ActiveDirectory \
  --name AADSSHLoginForLinux --resource-group rg-app1 --vm-name vm-app1-01

# Windows
az vm extension set --publisher Microsoft.Azure.ActiveDirectory \
  --name AADLoginForWindows --resource-group rg-app1 --vm-name vm-win-01

Grant Virtual Machine User Login or Virtual Machine Administrator Login at the VM or resource group, make the administrator role eligible through PIM rather than permanent (see the Entra ID page and RBAC page), and connect with az ssh vm --resource-group rg-app1 --name vm-app1-01. Conditional Access policies, including MFA, apply to these sign-ins through the "Azure Windows VM Sign-In" and "Azure Linux VM Sign-In" applications.

Keep one local admin account only as a break-glass path: a long random password or key stored in Key Vault, or Windows LAPS for Windows VMs. On Linux, the built-in "Authentication to Linux machines should require SSH keys" audits that password authentication is off, and "Linux machines should only have local accounts that are allowed" flags unexpected local users.

Run Command and extension control

Anyone with Microsoft.Compute/virtualMachines/runCommand/action or Microsoft.Compute/virtualMachines/extensions/write can run arbitrary code as root or SYSTEM on the VM without logging in. Both are included in Contributor and Virtual Machine Contributor. This is a well-known lateral movement path from an Azure role to a guest OS, documented in MITRE ATT&CK as T1651 (Cloud Administration Command), and it bypasses Entra ID login, JIT and Bastion entirely.

  • Do not grant Contributor at subscription scope to people who should not have root on every VM. Use narrower built-in roles or custom roles that exclude these actions with NotActions.
  • Watch for managed run commands too (Microsoft.Compute/virtualMachines/runCommands/write), which persist on the VM resource.

Find who holds the action:

bash
az role assignment list --all --include-inherited \
  --query "[?roleDefinitionName=='Contributor' || roleDefinitionName=='Virtual Machine Contributor' || roleDefinitionName=='Owner'].{who:principalName, role:roleDefinitionName, scope:scope}" -o table

Alert on use in the activity log (query under Logging and detection).

Disk encryption

Managed disks are always encrypted at rest with server-side encryption (SSE) using platform-managed keys. On top of that:

  • Encryption at host encrypts temp disks, ephemeral OS disks and the disk caches on the host, and data flows from compute to storage are encrypted end to end. It needs a one-time feature registration per subscription:

    bash
    az feature register --namespace Microsoft.Compute --name EncryptionAtHost
    az provider register --namespace Microsoft.Compute
    

    Enforce with "Virtual machines and virtual machine scale sets should have encryption at host enabled" (Audit or Deny). Defender for Cloud's recommendation behind "Linux virtual machines should enable Azure Disk Encryption or EncryptionAtHost." and its Windows twin accepts encryption at host.

  • Customer-managed keys through a disk encryption set when regulation requires control over keys. The key lives in a Key Vault or Managed HSM with purge protection, as covered on the Key Vault page.

  • Confidential disk encryption on confidential VM SKUs when you need protection from the host operator itself.

Azure Disk Encryption (BitLocker or dm-crypt inside the guest) is scheduled for retirement in September 2028. Do not use it for new deployments; plan the migration to encryption at host.

Patching with Azure Update Manager

Azure Automation Update Management and the Log Analytics agent it depended on were retired in 2024. Azure Update Manager replaces it for Azure VMs and Arc-enabled servers, using only the VM guest agent.

Periodic assessment

Turn on periodic assessment so missing updates are visible every 24 hours:

bash
az vm update -g rg-app1 -n vm-app1-01 \
  --set osProfile.linuxConfiguration.patchSettings.assessmentMode=AutomaticByPlatform

(Use osProfile.windowsConfiguration.patchSettings.assessmentMode on Windows.) At scale, assign the built-in "Configure periodic checking for missing system updates on azure virtual machines" with a remediation task, and audit with "Machines should be configured to periodically check for missing system updates".

Orchestration

Choose AutomaticByPlatform (Azure decides timing, outside regional peak hours, in safe deployment order) for stateless fleets, or customer-managed schedules for workloads with fixed windows. A schedule is a maintenance configuration with scope InGuestPatch, attached directly or through dynamic scopes (subscription, resource group, tag, OS):

Bicep
resource weekly 'Microsoft.Maintenance/maintenanceConfigurations@2023-04-01' = {
  name: 'mc-weekly-sunday'
  location: 'westeurope'
  properties: {
    maintenanceScope: 'InGuestPatch'
    extensionProperties: { InGuestPatchMode: 'User' }
    maintenanceWindow: {
      startDateTime: '2026-11-22 02:00'
      duration: '03:00'
      timeZone: 'W. Europe Standard Time'
      recurEvery: 'Week Sunday'
    }
    installPatches: {
      rebootSetting: 'IfRequired'
      linuxParameters: { classificationsToInclude: [ 'Critical', 'Security' ] }
      windowsParameters: { classificationsToInclude: [ 'Critical', 'Security', 'Definition' ] }
    }
  }
}

VMs on a customer-managed schedule need patch mode AutomaticByPlatform with bypassPlatformSafetyChecksOnUserSchedule set to true, otherwise the platform and your schedule both try to patch.

Verify

KQL
patchassessmentresources
| where type =~ "microsoft.compute/virtualmachines/patchassessmentresults"
| extend crit = toint(properties.availablePatchCountByClassification.critical),
         sec  = toint(properties.availablePatchCountByClassification.security)
| where crit > 0 or sec > 0
| project vm = tostring(split(id, "/patchAssessmentResults")[0]), crit, sec, lastAssessed = properties.lastModifiedDateTime

The Defender for Cloud recommendation behind "System updates should be installed on your machines (powered by Update Center)" reports the same gap in secure score.

Machine configuration baselines

Azure Machine Configuration (formerly Guest Configuration) audits settings inside the OS through Azure Policy. The built-ins "Linux machines should meet requirements for the Azure compute security baseline" and "Windows machines should meet requirements of the Azure compute security baseline" check hundreds of OS settings (SSH configuration, password policy, audit settings, legacy protocols) and report per machine. They need the machine configuration extension and a system-assigned managed identity; assign the initiative "Deploy prerequisites to enable Guest Configuration policies on virtual machines" first, at the same scope.

Machine configuration can also apply settings (audit and set modes) with custom DSC packages, which lets you push your own CIS-derived baseline instead of only reporting drift.

Defender for Servers

Microsoft Defender for Servers integrates Microsoft Defender for Endpoint (EDR), agentless vulnerability scanning and secrets scanning on disk snapshots, and, with Plan 2, file integrity monitoring and JIT. Enable it at subscription scope:

bash
az security pricing create -n VirtualMachines --tier Standard --subplan P2

Enforce coverage with "Configure Microsoft Defender for Servers plan" (DeployIfNotExists) at the management group, as described on the Defender for Cloud page. Exclude nothing by default: a VM without EDR is where attackers settle. The built-in "A vulnerability assessment solution should be enabled on your virtual machines" flags machines without scanning.

Managed identity scope

If the VM has a managed identity, any process on it, including an attacker with a web shell, can request a token from the instance metadata service at 169.254.169.254 without credentials. Give that identity only the data-plane roles the application needs at the narrowest scope (one storage container, one key vault), never Contributor or Owner on the subscription. Prefer a user-assigned identity shared by a defined set of VMs over system-assigned identities with ad hoc grants, so access is reviewable. Scoping patterns are on the Azure RBAC page.

bash
PID=$(az vm show -g rg-app1 -n vm-app1-01 --query identity.principalId -o tsv)
az role assignment list --assignee "$PID" --all -o table

Azure Backup

Backups are your recovery path after ransomware in the guest or an accidental deletion. Protect production VMs with a Recovery Services vault, enable soft delete and immutability on the vault, and enable multi-user authorization (Resource Guard) so a single compromised admin cannot delete backups. Audit coverage with "Azure Backup should be enabled for Virtual Machines", and use the DeployIfNotExists backup policies to enroll VMs by tag.

Logging and detection

  • Activity log (route it to Log Analytics with a subscription diagnostic setting): Run Command, extension writes, JIT initiations, disk exports (Microsoft.Compute/disks/beginGetAccess/action) and NSG changes all appear here.
  • Guest logs through the Azure Monitor Agent and data collection rules: Syslog (auth, authpriv) on Linux, Security events on Windows. The legacy Log Analytics agent is retired; audit with "Linux virtual machines should have Azure Monitor Agent installed" and "Windows virtual machines should have Azure Monitor Agent installed".
  • Defender for Servers alerts: Defender for Endpoint detections, suspicious Run Command or extension use, and brute force attempts.

Alert on Run Command, extension writes and disk SAS exports:

KQL
AzureActivity
| where OperationNameValue in~ (
    "MICROSOFT.COMPUTE/VIRTUALMACHINES/RUNCOMMAND/ACTION",
    "MICROSOFT.COMPUTE/VIRTUALMACHINES/RUNCOMMANDS/WRITE",
    "MICROSOFT.COMPUTE/VIRTUALMACHINES/EXTENSIONS/WRITE",
    "MICROSOFT.COMPUTE/DISKS/BEGINGETACCESS/ACTION")
| where ActivityStatusValue in ("Start", "Started", "Success", "Succeeded")
| project TimeGenerated, Caller, CallerIpAddress, OperationNameValue, _ResourceId

Workspace design, retention and alert routing are on the Azure Monitor page.

Common mistakes

  • Opening 3389 or 22 to Any "for a quick test" and forgetting it: internet scanners find and brute force it within hours.
  • Granting Contributor broadly and assuming Entra ID login controls who can run code on VMs, while Run Command bypasses login entirely.
  • Leaving templates on securityType: Standard, which silently creates VMs without Secure Boot or vTPM that later need a rebuild or upgrade window.
  • Deploying new workloads with Azure Disk Encryption instead of encryption at host, then facing a forced migration before the 2028 retirement.
  • Setting a customer-managed patch schedule without the bypass flag, so platform patching and the schedule collide and reboots happen outside the window.
  • Giving the VM managed identity subscription Contributor "so the app works", turning any web shell into control of the whole subscription.
  • Enabling Defender for Servers on some subscriptions only, leaving forgotten VMs without EDR or vulnerability scanning.

References

Filed under virtual-machines, compute, network, cis-benchmark

Written by

, Cloud Security Engineer & Editor

Security engineer writing practical hardening pages for Microsoft Azure tenants and subscriptions, aligned with the CIS Microsoft Azure Foundations Benchmark.

Related services

  1. Storage accountsHarden Azure Storage accounts: no anonymous blob access, no shared keys, short SAS, private endpoints, TLS 1.2, customer-managed keys, soft delete and logging.
  2. App ServiceHarden Azure App Service: HTTPS and TLS, basic auth and FTP off, access restrictions, private endpoints, Key Vault references, logging and dangling DNS.
  3. Azure FunctionsHarden Azure Functions: access keys and Entra auth, master key exposure, identity-based storage, network isolation, Flex Consumption, CORS and logging.