AZ-104Chapter 26 of 168Objective 4.1

Network Security Groups (NSG)

This chapter covers Network Security Groups (NSGs), a fundamental Azure networking component that acts as a distributed, stateful firewall for filtering traffic to and from Azure resources. NSGs are a core topic for the AZ-104 exam, appearing in approximately 10-15% of questions, often in scenarios involving virtual networks, subnets, and network interfaces. Understanding NSG rule evaluation, default rules, and application to subnets vs. NICs is critical for both the exam and real-world Azure administration.

25 min read
Intermediate
Updated May 31, 2026

The Bouncer with a Guest List

Imagine a nightclub with two doors: one for entry (inbound) and one for exit (outbound). The bouncer at the main door holds a clipboard with two lists: an 'Allow' list and a 'Deny' list. When a person tries to enter, the bouncer checks the lists in order — first Deny, then Allow — and lets them in only if they match an Allow entry and no Deny entry. However, once inside, the bouncer remembers them and allows them to leave freely. Now suppose the club also has a VIP section (subnet) with its own bouncer. That bouncer has a separate clipboard with its own lists. A person allowed by the main bouncer might still be denied by the VIP bouncer if they're not on the VIP Allow list. The bouncers never override each other; each enforces their own lists independently. In Azure, Network Security Groups (NSGs) are these bouncers. Each NSG contains security rules (the lists) that filter traffic at the network interface (NIC) or subnet level. The rules are evaluated in priority order, and the first match determines whether traffic is allowed or denied. Just as the bouncer remembers guests who entered, NSGs use stateful filtering: if a packet is allowed inbound, the return traffic is automatically allowed, regardless of outbound rules. Conversely, if a packet is denied, no return traffic is permitted. The bouncer never forgets a guest once they're inside, but if the guest leaves and tries to re-enter, they must pass the check again.

How It Actually Works

What is a Network Security Group (NSG)?

A Network Security Group (NSG) is a cloud-level firewall that filters network traffic to and from Azure resources in a virtual network (VNet). It contains a set of security rules that allow or deny inbound and outbound traffic based on source/destination IP addresses, ports, and protocols. NSGs are stateful: when a packet is allowed in one direction, the return traffic is automatically permitted, regardless of outbound rules. This stateful behavior is essential for protocols like TCP, where a connection requires bidirectional communication.

NSGs can be associated with either a subnet or a network interface (NIC) of a virtual machine. When associated with a subnet, the rules apply to all resources within that subnet. When associated with a NIC, the rules apply only to that specific VM. If both are applied, the subnet NSG rules are evaluated first, then the NIC NSG rules (or vice versa depending on traffic direction). For inbound traffic, the subnet NSG is evaluated first, then the NIC NSG. For outbound traffic, the NIC NSG is evaluated first, then the subnet NSG. This hierarchical evaluation is a common exam point.

How NSG Rules Work

Each NSG rule has the following properties: - Name: A unique name within the NSG. - Priority: A number between 100 and 4096. Lower numbers are evaluated first. Rules are processed in ascending priority order until a match is found. Once a match occurs, no further rules are evaluated. - Source / Destination: Can be an IP address, CIDR block, service tag (e.g., Internet, VirtualNetwork, AzureLoadBalancer), or application security group (ASG). - Protocol: TCP, UDP, ICMP, or Any (all protocols). - Direction: Inbound or Outbound. - Action: Allow or Deny. - Description: Optional metadata.

Rules are evaluated based on the five-tuple: source IP, source port, destination IP, destination port, and protocol. The first rule that matches all five parameters determines the action. If no rule matches, traffic is denied by default (implicit deny).

Default Rules

Every NSG includes a set of default rules that cannot be deleted but can be overridden by custom rules with lower priority. The default rules are:

Inbound default rules: - AllowVNetInBound: Priority 65000, allows all traffic from the virtual network (source VirtualNetwork) to any destination in the VNet. - AllowAzureLoadBalancerInBound: Priority 65001, allows traffic from Azure Load Balancer health probes (source AzureLoadBalancer). - DenyAllInbound: Priority 65500, denies all inbound traffic that hasn't been matched by previous rules.

Outbound default rules: - AllowVNetOutBound: Priority 65000, allows all traffic to the virtual network. - AllowInternetOutBound: Priority 65001, allows all outbound traffic to the internet (destination Internet). - DenyAllOutBound: Priority 65500, denies all outbound traffic not matched.

Note: The AllowInternetOutBound default rule means that by default, VMs can initiate outbound connections to the internet. To block outbound internet access, you must add a higher-priority (lower number) deny rule.

Stateful Behavior

NSGs are stateful. When a packet is allowed inbound, the NSG automatically creates a flow entry for the return traffic. This return traffic is allowed regardless of outbound rules. Similarly, if outbound traffic is allowed, the inbound response is allowed. The flow is tracked for the duration of the TCP session (up to 4 minutes after the last packet) or for 60 seconds for UDP. This stateful behavior simplifies rule creation because you don't need to create symmetric rules for response traffic.

Service Tags

Service tags are predefined identifiers that represent a group of IP address prefixes from a given Azure service. They simplify rule creation by allowing you to specify VirtualNetwork, AzureLoadBalancer, Internet, Sql, Storage, etc., instead of individual IP ranges. Microsoft manages the prefixes behind service tags, so they automatically update as Azure IP ranges change. Service tags can only be used as source or destination in NSG rules, not as specific port/protocol filters.

Application Security Groups (ASGs)

ASGs provide a way to group VMs logically by application role (e.g., Web, Database) and use those groups as source or destination in NSG rules. Instead of using individual IP addresses or subnets, you can reference an ASG. This decouples security rules from IP addresses, making them easier to manage as VMs are added or removed. An ASG can contain multiple VMs, and a VM can be part of multiple ASGs. ASGs are only valid within the same VNet and cannot be used across peered VNets.

Effective Security Rules

When troubleshooting, you can view the effective security rules for a VM or NIC. These are the union of all NSG rules applied to the subnet and NIC, with the evaluation order as described. The effective rules show which rules are actually enforced after considering priorities and associations. You can view this in the Azure portal under the VM's Networking blade or using Azure CLI:

az network nic list-effective-nsg --resource-group MyResourceGroup --name MyNic

Interaction with Azure Firewall and Network Virtual Appliances

NSGs are a basic firewall. For advanced filtering (e.g., application-layer inspection, URL filtering, threat intelligence), Azure Firewall is used. When both NSGs and Azure Firewall are deployed, traffic may traverse multiple layers. For example, traffic entering a subnet might be filtered first by the subnet NSG, then by the Azure Firewall (if the subnet's route table sends traffic to the firewall), and then by the NIC NSG. Understanding the order of evaluation is crucial for troubleshooting.

Performance and Limits

An NSG can have up to 1000 rules per direction (inbound/outbound) for a total of 2000 rules per NSG. However, the number of rules affects evaluation time. For best performance, keep rules to a minimum and use higher priorities for frequently matched rules. The maximum number of NSGs per subscription is 5000 (per region). Each subnet can be associated with up to one NSG, and each NIC can be associated with up to one NSG (or one per direction if using NIC-level NSGs).

Logging and Diagnostics

NSG flow logs capture information about traffic that is allowed or denied by NSG rules. These logs can be sent to Azure Storage, Log Analytics, or Event Hubs for analysis. Flow logs are essential for security auditing and troubleshooting. To enable flow logs, you need a storage account and a Log Analytics workspace (optional). Flow logs are not enabled by default and must be configured per NSG.

Creating and Managing NSGs

You can create NSGs via the Azure portal, Azure CLI, PowerShell, or ARM templates. Example using Azure CLI:

# Create an NSG
az network nsg create --name MyNsg --resource-group MyResourceGroup --location eastus

# Create a rule to allow SSH inbound
az network nsg rule create --nsg-name MyNsg --resource-group MyResourceGroup --name AllowSSH --priority 100 --direction Inbound --access Allow --protocol Tcp --source-address-prefixes 203.0.113.0/24 --source-port-ranges '*' --destination-address-prefixes '*' --destination-port-ranges 22

# Associate NSG with a subnet
az network vnet subnet update --resource-group MyResourceGroup --vnet-name MyVNet --name MySubnet --network-security-group MyNsg

Common Exam Scenarios

Restricting inbound RDP/SSH: Create a rule with priority 100 to allow RDP (port 3389) or SSH (port 22) from a specific IP range, and ensure no lower-priority allow rule exists.

Blocking outbound internet access: Add a deny rule with priority 100 for destination Internet to override the default allow rule.

Allowing only specific traffic between subnets: Use subnet-level NSGs to restrict traffic between frontend and backend subnets.

Using ASGs for web tiers: Create an ASG for web servers and another for database servers, then create rules referencing the ASGs.

Walk-Through

1

Create an NSG

First, create an NSG resource in your Azure subscription. You can do this via the portal, CLI, or PowerShell. The NSG is a container for rules and has no effect until associated with a subnet or NIC. When creating, specify a name, resource group, and location (must match the VNet location). The NSG is initially empty of custom rules but includes default rules. At this point, no traffic filtering occurs.

2

Add security rules

Add custom rules to the NSG based on your security requirements. Each rule includes a priority (100-4096), source/destination IP ranges, ports, protocol, direction, and action. Lower priority numbers are evaluated first. Rules are processed in order until a match; if no match, the default deny rule applies. For example, to allow SSH from a specific IP, create a rule with priority 100, source IP prefix, destination port 22, protocol TCP, action Allow. Ensure no lower-priority rule denies it.

3

Associate NSG with subnet or NIC

Associate the NSG with one or more subnets or NICs. You can associate one NSG per subnet and one per NIC (or one per direction for NIC). When associated with a subnet, all VMs in that subnet get the NSG rules. When associated with a NIC, only that VM is affected. If both are applied, inbound traffic is evaluated first by the subnet NSG, then by the NIC NSG; outbound traffic is evaluated first by the NIC NSG, then by the subnet NSG. This hierarchical evaluation is critical for troubleshooting.

4

Verify effective rules

After association, verify the effective security rules for a VM or NIC. Use the Azure portal or CLI to view the effective rules, which show the union of subnet and NIC NSG rules after priority evaluation. This step confirms that your intended rules are applied correctly. For example, if you created a rule to allow HTTP but it's not working, check effective rules to see if a higher-priority deny rule is blocking it.

5

Monitor and troubleshoot

Enable NSG flow logs to capture traffic data. Flow logs record allowed and denied traffic, including source/destination IPs, ports, and timestamps. Use these logs to identify misconfigurations or security threats. Additionally, use Network Watcher's IP flow verify to test if a specific packet is allowed or denied. This tool simulates traffic and returns the rule that matched. For example, to test if a VM can reach a specific IP on port 443, use IP flow verify with the source and destination.

What This Looks Like on the Job

Enterprise Scenario 1: Multi-Tier Web Application

A company hosts a three-tier web application: web servers, application servers, and database servers, each in separate subnets within a VNet. The web servers must accept HTTPS traffic from the internet, the application servers must only accept traffic from the web servers, and the database servers must only accept traffic from the application servers on port 1433 (SQL).

Solution: Create an NSG for each subnet. For the web subnet, add an inbound rule allowing HTTPS from the Internet (using service tag Internet). For the app subnet, add an inbound rule allowing traffic from the web subnet IP range (or use an ASG for web servers). For the db subnet, add an inbound rule allowing traffic from the app subnet IP range on port 1433. All other inbound traffic is denied by default. Outbound rules are left as default to allow internet access for updates, but if needed, restrict outbound to specific services.

Common pitfalls: Forgetting to allow ICMP for troubleshooting, or misconfiguring the priority of deny rules. In production, use ASGs to avoid IP changes when scaling VMs.

Scenario 2: Blocking Outbound Internet Access for Compliance

A financial institution requires that VMs in a specific subnet cannot access the internet to prevent data exfiltration. However, they must be able to communicate with other VNets via VNet peering and receive patches from a local WSUS server.

Solution: Create an NSG for the restricted subnet. Add a high-priority outbound deny rule (priority 100) with destination Internet and action Deny. Then add a lower-priority allow rule (priority 200) for destination VirtualNetwork to allow VNet communication. Also add an allow rule for the WSUS server IP on port 8530. The default AllowInternetOutBound rule (priority 65001) will be overridden by the higher-priority deny rule. Test with IP flow verify to ensure internet is blocked.

Common issues: The deny rule must have a lower priority number (higher priority) than the default allow rule. If the deny rule has a higher number (e.g., 65500), it won't be evaluated because the default allow rule matches first.

Scenario 3: Using ASGs for Dynamic Environments

A DevOps team uses autoscaling VMSS for a microservices architecture. Services are scaled up/down frequently, and IP addresses change. Manually updating NSG rules with IP addresses is impractical.

Solution: Create ASGs for each microservice (e.g., WebASG, ApiASG, DbASG). Add VMs to the appropriate ASG. Then create NSG rules that reference the ASGs as source or destination. For example, allow traffic from WebASG to ApiASG on port 8080. When new VMs are added to an ASG, the NSG rules automatically apply. This decouples security from IP addresses and simplifies management.

Performance consideration: ASGs are resolved to IP addresses at evaluation time, so there is a slight delay if ASGs change frequently. However, for most scenarios, this is negligible.

How AZ-104 Actually Tests This

What AZ-104 Tests on NSGs

The AZ-104 exam objectives under 'Configure and manage virtual networking' include NSG configuration, rule evaluation, and association. Specific areas: - Objective 4.1: Implement and manage virtual networking, including NSGs, ASGs, service tags, and effective security rules. - Objective 4.2: Configure name resolution and load balancing (NSGs interact with load balancers via service tags). - Objective 4.3: Monitor and troubleshoot networking (flow logs, IP flow verify, effective rules).

Common Wrong Answers and Why Candidates Choose Them

1.

'NSGs are stateless': Candidates confuse NSGs with network virtual appliances. NSGs are stateful, meaning return traffic is automatically allowed. The exam often presents a scenario where a rule allows inbound traffic but the outbound rule denies all; the correct answer is that the return traffic is still allowed due to statefulness.

2.

'Rules are evaluated in order of priority, highest to lowest': Many candidates think higher priority numbers are evaluated first. Actually, lower numbers have higher priority and are evaluated first. The exam may ask which rule is applied if two rules conflict; the one with the lower priority number wins.

3.

'Associating an NSG with a subnet overrides NIC-level NSG': The truth is that both are applied sequentially. For inbound, subnet NSG is evaluated first, then NIC NSG. For outbound, NIC first, then subnet. Candidates often think one overrides the other entirely.

4.

'Default rules can be deleted': Default rules cannot be deleted but can be overridden by custom rules with lower priority numbers. The exam may ask how to block all inbound traffic; the answer is to add a deny rule with priority less than 65000 (the lowest default rule priority).

Specific Numbers and Terms That Appear on the Exam

Priority range: 100 to 4096 (custom rules). Default rules use 65000, 65001, 65500.

Maximum rules per NSG: 1000 per direction (2000 total).

Maximum NSGs per subscription per region: 5000.

Service tags: VirtualNetwork, AzureLoadBalancer, Internet, Sql, Storage, AzureCloud.

ASGs: Can only be used within the same VNet.

Flow logs: Must be enabled per NSG; stored in Azure Storage or Log Analytics.

Edge Cases and Exceptions

When using VNet peering, NSGs in the peered VNet do not affect traffic unless the traffic is routed through the peering. However, NSGs in the source VNet still apply.

For Azure Load Balancer health probes, the default rule AllowAzureLoadBalancerInBound must be present; otherwise, the load balancer will mark VMs as unhealthy.

When using Azure Firewall, NSGs are still evaluated before traffic reaches the firewall (if the firewall is not inline). Understand the traffic flow.

How to Eliminate Wrong Answers

If a question mentions 'return traffic' or 'response packets', remember statefulness: the answer likely involves NSGs automatically allowing return traffic.

If a question involves multiple NSGs (subnet and NIC), draw the flow: inbound: subnet NSG -> NIC NSG; outbound: NIC NSG -> subnet NSG.

If a question mentions 'blocking all traffic from the internet', the answer must involve a deny rule with priority lower than 65000.

If a question mentions 'application security group', remember they are used for logical grouping, not IP-based rules.

Key Takeaways

NSGs are stateful; return traffic is automatically allowed for established sessions.

Custom rules have priority range 100-4096; lower numbers are evaluated first.

Default rules (65000, 65001, 65500) cannot be deleted but can be overridden by custom rules.

NSGs can be associated with subnets and/or NICs; both are evaluated sequentially (inbound: subnet then NIC; outbound: NIC then subnet).

Service tags represent Azure service IP prefixes and are automatically updated by Microsoft.

Application Security Groups (ASGs) allow logical grouping of VMs for rule creation, decoupling security from IP addresses.

Maximum 1000 rules per direction per NSG; maximum 5000 NSGs per subscription per region.

NSG flow logs capture allowed/denied traffic and can be sent to Storage or Log Analytics for analysis.

Use IP flow verify in Network Watcher to test if a packet is allowed or denied by NSGs.

When using VNet peering, NSGs in the source VNet still apply to traffic crossing the peering.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Network Security Group (NSG)

Stateful firewall at the subnet or NIC level.

Rules based on 5-tuple (source/dest IP, port, protocol).

No application-layer inspection (L7).

Free of charge (only egress data charges apply).

Supports service tags and ASGs.

Azure Firewall

Stateful firewall as a managed service with central control.

Supports FQDN filtering, TLS inspection, threat intelligence.

Provides application-layer (L7) filtering.

Costs based on deployment hours and data processing.

Supports network and application rules, NAT, and routing.

Watch Out for These

Mistake

NSGs are stateless, so you need to create symmetric inbound and outbound rules.

Correct

NSGs are stateful. When a packet is allowed in one direction, the return traffic is automatically permitted regardless of outbound rules. You do not need to create symmetric rules for established connections.

Mistake

Custom rules with higher priority numbers are evaluated first.

Correct

Priority numbers range from 100 to 4096 for custom rules. Lower numbers have higher priority and are evaluated first. For example, a rule with priority 100 is evaluated before a rule with priority 200.

Mistake

You can delete the default rules in an NSG.

Correct

Default rules cannot be deleted. However, you can override them by adding custom rules with lower priority numbers (e.g., priority 100) that allow or deny traffic before the default rules are evaluated.

Mistake

Associating an NSG with a subnet overrides any NSG associated with a NIC in that subnet.

Correct

Both NSGs are evaluated sequentially. For inbound traffic, the subnet NSG is evaluated first, then the NIC NSG. For outbound traffic, the NIC NSG is evaluated first, then the subnet NSG. Traffic is only allowed if both NSGs allow it.

Mistake

Service tags can be used as source or destination in NSG rules but require manual updates when Azure IP ranges change.

Correct

Service tags are automatically managed by Microsoft. The IP prefixes behind a service tag are updated dynamically as Azure services change, so you do not need to manually update NSG rules.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

Can I associate the same NSG with multiple subnets?

Yes, a single NSG can be associated with multiple subnets (and NICs) within the same region. However, each subnet can have only one NSG associated. Associating the same NSG with multiple subnets can simplify management if the same rules apply to all those subnets.

What happens if I have an NSG on both the subnet and the NIC?

Both NSGs are evaluated. For inbound traffic, the subnet NSG is evaluated first, then the NIC NSG. For outbound traffic, the NIC NSG is evaluated first, then the subnet NSG. Traffic must be allowed by both NSGs to pass. The effective security rules show the combined result.

How do I block all inbound internet traffic except HTTP and HTTPS?

Create two allow rules with priority 100 and 101 for TCP ports 80 and 443 from source `Internet` to destination `*`. Then create a deny rule with priority 102 for source `Internet` to destination `*` for all protocols. The deny rule will block all other inbound internet traffic because it has a lower priority number than the default deny rule (65500) and will be evaluated first.

Can I use NSGs across VNet peerings?

NSGs are applied within the VNet where they are created. When using VNet peering, traffic from a peered VNet is subject to the NSG rules of the destination VNet. However, NSGs in the source VNet also apply to outbound traffic before it leaves the source VNet. You cannot directly reference a peered VNet's IP ranges in an NSG rule without specifying the IP prefixes manually.

What is the difference between an NSG and an ASG?

An NSG is a firewall that contains security rules and is associated with subnets or NICs. An ASG is a logical grouping of VMs that can be used as a source or destination in NSG rules, allowing you to define rules based on application roles rather than IP addresses. ASGs are not firewalls themselves; they are referenced by NSG rules.

How do I enable NSG flow logs?

You can enable flow logs via the Azure portal, CLI, or PowerShell. You need a storage account in the same region as the NSG. Optionally, you can send logs to Log Analytics. The command to enable via CLI: `az network watcher flow-log create --resource-group MyRG --nsg MyNSG --storage-account MyStorage --name MyFlowLog --retention 90`.

What is the default outbound internet access for VMs?

By default, VMs have outbound internet access due to the default rule `AllowInternetOutBound` (priority 65001). This allows all outbound traffic to the internet. To restrict outbound internet access, you must add a higher-priority deny rule for destination `Internet`.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Network Security Groups (NSG) — now see how well it sticks with free AZ-104 practice questions. Full explanations included, no account needed.

Done with this chapter?