Theoretical Foundation: Evaluate Effective Security Rules in NSGs
1. Initial Intuitionβ
Imagine you work in a corporate building with two security checkpoints: the first at the floor entrance and the second at the specific office door. Each checkpoint has its own list of rules. To reach your desk, you need to pass through both checkpoints. If either one blocks you, you can't enter.
Now imagine you need to explain to someone why they can't enter the office. You would need to consult both rule lists simultaneously, in the order they are checked, to find exactly which rule is blocking access.
Effective Security Rules is the Azure tool that does exactly this: it consolidates and displays, in a single ordered view, all the rules from all NSGs that apply to a specific network interface, both subnet NSG rules and NIC NSG rules. It's the definitive diagnostic to understand the actual security behavior of a VM.
2. Contextβ
2.1 Why Effective Security Rules existsβ
In the previous module about NSGs, we saw that a traffic flow can be evaluated by up to two NSGs simultaneously: one associated with the subnet and another associated with the NIC. Each NSG can have dozens of rules, including default rules and custom rules.
When an administrator needs to answer "why is traffic on port 8080 being blocked for this VM?", looking at the two NSGs separately and mentally combining the rules is complex, error-prone, and slow.
Effective Security Rules solves this by automatically computing the consolidated and ordered view of all rules that actually apply to inbound and outbound traffic for a specific NIC.
2.2 Complementary tools in the ecosystemβ
3. Building the Conceptsβ
3.1 What exactly are Effective Security Rulesβ
The Effective Security Rules of a NIC are the result of combining and ordering all rules from all NSGs that apply to it:
- Rules from the NSG associated with the subnet where the VM is located
- Rules from the NSG directly associated with the NIC
- Default rules from each NSG (the three rules with priority 65000-65500)
The combination results in a single list, separated by direction (inbound and outbound), ordered by priority. The evaluation logic for inbound traffic is:
- Subnet NSG is evaluated first
- If allowed, NIC NSG is evaluated
- If both allow, traffic passes
- If either denies, traffic is blocked
Effective Security Rules doesn't "merge" the two NSGs into one. It displays rules from each NSG separately, but organized so you understand which is evaluated first and in what context.
3.2 What is displayed in Effective Security Rulesβ
The visualization shows, for each rule, the following fields:
| Field | Description |
|---|---|
| Priority | Rule priority number (lower = higher priority) |
| Name | Rule name |
| Port | Destination port(s) |
| Protocol | TCP, UDP, ICMP or Any |
| Source | Source IP, CIDR, Service Tag or ASG |
| Destination | Destination IP, CIDR, Service Tag or ASG |
| Action | Allow or Deny |
| Source (NSG) | Indicates which NSG the rule comes from (subnet NSG or NIC NSG) |
This last field is crucial: it allows you to identify whether the rule comes from the subnet NSG or NIC NSG, which is essential for knowing where to make corrections.
3.3 Evaluation order: inbound vs outboundβ
The NSG evaluation order changes depending on traffic direction:
3.4 IP Flow Verify: the practical complementβ
While Effective Security Rules shows all rules, IP Flow Verify answers a specific question: "if a packet comes from IP X, port Y, to my VM on port Z, would it be allowed or denied, and by which rule?"
IP Flow Verify simulates the evaluation process for a specific flow and returns:
- Whether the flow would be Allowed or Denied
- The exact name of the rule that made the decision
- The NSG that contains that rule
This is the most direct tool for specific connectivity diagnosis.
3.5 Connection Troubleshoot: end-to-end diagnosisβ
Connection Troubleshoot goes beyond NSGs: it verifies complete connectivity between two endpoints, considering routes, firewalls within VMs, and NSGs. It returns:
- Connection status (Reachable/Unreachable)
- Latency and hop count
- Which component is causing the problem (NSG, route, VM firewall)
4. Structural Viewβ
4.1 Complete diagnosis scenarioβ
5. Practical Operationβ
5.1 Accessing Effective Security Rules in the Portalβ
Path 1: Via VM NIC
VM > Settings > Networking > Inbound/Outbound port rules > Effective security rules
Path 2: Via NIC directly
Network Interfaces > [NIC] > Support + troubleshooting > Effective security rules
Path 3: Via Network Watcher
Network Watcher > Network diagnostic tools > NSG diagnostics
The interface displays two sections:
- Inbound rules (with subsections for subnet NSG and NIC NSG)
- Outbound rules (with subsections for NIC NSG and subnet NSG, in that order)
5.2 Interpreting the resultβ
Consider this scenario: a VM has two associated NSGs.
Subnet NSG (NSG-WebSubnet):
| Priority | Name | Source | Dest Port | Action |
|---|---|---|---|---|
| 100 | Allow-HTTPS | Internet | 443 | Allow |
| 200 | Allow-HTTP | Internet | 80 | Allow |
| 65000 | AllowVnetInBound | VirtualNetwork | * | Allow |
| 65001 | AllowAzureLBInBound | AzureLoadBalancer | * | Allow |
| 65500 | DenyAllInBound | * | * | Deny |
NIC NSG (NSG-VM01-NIC):
| Priority | Name | Source | Dest Port | Action |
|---|---|---|---|---|
| 100 | Deny-SSH | * | 22 | Deny |
| 65000 | AllowVnetInBound | VirtualNetwork | * | Allow |
| 65001 | AllowAzureLBInBound | AzureLoadBalancer | * | Allow |
| 65500 | DenyAllInBound | * | * | Deny |
Question: An external client attempts SSH (port 22) to the VM. What happens?
Analysis with Effective Security Rules:
-
Subnet NSG evaluates first. Port 22 is not covered by rules 100 or 200.
AllowVnetInBound(65000) covers VirtualNetwork as source, but this traffic comes from Internet. TheDenyAllInBound(65500) blocks... but wait: there's no explicit Deny rule before 65500 for port 22 in the subnet NSG. -
Actually,
AllowVnetInBounddoesn't apply (source is Internet, not VirtualNetwork). Traffic reaches rule 65500 (DenyAllInBound) and would be blocked. -
Result: Blocked by subnet NSG before even reaching the NIC NSG.
Now imagine the subnet NSG had allowed SSH:
If the subnet NSG had Allow SSH from Internet with priority 150, traffic would pass through the subnet NSG. Then the NIC NSG would evaluate: its rule 100 (Deny-SSH) would block the traffic. The final result would be Deny, but now by the NIC NSG.
This distinction matters because corrections are in different NSGs.
5.3 Using IP Flow Verifyβ
IP Flow Verify is in Network Watcher and requires:
- VM destination (or source for outbound)
- Direction: Inbound or Outbound
- Protocol: TCP or UDP
- Local IP and Port: VM's local IP and port
- Remote IP and Port: External client IP and port
The result returns:
Access: Denied
Rule Name: DenyAllInBound
Rule Priority: 65500
NSG Name: NSG-WebSubnet
NSG Resource Group: myRG
This precise result eliminates the need to manually analyze all rules.
6. Implementation Methodsβ
6.1 Azure Portalβ
When to use: Visual diagnosis, interactive troubleshooting, when you need to navigate through rules and understand the complete context.
Effective Security Rules:
Navigate to VM > Networking > Effective security rules. The interface shows rules in tabular format with filters by direction.
IP Flow Verify:
Network Watcher > IP Flow Verify
Fill in the fields and get immediate results.
Limitation: Not scriptable, doesn't generate bulk reports for multiple VMs.
6.2 Azure CLIβ
Listing Effective Security Rules via CLI:
# Identify VM's NIC name
az vm show \
--resource-group myRG \
--name myVM \
--query "networkProfile.networkInterfaces[].id" \
--output tsv
# Get effective security rules for the NIC
az network nic show-effective-nsg \
--name myVM-NIC \
--resource-group myRG \
--output json
The JSON output contains two arrays: effectiveNetworkSecurityGroups for applied rules, with the source of each rule (subnet NSG or NIC NSG).
Example output parsing:
# List only effective Deny rules
az network nic show-effective-nsg \
--name myVM-NIC \
--resource-group myRG \
--query "effectiveNetworkSecurityGroups[].effectiveSecurityRules[?access=='Deny'].{Name:name, Priority:priority, Direction:direction, Port:destinationPortRange}" \
--output table
IP Flow Verify via CLI:
az network watcher test-ip-flow \
--resource-group myRG \
--vm myVM \
--direction Inbound \
--protocol TCP \
--local 10.0.1.4:22 \
--remote 203.0.113.1:* \
--out table
Output:
Access DirectionEnum RuleName TargetNicId
-------- --------------- ----------------- ------------
Deny Inbound Deny-SSH /subscriptions/.../networkInterfaces/myVM-NIC
Connection Troubleshoot via CLI:
az network watcher test-connectivity \
--resource-group myRG \
--source-resource myVM \
--dest-address 10.0.2.5 \
--dest-port 1433 \
--protocol Tcp
6.3 Azure PowerShellβ
# Effective Security Rules
$nic = Get-AzNetworkInterface `
-Name "myVM-NIC" `
-ResourceGroupName "myRG"
$effectiveNSG = Get-AzEffectiveNetworkSecurityGroup `
-NetworkInterfaceName "myVM-NIC" `
-ResourceGroupName "myRG"
# View inbound Deny rules
$effectiveNSG.EffectiveNetworkSecurityGroups |
ForEach-Object { $_.EffectiveSecurityRules } |
Where-Object { $_.Access -eq "Deny" -and $_.Direction -eq "Inbound" } |
Select-Object Name, Priority, SourcePortRange, DestinationPortRange |
Sort-Object Priority
# IP Flow Verify
$networkWatcher = Get-AzNetworkWatcher `
-ResourceGroupName "NetworkWatcherRG" `
-Name "NetworkWatcher_eastus"
$vm = Get-AzVM `
-ResourceGroupName "myRG" `
-Name "myVM"
Test-AzNetworkWatcherIPFlow `
-NetworkWatcher $networkWatcher `
-TargetVirtualMachineId $vm.Id `
-Direction Inbound `
-Protocol TCP `
-RemoteIPAddress "203.0.113.1" `
-LocalIPAddress "10.0.1.4" `
-LocalPort "22" `
-RemotePort "12345"
6.4 NSG Diagnostics in Network Watcher (Portal)β
A more complete tool than basic IP Flow Verify:
Network Watcher > NSG diagnostics
Allows you to specify:
- Target VM or NIC
- Protocol, source IP, destination IP, port
Returns not only Allow/Deny, but also which NSGs were evaluated, in what order, and which specific rule made the final decision. Visually displays the evaluation path.
7. Control and Securityβ
7.1 Required permissionsβ
| Operation | Minimum role |
|---|---|
| View Effective Security Rules | Network Contributor or Reader with Network Watcher Reader |
| Use IP Flow Verify | Network Watcher Contributor |
| Use Connection Troubleshoot | Network Watcher Contributor |
| Modify NSG rules after diagnosis | Network Contributor |
7.2 NSG change auditingβ
Whenever an NSG change is needed after diagnosis, it should be documented and audited:
# View NSG change history via Activity Log
az monitor activity-log list \
--resource-group myRG \
--caller "user@company.com" \
--start-time "2025-01-01T00:00:00Z" \
--query "[?contains(operationName.value, 'networkSecurityGroups')].{Time:eventTimestamp, Operation:operationName.value, Status:status.value}" \
--output table
7.3 Diagnosis pitfallsβ
Pitfall 1: Correct rule in wrong NSG
An administrator adds Allow SSH to the NIC NSG but forgets that the Subnet NSG has Deny SSH with lower priority (higher precedence). For inbound, the subnet NSG is evaluated first and blocks before even reaching the NIC NSG.
Pitfall 2: Outbound rules in wrong NSG
For outbound traffic, the NIC NSG is evaluated first. A rule in the Subnet NSG has no effect if the NIC NSG already denied the traffic.
Pitfall 3: Traffic allowed by NSG but blocked inside VM
Effective Security Rules and IP Flow Verify only analyze NSGs. If Windows Firewall or iptables inside the VM is blocking, these tools will return "Allowed" but traffic still won't reach the service.
8. Decision Makingβ
8.1 Which tool to use for each scenarioβ
| Situation | Tool | Reason |
|---|---|---|
| "Which rules apply to this VM?" | Effective Security Rules | Complete view of all rules |
| "Why is port 8080 blocked for this IP?" | IP Flow Verify | Direct diagnosis for specific flow |
| "Can the VM connect to the database?" | Connection Troubleshoot | End-to-end test with connectivity response |
| "Which route is traffic using?" | Next Hop | Routing diagnosis |
| "Traffic reaches VM but application doesn't respond?" | Packet Capture | Packet analysis within the network |
| "Multiple VMs with issues, need bulk analysis" | CLI + az network nic show-effective-nsg | Scriptable and automatable |
8.2 When subnet NSG is sufficient vs when NIC NSG is necessaryβ
| Situation | Approach |
|---|---|
| Rule that should apply to all VMs in subnet | Subnet NSG |
| Exception for specific VM (more permissive) | NIC NSG with Allow rule of lower priority than subnet Deny |
| Exception for specific VM (more restrictive) | NIC NSG with additional Deny rule |
| Complex microsegmentation with ASGs | Subnet NSG with rules using ASG |
9. Best Practicesβ
- Use IP Flow Verify as first step when there's a specific connectivity problem. It's faster and more direct than manually navigating through Effective Security Rules.
- Use Effective Security Rules for auditing when you need to understand the complete security context of a VM, not just a specific flow.
- Always verify the correct direction when using IP Flow Verify: inbound for traffic coming to the VM, outbound for traffic leaving.
- After identifying the problem with IP Flow Verify, use Effective Security Rules to locate the rule in the complete context and confirm where to make corrections.
- Automate security audits across multiple VMs via CLI with
az network nic show-effective-nsgand scripts that identify VMs with high permissivity rules (e.g., ports 22/3389 open to*). - Document all changes made after diagnosis in the Activity Log and ticket system for traceability.
- Enable NSG Flow Logs to have historical data of which flows were allowed or denied, enabling retroactive forensic analysis.
10. Common Errorsβ
| Error | Why it happens | How to avoid |
|---|---|---|
| Adds Allow on NIC NSG but remains blocked | Subnet NSG blocks first for inbound | Check evaluation order: subnet first for inbound |
| IP Flow Verify returns "Allowed" but service doesn't respond | Firewall inside VM (Windows Firewall/iptables) blocking | Combine IP Flow Verify with diagnosis inside VM |
| Confuses inbound and outbound in IP Flow Verify | Direction logic not intuitive | For traffic entering VM: inbound. For traffic leaving: outbound. |
| Adds Allow on NSG but forgets response port | TCP requires response (outbound) in addition to request (inbound) | NSGs are stateful: established connections have response allowed automatically |
| Diagnosis done on wrong VM | Multiple VMs with similar names | Confirm IP and Resource ID of VM before diagnosis |
| Rule applied on unassociated NSG | NSG exists but isn't associated to subnet or NIC | Check NSG associations in Overview > Subnets and Network interfaces |
11. Operation and Maintenanceβ
11.1 Automated audit of Effective Security Rulesβ
Script to check if any VM has SSH/RDP open to any IP:
#!/bin/bash
# Check VMs with SSH or RDP open to Internet
RESOURCE_GROUP="myRG"
# List all NICs
for NIC in $(az network nic list --resource-group $RESOURCE_GROUP --query "[].name" --output tsv); do
echo "Checking NIC: $NIC"
# Check rules that allow SSH/RDP from Internet
az network nic show-effective-nsg \
--name "$NIC" \
--resource-group "$RESOURCE_GROUP" \
--query "effectiveNetworkSecurityGroups[].effectiveSecurityRules[?access=='Allow' && direction=='Inbound' && (contains(destinationPortRange, '22') || contains(destinationPortRange, '3389')) && sourceAddressPrefix=='*'].{NIC:'$NIC', Rule:name, Port:destinationPortRange, Source:sourceAddressPrefix}" \
--output table
done
11.2 NSG Flow Logs for retroactive analysisβ
If you need to analyze retroactively why traffic was blocked and Flow Logs are enabled:
# Query Flow Logs in Log Analytics (if Traffic Analytics enabled)
In Log Analytics:
AzureNetworkAnalytics_CL
| where SubType_s == "FlowLog"
| where FlowDirection_s == "I" // Inbound
| where FlowStatus_s == "D" // Denied
| where DestPort_d == 22 // SSH
| project TimeGenerated, SrcIP_s, DestIP_s, DestPort_d, NSGName_s, NSGRules_s
| order by TimeGenerated desc
| take 100
11.3 Limits and considerationsβ
| Aspect | Detail |
|---|---|
| Effective Security Rules available when | VM is in Running state |
| IP Flow Verify works when | Network Watcher is enabled in the region |
| VM without associated NSG | Effective Security Rules returns empty for that level |
| NSGs not displayed | If VM has no NIC or NIC has no NSG, corresponding section remains empty |
| IP Flow Verify response time | Immediate (simulation, not real traffic) |
12. Integration and Automationβ
12.1 Automated security report with Logic Appsβ
Create a daily report of all VMs with permissive rules:
{
"trigger": "Recurrence (Daily 08:00)",
"actions": [
{
"type": "Azure CLI",
"command": "az network nic list + az network nic show-effective-nsg"
},
{
"type": "Filter",
"condition": "Rules with source=* and Action=Allow and Port in [22,3389,3306,1433]"
},
{
"type": "Send Email",
"to": "security-team@company.com",
"body": "VMs with permissive rules detected"
}
]
}
12.2 Integration with Microsoft Defender for Cloudβ
Defender for Cloud automatically uses Effective Security Rules information to generate security recommendations such as:
- "Management ports should be closed on your virtual machines"
- "Just-in-time network access control should be applied on virtual machines"
Configure alerts in Defender for Cloud for automatic notification when VMs expose sensitive ports:
az security pricing create \
--name VirtualMachines \
--tier Standard
12.3 Azure Policy for preventionβ
Combine reactive diagnosis (Effective Security Rules) with proactive prevention (Azure Policy):
# Policy: Deny creation of NSG rules that allow SSH from Internet
az policy assignment create \
--name "deny-ssh-from-internet" \
--policy "5e1e7afc-2ffe-4a9f-a897-db51f019099c" \
--scope "/subscriptions/<sub-id>"
This built-in policy denies creation of NSG rules that open SSH (22) or RDP (3389) to any source (* or Internet).
13. Final Summaryβ
Essential concepts:
- Effective Security Rules displays the consolidated view of all rules from all NSGs applied to a NIC, separated by direction (inbound/outbound) and by origin (subnet NSG or NIC NSG).
- IP Flow Verify simulates a specific flow and returns Allow/Deny with the exact rule name and NSG responsible for the decision.
- Connection Troubleshoot performs end-to-end diagnosis between two endpoints, considering NSGs, routes, and general connectivity.
The evaluation order that needs to be memorized:
- Inbound: Subnet NSG β NIC NSG. Both must allow.
- Outbound: NIC NSG β Subnet NSG. Both must allow.
Critical differences:
- Effective Security Rules vs IP Flow Verify: Effective Security Rules shows all rules for complete analysis. IP Flow Verify tests a specific flow and returns binary result with responsible rule.
- Stateful NSG: Once a TCP connection is established (inbound allowed), return traffic (outbound) is automatically permitted without needing explicit outbound rule. IP Flow Verify and Effective Security Rules reflect this behavior.
- NSG blocking vs blocking inside VM: IP Flow Verify returning "Allowed" but service not responding indicates problem inside VM (local firewall, service not started), not in NSG.
What needs to be remembered:
- Effective Security Rules only works when VM is in Running state.
- Network Watcher needs to be enabled in the region of the VM to use IP Flow Verify and Connection Troubleshoot.
- A VM without associated NSG (neither to subnet nor NIC) allows all traffic by default.
- For mass diagnosis of multiple VMs, use
az network nic show-effective-nsgvia CLI script. - The fastest tool to identify which NSG rule causes a specific connectivity problem is IP Flow Verify, not manual reading of Effective Security Rules.