Just-in-time VM access with Defender for Cloud

Just-in-time VM access keeps management ports like 22 and 3389 shut all the time and opens them only when someone asks, only for that person’s IP and only for a few hours. It’s a feature of Microsoft Defender for Cloud.

Bastion (Lesson 27) is the best way to give admins access, but plenty of companies still run VMs with public IPs: vendor appliances, legacy apps, or servers that are reached by tools which can’t go through Bastion. JIT is how you protect those ones.

You’ll switch on the Defender plan that JIT needs, protect web01 and open SSH for one hour from your own IP, and after that you’ll see the two ways JIT can fail without telling you.

TimeYou needCostBy the end you can
About 45 minutesweb01, the CLI, a subscription that can start the Defender for Servers trialAbout 1 US cent for a temporary public IP, if the Defender for Servers Plan 2 trial is active; without the trial, Plan 2 costs about 2 US cents per VM-hourEnable JIT, request and audit access, and spot rules that bypass it

What it is, in one line

Just-in-time VM access opens a management port for one IP and a fixed time, and closes it again on its own.

In Simple Words

The school gate during class hours

The school gate stays locked all day. When a parent needs to come in, they ring the office and say who they are and why, and the guard opens the gate for that one parent for twenty minutes. Once the twenty minutes are up the gate locks again, even if the parent forgot to say goodbye, and the office book shows who came, when and why.

But if a teacher props the side door open with a chair, the locked gate stops mattering. That chair is the second break in today’s lab.

Engineer's View

How JIT works under the hood

  • Licence: JIT comes with Defender for Servers Plan 2, which costs about USD 15 per server per month once the 30-day trial ends. Plan 1 doesn’t have it.
  • Policy: for each VM you list the ports (say 22 and 3389), the protocol, which source addresses people are allowed to request, and the longest time anyone can ask for (up to 24 hours).
  • Enforcement: Defender puts deny rules for those ports on the NSGs attached to the VM’s NIC and subnet, and on Azure Firewall if you use it. It doesn’t remove anything, so rules that already allow those ports keep winning.
  • Request: a user who has the right RBAC action (Microsoft.Security/locations/jitNetworkAccessPolicies/initiate/action) asks for a port, a source IP and a duration. Defender then adds an allow rule above the deny and takes it away when the time runs out.
  • Audit: each request is written to the Activity log along with who asked, the ports, the source IP and the reason they gave.
  • API: Microsoft.Security/locations/{region}/jitNetworkAccessPolicies, version 2020-01-01. The CLI can list the policies, and for everything else you use az rest.

How it works, step by step

What happens to the NSG during one JIT request:

Just-in-time VM access: what happens to the NSG during a request
  1. Policy saved: Defender writes “deny 22 from any” for web01’s IP into nsg-saat-web.
  2. Request: you ask for 22 from your IP for one hour, and give a reason.
  3. Allow rule: Defender adds “allow 22 from your IP” at a higher priority than its own deny rule.
  4. Work: you SSH in, and anyone else still runs into the deny rule.
  5. Expiry: after the hour is up, Defender deletes the allow rule and leaves the deny rule in place.

JIT only looks after the ports in its policy. The rest of the NSG is your job, and that includes old rules that already allow the same ports.

Just-in-time VM access bypassed by an older NSG allow rule

Use both where you can: Bastion for your admins, and JIT only on the handful of VMs that really need a public management port.

Hands-on lab: just-in-time VM access for web01

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

First, set the names you’ll be using:

$sub = az account show --query id -o tsv
$vmId = az vm show --resource-group rg-saat-vms --name web01 --query id -o tsv
$jit = "https://management.azure.com/subscriptions/$sub/resourceGroups/rg-saat-vms/providers/Microsoft.Security/locations/centralindia/jitNetworkAccessPolicies/default"
$ip = Invoke-RestMethod -Uri https://api.ipify.org
az vm start --resource-group rg-saat-vms --name web01

1Turn on Defender for Servers Plan 2

Run this:

az security pricing create --name VirtualMachines --tier Standard --subplan P2 -o none
az security pricing show --name VirtualMachines --query "{tier:pricingTier, plan:subPlan, trialLeft:freeTrialRemainingTime}" -o table

You should see something like this:

Tier      Plan    TrialLeft
--------  ------  -----------
Standard  P2      29.23:59:00

If TrialLeft shows zero, your subscription has already used up its trial and Plan 2 is charged per VM-hour. You’ll turn it off again at the end.

2Give web01 a temporary public IP

JIT is meant for VMs that are reached over a public IP, so give the VM one for this lesson only:

az network public-ip create --resource-group rg-saat-vms --name pip-web01-tmp --sku Standard --location centralindia --tags course=saatvedha-azure lesson=28 -o none
$nic = az vm show --resource-group rg-saat-vms --name web01 --query "networkProfile.networkInterfaces[0].id" -o tsv
$ipc = az network nic show --ids $nic --query "ipConfigurations[0].id" -o tsv
az network nic ip-config update --ids $ipc --public-ip-address pip-web01-tmp -o none
$pip = az network public-ip show --resource-group rg-saat-vms --name pip-web01-tmp --query ipAddress -o tsv
(Test-NetConnection -ComputerName $pip -Port 22 -WarningAction SilentlyContinue).TcpTestSucceeded

You should see this:

False

Port 22 is closed already, because nsg-saat-web only lets 80 and 443 in from the internet. What JIT adds is a closure that’s explicit and shows up in an audit.

3Create the JIT policy for web01

Run this:

$policy = @{ kind = 'Basic'; properties = @{ virtualMachines = @(@{ id = $vmId; ports = @(@{ number = 22; protocol = 'TCP'; allowedSourceAddressPrefix = '*'; maxRequestAccessDuration = 'PT3H' }) }) } }
$policy | ConvertTo-Json -Depth 6 | Set-Content -Path C:\azure-lab\jit-policy.json
az rest --method put --url "${jit}?api-version=2020-01-01" --body '@C:\azure-lab\jit-policy.json' -o none
Start-Sleep -Seconds 60
az network nsg rule list --resource-group rg-saat-core --nsg-name nsg-saat-web --query "[?contains(name, 'JIT')].{name:name, access:access, port:destinationPortRange, priority:priority}" -o table

You should see something like this:

Name                                           Access    Port    Priority
---------------------------------------------  --------  ------  ----------
SecurityCenter-JITRule-1347516193-B4FC8A3BAB   Deny      22      4096

4Request access for one hour

Ask for port 22 from the public IP you’re on right now:

$req = @{ virtualMachines = @(@{ id = $vmId; ports = @(@{ number = 22; duration = 'PT1H'; allowedSourceAddressPrefix = $ip }) }); justification = 'Lesson 28 test' }
$req | ConvertTo-Json -Depth 6 | Set-Content -Path C:\azure-lab\jit-request.json
az rest --method post --url "${jit}/initiate?api-version=2020-01-01" --body '@C:\azure-lab\jit-request.json' --query "virtualMachines[0].ports[0].{port:number, source:allowedSourceAddressPrefix, status:status}" -o table
Start-Sleep -Seconds 60
(Test-NetConnection -ComputerName $pip -Port 22 -WarningAction SilentlyContinue).TcpTestSucceeded
ssh azureuser@$pip hostname

You should see something like this:

Port    Source         Status
------  -------------  ---------
22      49.36.x.x      Initiated
True
web01

Defender has put an allow rule for your IP above its deny rule, and in an hour it will take it away again without you doing anything.

Defender for Cloud just-in-time VM access configured tab
Just-in-time VM access, Configured tab: web01 with an active request.
Just-in-time VM access lab: port 22 closed, requested, then open for one IP
Port 22 closed, a JIT request for one IP, then SSH works.

✅ Checkpoint: web01 is protected by JIT, your request opened port 22 for your IP only, and SSH works until the time runs out.

Break It, Then Fix It

JIT hardly ever fails with an error message. It fails silently, and that’s worse.

1Break it: the request for the wrong IP

A colleague puts in the request with the office IP while you’re working from home:

$req = @{ virtualMachines = @(@{ id = $vmId; ports = @(@{ number = 22; duration = 'PT1H'; allowedSourceAddressPrefix = '203.0.113.10' }) }); justification = 'Lesson 28 test' }
$req | ConvertTo-Json -Depth 6 | Set-Content -Path C:\azure-lab\jit-request.json
az rest --method post --url "${jit}/initiate?api-version=2020-01-01" --body '@C:\azure-lab\jit-request.json' --query "virtualMachines[0].ports[0].{port:number, source:allowedSourceAddressPrefix, status:status}" -o table
Start-Sleep -Seconds 60
az network nsg rule list --resource-group rg-saat-core --nsg-name nsg-saat-web --query "[?access=='Allow' && destinationPortRange=='22'].sourceAddressPrefix" -o tsv

You should see something like this:

Port    Source         Status
------  -------------  ---------
22      203.0.113.10   Initiated
49.36.x.x
203.0.113.10

The request “worked” and Defender shows it as approved. But if your first request had already expired, Test-NetConnection on your laptop would return False, because the allow rule is for an address you aren’t using. Home internet IPs also change, sometimes a few times a day, and you get the same “JIT is broken” ticket.

Fix it: always request with the public IP you’re on now (the “My IP” option in the portal does that for you), and check what the server sees:

$ip = Invoke-RestMethod -Uri https://api.ipify.org
$req = @{ virtualMachines = @(@{ id = $vmId; ports = @(@{ number = 22; duration = 'PT1H'; allowedSourceAddressPrefix = $ip }) }); justification = 'Lesson 28 test' }
$req | ConvertTo-Json -Depth 6 | Set-Content -Path C:\azure-lab\jit-request.json
az rest --method post --url "${jit}/initiate?api-version=2020-01-01" --body '@C:\azure-lab\jit-request.json' --query "virtualMachines[0].ports[0].{port:number, source:allowedSourceAddressPrefix, status:status}" -o table

2Break it: the old rule that makes JIT useless

Someone adds a “temporary” rule to sort out a vendor problem and then forgets about it:

az network nsg rule create --resource-group rg-saat-core --nsg-name nsg-saat-web --name tmp-vendor-ssh --priority 150 --direction Inbound --access Allow --protocol Tcp --source-address-prefixes Internet --destination-port-ranges 22 -o none
az network nsg rule list --resource-group rg-saat-core --nsg-name nsg-saat-web --query "[?destinationPortRange=='22'].{name:name, access:access, source:sourceAddressPrefix, priority:priority}" -o table

You should see something like this:

Name                                           Access    Source        Priority
---------------------------------------------  --------  ------------  ----------
tmp-vendor-ssh                                 Allow     Internet      150
SecurityCenter-JITRule-1347516193-B4FC8A3BAB   Allow     49.36.x.x     100
SecurityCenter-JITRule-...                     Allow     203.0.113.10  101
SecurityCenter-JITRule-1347516193-B4FC8A3BAB   Deny      *             4096

At priority 150 that rule sits far above JIT’s deny at 4096, so port 22 is open to the whole internet whether anyone has requested access or not. Defender doesn’t delete rules it didn’t create. Its recommendations will flag the open port, but JIT itself looks perfectly healthy.

Fix it: delete the rule, and then look for any other allow rules on the JIT ports:

az network nsg rule delete --resource-group rg-saat-core --nsg-name nsg-saat-web --name tmp-vendor-ssh
az network nsg rule list --resource-group rg-saat-core --nsg-name nsg-saat-web --query "[?destinationPortRange=='22' && access=='Allow' && !contains(name, 'JIT')].name" -o tsv

If the last command prints nothing, JIT is once again the only thing controlling port 22.

To clean up, remove the JIT policy, the public IP and the Defender plan, and then stop web01:

az rest --method delete --url "${jit}?api-version=2020-01-01"
az network nic ip-config update --ids $ipc --remove publicIPAddress -o none
az network public-ip delete --resource-group rg-saat-vms --name pip-web01-tmp
az security pricing create --name VirtualMachines --tier Free -o none
az vm deallocate --resource-group rg-saat-vms --name web01
az network nsg rule list --resource-group rg-saat-core --nsg-name nsg-saat-web --query "[?contains(name, 'JIT')].name" -o tsv
C:\azure-lab\Find-LabResources.ps1 -Lesson 28

You should see this (the rule list can take a minute to clear):

Nothing tagged course=saatvedha-azure is left.
Just-in-time VM access problems: wrong source IP and a bypass rule
An approved request for the wrong IP, and an old rule that opens the port anyway.

✅ Checkpoint: No JIT rules, no public IP and no tmp rule remain, Defender for Servers is back on Free, and web01 is deallocated.

This happened at work

JIT was on, and the server was still attacked

A logistics company had JIT switched on for all 120 VMs and had passed its security audit. Three months later, one of its Windows servers with a public IP got hit by a password-spraying attack over RDP.

When the team dug in, they found an NSG rule called “allow-rdp-vendor” at priority 200, put there two years earlier for a printer vendor. JIT’s deny rule was at 4096, underneath it, so RDP had been open to the internet the whole time while the JIT dashboard happily showed the VM as protected.

What they changed: an Azure Policy now denies NSG rules that allow 22 or 3389 from Internet or Any, unless Defender created them. A weekly Resource Graph query lists every allow rule on a management port, and the audit checklist now asks “what else allows this port?” as well as “is JIT enabled?”.

Common mistakes and troubleshooting

MistakeWhat you seeWhat to do
Old allow rules on JIT portsPort open without any requestDelete them, because JIT leaves existing rules alone.
Requesting with the wrong source IPJIT approved, connection still failsUse “My IP” or check your public IP first.
Defender for Servers Plan 1 onlyJIT option missingJIT needs Plan 2.
VM without an NSGJIT can’t be enabledAttach an NSG to the NIC or subnet.
Using JIT instead of Bastion everywherePublic IPs on many VMsBastion for admins; JIT only where needed.
Leaving the Plan 2 trial running after labsCharges after 30 daysSwitch the plan back to Free.

Interview questions

Click any question to open it. They’re worded the way an interviewer would ask them, and under each one you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. What is just-in-time VM access?

Why they ask this: To see if you know the basic idea.

How you might answer: It’s a Defender for Cloud feature. It keeps management ports closed with NSG deny rules and only opens them when someone asks, for one source IP and for a limited time.

2. Which licence does JIT need?

Why they ask this: It’s a prerequisite people trip over in practice.

How you might answer: You need Microsoft Defender for Servers Plan 2, on the subscription or on the servers. Plan 1 doesn’t include JIT.

3. What happens when a JIT request expires?

Why they ask this: They want to see that you know it happens on its own.

How you might answer: Defender takes away the allow rule it added, and the deny rule closes the port again. Nobody has to remember to do it.

2–5 years experience

4. JIT shows access approved, but the user still can’t connect. What do you check?

Why they ask this: It’s one of the most common support tickets.

How you might answer: First I’d check that the source IP in the request matches the user’s real public IP, because changing home IPs are usually the cause. Then I’d confirm the allow rule is in the NSG, look at any other NSG on the NIC or subnet, the OS firewall, and whether the VM is listening at all.

5. How does JIT work with existing NSG rules?

Why they ask this: They’re checking you know how JIT gets bypassed.

How you might answer: JIT adds deny rules for its ports, but it doesn’t remove the rules that are already there. So an older allow rule with a higher priority still lets traffic in, and JIT looks enabled while the port is wide open.

6. JIT or Bastion: which do you recommend?

Why they ask this: They want to hear your judgement.

How you might answer: For day-to-day admin access I’d go with Bastion, because then the VMs don’t need a public IP at all. JIT is for the few VMs that have to keep a public IP, or where some tool needs a direct connection. Plenty of companies use both.

Senior level

7. How would you roll out JIT across hundreds of VMs?

Why they ask this: They want to hear about automation and governance.

How you might answer: I’d enable Plan 2 through policy and create the JIT policies per resource group with ARM, Bicep or the REST API, with maximum durations set. Then I’d add a policy that denies any other allow rules on management ports, give the on-call groups the initiate action through PIM, and set up alerts on JIT requests.

8. How do you audit who opened which port and when?

Why they ask this: They’re checking whether you know where the logs live.

How you might answer: JIT requests show up in the Activity log under Microsoft.Security jitNetworkAccessPolicies initiate, with the user, ports, source IP and justification. I’d export the Activity log to Log Analytics and keep it for as long as the audit period needs.

9. What are JIT’s limits?

Why they ask this: They want you to be honest about what the tool can’t do.

How you might answer: It only controls the ports in its policy and it relies on NSGs or Azure Firewall, so other rules can get around it. It won’t stop someone who already has a session, and it still needs a public path, which Bastion avoids.

Quick quiz

Q1. Which Defender plan includes JIT?

  1. Foundational CSPM only
  2. Defender for Servers Plan 1
  3. Defender for Servers Plan 2
  4. Defender for Storage
Show answer

C — JIT is part of Plan 2.

Q2. What does JIT add to the NSG when the policy is saved?

  1. Allow rules
  2. Deny rules for the chosen ports
  3. Nothing
  4. A public IP
Show answer

B — Deny rules keep the ports closed until requested.

Q3. An old rule allows 22 at priority 150; JIT deny is at 4096. Result?

  1. Port closed
  2. Port open to the rule’s sources
  3. JIT deletes the old rule
  4. The VM stops
Show answer

B — The lower number wins, so the old allow rule bypasses JIT.

Q4. When a JIT request expires, Defender:

  1. Deletes the VM
  2. Removes its allow rule
  3. Rotates keys
  4. Turns off the NSG
Show answer

B — The allow rule is removed automatically.

Q5. Where are JIT requests audited?

  1. Activity log
  2. Boot diagnostics
  3. Storage logs
  4. Nowhere
Show answer

A — Each request is recorded in the Activity log.

Quick recap

You can now open a management port safely and show that it closes again.

  • JIT needs Defender for Servers Plan 2.
  • The policy adds deny rules; requests add timed allow rules for one IP.
  • Old allow rules with higher priority bypass JIT.
  • Request with your current public IP.
  • Bastion first; JIT for the VMs that must keep a public IP.

Next lesson

Lesson 29: VM tools: Run Command, extensions, Custom Script → Next, you manage VMs from outside the OS with Run Command and extensions, and sort out a stuck extension.

Further reading: just-in-time VM access

Want to go deeper into just-in-time VM access? Microsoft’s Understand just-in-time VM access and Enable just-in-time access on VMs are good next reads, and the full plan for this course is on the Azure Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.