Home / Azure

AzureHow-toIntermediate

Just-in-time VM access in Defender for Cloud: lock down RDP and SSH, request access from PowerShell and fix requests that fail

Close RDP and SSH on Azure VMs and open them only on request with Defender for Cloud JIT. Enable a policy, request access from PowerShell or az rest, and fix requests that still time out.

Deepak Bhardwaj7 min read

Applies toMicrosoft Defender for Cloud just-in-time VM access (Defender for Servers Plan 2); Azure VMs (Resource Manager) protected by NSGs or Azure Firewall; Az PowerShell (Az.Security); Azure CLI

The goal

Your security scanner flags port 3389 or 22 open to the internet, or to the whole corporate range, on a set of Azure VMs. Admins still need to log in now and then. Just-in-time (JIT) VM access in Microsoft Defender for Cloud fixes this. It adds a deny rule for the management ports to the VM's network security group (NSG). When an admin asks for access, it adds a temporary allow rule for that admin's source IP, then removes it when the time window ends.

This post covers enabling JIT on a VM, requesting access from a script and the reasons a request "succeeds" but the connection still times out.

Tip

If nobody should reach the VM from the internet at all, Azure Bastion or a private path over VPN/ExpressRoute is a better fit. JIT suits VMs that already sit behind a public IP or a shared admin subnet that you can't remove yet.

Prerequisites

Requirement Why it matters
Defender for Servers Plan 2 on the subscription JIT isn't included in Plan 1
Resource Manager VM (not classic) Classic VMs aren't supported
NSG on the NIC or subnet, or an Azure Firewall in the path JIT works by writing NSG rules or firewall rules. With neither, it has nothing to change
RBAC to configure: write on Microsoft.Security/locations/jitNetworkAccessPolicies Security Admin or Contributor on the scope
RBAC to request: Microsoft.Security/locations/jitNetworkAccessPolicies/initiate/action, plus read on the VM and its NIC Give admins a custom role with these actions so they don't need Contributor

Check the plan first:

Get-AzSecurityPricing -Name VirtualMachines | Select-Object Name, PricingTier, SubPlan

PricingTier should be Standard and SubPlan should be P2.

Enable JIT on a VM

The portal is the quickest way to enable JIT on a single VM: VM > Configuration > Just-in-time VM access > Enable. To roll it out across many VMs, script it with Set-AzJitNetworkAccessPolicy. One policy per resource group and region is common, usually named default. The policy lists every VM it protects.

$sub = (Get-AzContext).Subscription.Id
$rg  = "rg-prod-app"
$loc = "westeurope"
$vm  = "vm-app-01"

$vmRule = @{
  id    = "/subscriptions/$sub/resourceGroups/$rg/providers/Microsoft.Compute/virtualMachines/$vm"
  ports = @(
    @{ number = 3389; protocol = "*"; allowedSourceAddressPrefix = @("203.0.113.0/24"); maxRequestAccessDuration = "PT3H" },
    @{ number = 22;   protocol = "*"; allowedSourceAddressPrefix = @("203.0.113.0/24"); maxRequestAccessDuration = "PT3H" }
  )
}

Set-AzJitNetworkAccessPolicy -Kind "Basic" -Location $loc -Name "default" `
  -ResourceGroupName $rg -VirtualMachine @($vmRule)
  • allowedSourceAddressPrefix sets which source ranges a request may ask for. Keep it to your admin egress ranges, not *.
  • maxRequestAccessDuration is an ISO 8601 duration. PT3H is three hours, which is also the portal default.
  • The policy name plus the VM name must stay within 56 characters.

Warning

Set-AzJitNetworkAccessPolicy replaces the VM list in the policy. If default already protects other VMs in the resource group, read it first with Get-AzJitNetworkAccessPolicy, add your VM to the existing VirtualMachines array and write the whole list back. If you send only the new VM, every other VM drops out of JIT and the deny rules on its ports are removed.

List what is already protected:

Get-AzJitNetworkAccessPolicy |
  Select-Object Name, ResourceGroupName, Location,
    @{n='VMs';e={ ($_.VirtualMachines.Id | ForEach-Object { ($_ -split '/')[-1] }) -join ', ' }}

Then check the NSG. You should see new deny rules for the configured ports, added at a higher priority than your existing allow rules:

az network nsg rule list -g rg-prod-app --nsg-name nsg-vm-app-01 \
  --query "[?contains(name,'JIT')].{name:name,priority:priority,access:access,ports:destinationPortRange,src:sourceAddressPrefix}" -o table

Rule names vary by version, so if that filter returns nothing, list all rules and sort them by priority.

Request access

Admins can click Connect > Request access in the portal. For scripts and break-glass runbooks, use Start-AzJitNetworkAccessPolicy:

$myIp = (Invoke-RestMethod -Uri "https://api.ipify.org")   # or your known egress IP
$end  = (Get-Date).ToUniversalTime().AddHours(2).ToString("o")

$req = @{
  id    = "/subscriptions/$sub/resourceGroups/$rg/providers/Microsoft.Compute/virtualMachines/$vm"
  ports = @(@{ number = 3389; endTimeUtc = $end; allowedSourceAddressPrefix = @($myIp) })
}

Start-AzJitNetworkAccessPolicy `
  -ResourceId "/subscriptions/$sub/resourceGroups/$rg/providers/Microsoft.Security/locations/$loc/jitNetworkAccessPolicies/default" `
  -VirtualMachine @($req)

If your team only uses the Azure CLI, call the same REST action with az rest:

SUB=$(az account show --query id -o tsv)
RG=rg-prod-app; LOC=westeurope; VM=vm-app-01
MYIP=$(curl -s https://api.ipify.org)
END=$(date -u -d '+1 hour' +%Y-%m-%dT%H:%M:%SZ)

az rest --method post \
  --url "https://management.azure.com/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.Security/locations/$LOC/jitNetworkAccessPolicies/default/initiate?api-version=2020-01-01" \
  --body "{\"virtualMachines\":[{\"id\":\"/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.Compute/virtualMachines/$VM\",\"ports\":[{\"number\":22,\"endTimeUtc\":\"$END\",\"allowedSourceAddressPrefix\":\"$MYIP\"}]}],\"justification\":\"INC0012345 patching\"}"

The request adds an allow rule above the JIT deny rule for your IP and port. When the window ends, JIT removes that allow rule.

Requests that succeed but you still can't connect

Symptom Likely cause Fix
Request accepted, RDP/SSH times out The IP you requested isn't the IP Azure sees. Proxies, a VPN split tunnel or carrier NAT change your source IP Get your IP from the network you'll connect from, or request a range your egress NAT falls into
Allow rule is on the NIC NSG, but the subnet NSG still blocks Both NSGs are evaluated, and inbound traffic must pass the subnet NSG and the NIC NSG Check effective rules (below) and make sure the subnet NSG allows the admin range, or let JIT manage the NSG that does the blocking
AuthorizationFailed on initiate The admin's role doesn't include .../jitNetworkAccessPolicies/initiate/action Add the action to the custom role at the resource group scope
Request rejected for the port or IP The port isn't in the policy, or the IP is outside allowedSourceAddressPrefix, or the duration is longer than the maximum Request within the policy, or update the policy
Works, then stops mid-session The time window expired Make a new request. Existing sessions may drop when the rule is removed
JIT rules disappear An IaC pipeline or Azure Policy resets the NSG to its declared state Exclude JIT-managed rules from drift checks, or let JIT own those NSGs
VM behind Azure Firewall, port still closed JIT opened the NSG, but the firewall has no matching DNAT rule On the JIT page in Defender for Cloud, check whether the firewall is listed as managed by JIT. If it isn't, add the DNAT rule through your normal firewall change process

Show what is actually applied to the NIC. This command lists the merged subnet and NIC rules:

NIC=$(az vm show -g rg-prod-app -n vm-app-01 --query "networkProfile.networkInterfaces[0].id" -o tsv)
az network nic list-effective-nsg --ids "$NIC" -o json \
  | jq -r '.value[].effectiveSecurityRules[] | select(.destinationPortRange|test("3389|22")) | [.name,.access,.priority,.sourceAddressPrefix] | @tsv'

Then run IP flow verify to confirm the 5-tuple:

az network watcher test-ip-flow -g rg-prod-app --vm vm-app-01 \
  --direction Inbound --protocol TCP \
  --local 10.20.1.4:3389 --remote 198.51.100.25:50000

Access: Allow with the JIT rule name means the NSG isn't the problem. Next, check the guest firewall and whether the RDP or SSH service is running.

Audit who opened what

Every request is logged in the Activity Log. Search for the initiate operation:

AzureActivity
| where TimeGenerated > ago(30d)
| where OperationNameValue =~ "MICROSOFT.SECURITY/LOCATIONS/JITNETWORKACCESSPOLICIES/INITIATE/ACTION"
| project TimeGenerated, Caller, CallerIpAddress, ActivityStatusValue, ResourceGroup, _ResourceId
| order by TimeGenerated desc

Or use the CLI for a quick look:

az monitor activity-log list --resource-group rg-prod-app --offset 7d \
  --query "[?contains(operationName.value,'jitNetworkAccessPolicies/initiate')].{time:eventTimestamp,caller:caller,status:status.value}" -o table

Prevent it next time

  • Assign the built-in Defender for Cloud recommendation "Management ports of virtual machines should be protected with just-in-time network access control" and review it weekly.
  • Remove any standing Allow 3389/22 from Internet rules after you enable JIT. A standing allow rule with a higher priority than the JIT deny rule defeats it.
  • Give admins a narrow custom role that can only initiate requests, and keep the configure permission with the security team.
  • Script policy changes with read-modify-write. Never send a partial VM list.
  • Set maxRequestAccessDuration to the shortest window that works for patching. One to three hours is typical.