Skip to main content

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​

100%
Scroll para zoom Β· Arraste para mover Β· πŸ“± Pinch para zoom no celular

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:

  1. Rules from the NSG associated with the subnet where the VM is located
  2. Rules from the NSG directly associated with the NIC
  3. 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:

FieldDescription
PriorityRule priority number (lower = higher priority)
NameRule name
PortDestination port(s)
ProtocolTCP, UDP, ICMP or Any
SourceSource IP, CIDR, Service Tag or ASG
DestinationDestination IP, CIDR, Service Tag or ASG
ActionAllow 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:

100%
Scroll para zoom Β· Arraste para mover Β· πŸ“± Pinch para zoom no celular

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​

100%
Scroll para zoom Β· Arraste para mover Β· πŸ“± Pinch para zoom no celular

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):

PriorityNameSourceDest PortAction
100Allow-HTTPSInternet443Allow
200Allow-HTTPInternet80Allow
65000AllowVnetInBoundVirtualNetwork*Allow
65001AllowAzureLBInBoundAzureLoadBalancer*Allow
65500DenyAllInBound**Deny

NIC NSG (NSG-VM01-NIC):

PriorityNameSourceDest PortAction
100Deny-SSH*22Deny
65000AllowVnetInBoundVirtualNetwork*Allow
65001AllowAzureLBInBoundAzureLoadBalancer*Allow
65500DenyAllInBound**Deny

Question: An external client attempts SSH (port 22) to the VM. What happens?

Analysis with Effective Security Rules:

  1. 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. The DenyAllInBound (65500) blocks... but wait: there's no explicit Deny rule before 65500 for port 22 in the subnet NSG.

  2. Actually, AllowVnetInBound doesn't apply (source is Internet, not VirtualNetwork). Traffic reaches rule 65500 (DenyAllInBound) and would be blocked.

  3. 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​

OperationMinimum role
View Effective Security RulesNetwork Contributor or Reader with Network Watcher Reader
Use IP Flow VerifyNetwork Watcher Contributor
Use Connection TroubleshootNetwork Watcher Contributor
Modify NSG rules after diagnosisNetwork 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​

SituationToolReason
"Which rules apply to this VM?"Effective Security RulesComplete view of all rules
"Why is port 8080 blocked for this IP?"IP Flow VerifyDirect diagnosis for specific flow
"Can the VM connect to the database?"Connection TroubleshootEnd-to-end test with connectivity response
"Which route is traffic using?"Next HopRouting diagnosis
"Traffic reaches VM but application doesn't respond?"Packet CapturePacket analysis within the network
"Multiple VMs with issues, need bulk analysis"CLI + az network nic show-effective-nsgScriptable and automatable

8.2 When subnet NSG is sufficient vs when NIC NSG is necessary​

SituationApproach
Rule that should apply to all VMs in subnetSubnet 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 ASGsSubnet 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-nsg and 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​

ErrorWhy it happensHow to avoid
Adds Allow on NIC NSG but remains blockedSubnet NSG blocks first for inboundCheck evaluation order: subnet first for inbound
IP Flow Verify returns "Allowed" but service doesn't respondFirewall inside VM (Windows Firewall/iptables) blockingCombine IP Flow Verify with diagnosis inside VM
Confuses inbound and outbound in IP Flow VerifyDirection logic not intuitiveFor traffic entering VM: inbound. For traffic leaving: outbound.
Adds Allow on NSG but forgets response portTCP requires response (outbound) in addition to request (inbound)NSGs are stateful: established connections have response allowed automatically
Diagnosis done on wrong VMMultiple VMs with similar namesConfirm IP and Resource ID of VM before diagnosis
Rule applied on unassociated NSGNSG exists but isn't associated to subnet or NICCheck 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​

AspectDetail
Effective Security Rules available whenVM is in Running state
IP Flow Verify works whenNetwork Watcher is enabled in the region
VM without associated NSGEffective Security Rules returns empty for that level
NSGs not displayedIf VM has no NIC or NIC has no NSG, corresponding section remains empty
IP Flow Verify response timeImmediate (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-nsg via 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.