Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 57 ยท Networking

Network Security Groups and Firewalls

Learn Azure network security: NSG rules and priorities, default rules, application security groups, Azure Firewall, Bastion and DDoS Protection, with a rule evaluator.

A virtual network gives you private address space, but by itself it does not decide who may talk to whom. That job belongs to the security layers you add on top. In Azure the first and most common layer is the Network Security Group (NSG): a list of allow and deny rules, evaluated in priority order, that filters traffic to and from subnets and network interfaces. Heavier tools such as Azure Firewall, Azure Bastion and DDoS Protection cover the cases an NSG cannot.

The real services need an Azure account, so the commands in this lesson are read-only. The runnable examples are JavaScript stand-ins: a small rule evaluator that follows the same logic as an NSG, and a variant that uses groups of machines instead of addresses. They are simplified (one port, one direction), but the priority and default-rule behavior is the real thing. Before reading on, make sure the subnet ideas from Virtual Networks and Subnets are familiar.

How an NSG works

An NSG holds security rules. Each rule has these fields:

  • Priority: a number from 100 to 4096. A lower number is evaluated first.
  • Source and destination: an IP address, a CIDR range, a service tag, an application security group, or * for any.
  • Source port and destination port: a port, a range, or *.
  • Protocol: TCP, UDP, ICMP, or any.
  • Direction: inbound or outbound.
  • Action: allow or deny.

Evaluation stops at the first rule that matches. If rule 100 allows port 443 and rule 200 denies everything, a request to port 443 is allowed and rule 200 is never consulted. NSGs are stateful: when an inbound request is allowed, the reply travels back without needing an outbound rule, and the same holds the other way around.

You can attach an NSG to a subnet, to a network interface (NIC), or both. For inbound traffic the subnet's NSG is checked first and then the NIC's; for outbound traffic it is the other way around. Traffic must be allowed at both levels to get through. Most teams attach NSGs to subnets only, because fewer attachment points are easier to reason about.

The default rules

Every NSG starts with default rules that you cannot delete, only override with a lower priority number. They sit at priorities 65000 and above:

Direction Priority Name Effect
Inbound 65000 AllowVnetInBound Allow traffic from within the virtual network
Inbound 65001 AllowAzureLoadBalancerInBound Allow health probes from the Azure load balancer
Inbound 65500 DenyAllInBound Deny everything else
Outbound 65000 AllowVnetOutBound Allow traffic to the virtual network
Outbound 65001 AllowInternetOutBound Allow traffic to the internet
Outbound 65500 DenyAllOutBound Deny everything else

Two consequences matter every day. First, inbound traffic from the internet is blocked unless you add an allow rule. Second, everything inside the VNet can talk to everything else until you add deny rules, and outbound internet access is open by default.

Service tags

Writing IP lists by hand is fragile, so Azure offers service tags: named groups of address prefixes that Microsoft maintains. Common ones are Internet, VirtualNetwork, AzureLoadBalancer, Storage and Sql. A rule that allows outbound traffic to the Storage tag keeps working when Azure adds new storage addresses, because you never listed them yourself.

A rule evaluator in JavaScript

The platform's engine is Azure's own; this stand-in reproduces the essential logic. It sorts rules by priority, takes the first match, and falls through to the default rules. Run it and read the last column: it names the rule that decided each request.

JS Evaluate NSG rules by priority

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third line shows a classic mistake. The admin address 203.0.113.9 is meant to be allowed on port 22, but deny-ssh-internet has priority 200 and matches first, so the more specific allow at 300 never runs. The fix is to give the allow rule a lower number than the broad deny, for example 150. Edit the priority in the editor and run it again to watch the result flip. The rule of thumb: put narrow exceptions before broad rules.

The fourth line shows the default AllowVnetInBound rule at work: a machine inside the VNet can reach port 1433 without any custom rule, which is exactly why internal segmentation needs explicit deny rules.

Application security groups

Hard-coding IP addresses into rules breaks as soon as a VM is added or replaced. An application security group (ASG) is a label you attach to NICs, such as asg-web or asg-data. You then write rules between groups: "allow asg-web to asg-app on port 8080". Adding another web server only means putting its NIC in the group; no rule changes.

flowchart LR
    I["Internet"] -->|"443"| W["asg-web"]
    W -->|"8080"| A["asg-app"]
    A -->|"1433"| D["asg-data"]
    W -. "denied" .-> D

A three-tier layout expressed with groups. The dotted line is blocked by a catch-all deny rule.

JS Rules between groups, not addresses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The web tier cannot reach the database directly, only the app tier can, and a brand-new web server inherits the right access the moment it joins the group.

Creating rules with the CLI

These commands are read-only here because they change a real subscription:

Terminal
az network nsg create --resource-group rg-net --name nsg-web --location westeurope

az network nsg rule create \
  --resource-group rg-net --nsg-name nsg-web \
  --name allow-https --priority 100 \
  --direction Inbound --access Allow --protocol Tcp \
  --source-address-prefixes Internet \
  --destination-port-ranges 443

az network vnet subnet update \
  --resource-group rg-net --vnet-name vnet-app --name snet-web \
  --network-security-group nsg-web

Leave gaps between priorities (100, 110, 120, or even 100, 200, 300) so you can insert a rule later without renumbering.

Azure Firewall

An NSG works with addresses, ports and protocols. It cannot say "allow outbound traffic only to *.contoso.com" or inspect threats. Azure Firewall is a managed, stateful firewall service for the whole network:

  • Network rules (IP, port, protocol) and application rules that filter by FQDN (fully qualified domain name), for example allowing only api.example.com over HTTPS.
  • Threat intelligence filtering, and in the Premium tier TLS inspection and intrusion detection.
  • A fixed private IP that you use as the next hop in a route table, so outbound traffic from spoke subnets is forced through it (user-defined routes are covered in the virtual networks lesson).
  • It lives in a dedicated AzureFirewallSubnet of at least /26.

It costs considerably more than NSGs, which are free. A typical design uses both: NSGs for tier-to-tier filtering inside a VNet, and a firewall in a central hub for internet egress and cross-network control.

Azure Bastion

Opening RDP (3389) or SSH (22) to the internet is one of the most attacked configurations there is. Azure Bastion removes the need. It is a managed service in an AzureBastionSubnet (at least /26) that lets you open an RDP or SSH session to a VM from the Azure portal over TLS on port 443. The VM needs no public IP address and no inbound management port open to the internet. You then keep rule 3389/22 denied from Internet and manage servers through Bastion.

DDoS Protection

A distributed denial-of-service attack tries to overwhelm your public endpoints with traffic. Every Azure public IP gets basic infrastructure-level protection at no charge. For stronger defense there are paid plans (DDoS Network Protection and DDoS IP Protection) that add adaptive tuning for your specific traffic patterns, attack metrics and alerts, and support. They matter for internet-facing workloads whose downtime is expensive; an internal-only VNet usually does not need them.

Network Watcher: troubleshooting and diagnostic logs

Network Security Groups and routes decide whether traffic flows, but when a connection fails you cannot tell why by staring at them. Azure Network Watcher is a set of diagnostic tools for network resources. It is enabled per region (Azure usually creates it automatically in a NetworkWatcherRG resource group when you create a virtual network).

Tool Question it answers
IP flow verify Does an NSG rule allow or deny this exact packet to or from this VM, and which rule decides?
Next hop Where will this VM send traffic to that address (internet, virtual appliance, peering, nowhere)?
Connection troubleshoot Can this source reach this destination and port, and where along the path does it break?
Effective security rules The merged result of every NSG on the NIC and subnet
Packet capture Capture packets on a VM for analysis
Flow logs A record of the traffic that crossed an NSG or a virtual network
Terminal
# Does the NSG allow a client to reach port 443 on vm1? (read-only examples)
az network watcher test-ip-flow --resource-group web --vm vm1 --nic nic-vm1 \
  --direction Inbound --protocol TCP \
  --local 10.0.1.4:443 --remote 203.0.113.50:50000

az network watcher show-next-hop --resource-group web --vm vm1 \
  --source-ip 10.0.1.4 --dest-ip 10.1.0.5

az network watcher test-connectivity --resource-group web --source-resource vm1 \
  --dest-address db.internal.example.com --dest-port 1433

Troubleshooting order that works: IP flow verify (is a rule blocking it?), effective routes and next hop (does the packet go the right way?), then connection troubleshoot end to end. Remember the other usual suspects: the OS firewall, the app not listening, DNS returning the wrong address (see DNS and Traffic Manager) and a missing private DNS zone (see Private Endpoints, VPN and ExpressRoute).

Flow logs and firewall logs

Flow logs store records of connections (source, destination, port, protocol, allowed or denied) in a storage account, and Traffic Analytics can summarize them in a Log Analytics workspace. Microsoft has announced the retirement of the older NSG flow logs in favor of virtual network flow logs, which cover a whole virtual network, so plan new work with virtual network flow logs and check the current guidance and dates.

Azure Firewall writes its own rule logs when you enable diagnostic settings (see Azure Monitor, Log Analytics and Application Insights). With resource-specific tables you can find what the firewall denied:

KUSTO
AZFWNetworkRule
| where Action == "Deny"
| summarize Hits = count() by SourceIp, DestinationIp, DestinationPort
| order by Hits desc

An Application Gateway is restarted by stopping and starting it (az network application-gateway stop then start), which causes an outage, so do it in a window. Orphaned NICs and public IPs that cause confusion in these tools are listed with Resource Graph (see Azure Policy, Locks and Governance).

IP flow verify: a stand-in

The stand-in reuses the first-match-wins rule logic of an NSG and answers the IP flow verify question, naming the deciding rule.

JS IP flow verify and next hop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two inbound rules both match a request: priority 150 denies it and priority 400 allows it. What happens?

    Rules are evaluated from the lowest priority number upward, and evaluation stops at the first match.
  2. 2. A new NSG has no custom rules. What happens to an inbound request from the internet to a VM in the subnet?

    Inbound internet traffic is denied by default. You must add an explicit allow rule with a priority below 65500.
  3. 3. What is the main benefit of an application security group?

    ASGs let you write rules between roles such as web and app, independent of the IP addresses of individual machines.
  4. 4. Which service lets you allow outbound HTTPS only to specific domain names?

    NSGs filter by address, port and protocol. FQDN filtering is a feature of Azure Firewall.
  5. 5. Why use Azure Bastion?

    Bastion brokers secure sessions over TLS, so the VMs themselves are never exposed on port 22 or 3389.

Summary

  • An NSG is a stateful list of allow and deny rules; the lowest priority number is evaluated first and the first match wins.
  • Default rules deny inbound internet traffic, allow traffic inside the VNet and allow outbound internet traffic, so segmentation needs explicit rules.
  • Service tags and application security groups keep rules readable and stable as addresses change.
  • Azure Firewall adds FQDN filtering, threat intelligence and central egress control; Bastion removes public management ports; DDoS Protection hardens public endpoints.
  • Put narrow exceptions at lower priority numbers than broad denies, and leave gaps between numbers.

Next: Load Balancer, Application Gateway and Front Door.