Creating and Configuring NSG Rules
Complete the full lesson to earn 25 points
Work through each section, then tap “Mark as Complete” on the last one.
✦ Skip the page breaks and see fewer ads — read each lesson on a single page with Pro
Lesson: Creating and Configuring Network Security Group (NSG) Rules
Introduction: The Foundation of Cloud Network Security
In the landscape of modern cloud computing, the perimeter of your network is no longer a physical firewall sitting in a rack in your office. Instead, your infrastructure is defined by software, and the primary gatekeeper for your virtual machine traffic is the Network Security Group, or NSG. An NSG acts as a virtual firewall, filtering traffic to and from resources in an Azure virtual network. Without properly configured NSG rules, your virtual machines and applications are exposed to the entire internet, leaving them vulnerable to unauthorized access, brute-force attacks, and malicious traffic patterns.
Understanding how to create and configure NSG rules is not just a technical requirement; it is a fundamental security responsibility. When you deploy a resource—whether it is a web server, a database, or an application gateway—you must define exactly who can talk to it and what ports they are allowed to use. This practice, known as the Principle of Least Privilege, ensures that even if a service has a vulnerability, the potential for lateral movement or external exploitation is minimized. This lesson will guide you through the mechanics of NSG rules, the logic behind their processing, and the best practices for maintaining a secure environment.
Understanding Network Security Group Architecture
At its core, an NSG is a collection of access control list (ACL) rules that allow or deny network traffic to subnets, network interfaces (NICs), or both. When you associate an NSG with a subnet, the rules apply to all resources within that subnet. When you associate it with a NIC, the rules apply only to that specific virtual machine. Understanding this hierarchy is essential because the order in which rules are processed can determine whether your traffic is allowed or blocked.
The Anatomy of an NSG Rule
Every NSG rule consists of several key components that dictate its behavior. When you create a rule, you must define the following parameters:
- Name: A unique identifier for the rule within the NSG.
- Priority: A number between 100 and 4096. Lower numbers are processed first.
- Source/Destination: You can specify IP addresses, IP ranges, service tags (predefined identifiers for Azure services), or application security groups.
- Protocol: Defines the type of traffic, such as TCP, UDP, ICMP, or "Any."
- Port Range: The specific port or range of ports (e.g., 80, 443, 3389) that the rule affects.
- Action: Either "Allow" or "Deny."
- Direction: Whether the rule applies to inbound traffic (coming into the resource) or outbound traffic (leaving the resource).
Callout: Default Rules vs. Custom Rules Azure automatically creates a set of default rules in every NSG. These default rules allow traffic between virtual machines in the same virtual network, allow traffic from the Azure Load Balancer, and block all other inbound traffic from the internet. You cannot delete these default rules, but you can override them by creating custom rules with a higher priority (a lower number) than the default ones.
The Mechanics of Rule Processing
One of the most common sources of confusion for administrators is the order of operations. Azure processes rules based on their priority number, starting from the lowest number and moving upward. As soon as a packet matches a rule, processing stops, and the action defined by that rule is applied. This means that if you have a "Deny" rule with a priority of 100 and an "Allow" rule with a priority of 200, the "Deny" rule will always take precedence, effectively blocking the traffic regardless of the "Allow" rule.
Rule Evaluation Flow
- Traffic Arrival: A packet arrives at the network interface or subnet boundary.
- Rule Inspection: The system evaluates the rules starting from the lowest priority number.
- Matching: The system checks if the source, destination, protocol, and port match the packet.
- Action Execution: If a match is found, the system performs the defined action (Allow or Deny) and stops evaluating further rules.
- Default Deny: If no rules match the packet, the system falls back to the default "Deny All" rule, ensuring that traffic is blocked unless explicitly permitted.
Tip: Always leave gaps in your priority numbering. For example, use increments of 100 (100, 200, 300) rather than consecutive numbers (100, 101, 102). This allows you to insert new rules between existing ones later without having to renumber your entire rule set.
Configuring NSG Rules: Practical Examples
To configure NSG rules, you can use the Azure Portal, Azure CLI, or PowerShell. In this section, we will focus on the Azure CLI, as it provides a clear, repeatable, and scriptable way to manage your security posture.
Example 1: Allowing Web Traffic (HTTPS)
For a web server, you typically need to allow inbound traffic on port 443. We want to ensure this rule is prioritized correctly and applied to the appropriate resource.
# Create an inbound rule to allow HTTPS traffic
az network nsg rule create \
--resource-group MyResourceGroup \
--nsg-name MyWebNSG \
--name AllowHTTPSInbound \
--protocol tcp \
--priority 100 \
--destination-port-ranges 443 \
--direction inbound \
--access allow \
--source-address-prefixes "*" \
--destination-address-prefixes "*"
Explanation:
--priority 100: This ensures the rule is evaluated early.--source-address-prefixes "*": This allows traffic from any source, which is appropriate for a public-facing web server.--destination-port-ranges 443: This targets the standard HTTPS port.
Example 2: Restricting Management Traffic (SSH)
You should never expose SSH (port 22) or RDP (port 3389) to the entire internet. Instead, restrict access to your specific office or home IP address.
# Create an inbound rule to allow SSH from a specific IP only
az network nsg rule create \
--resource-group MyResourceGroup \
--nsg-name MyAdminNSG \
--name AllowSSHFromOffice \
--protocol tcp \
--priority 110 \
--destination-port-ranges 22 \
--direction inbound \
--access allow \
--source-address-prefixes "203.0.113.50" \
--destination-address-prefixes "*"
Explanation:
- By specifying a single IP address (
203.0.113.50) as the source, you drastically reduce the attack surface. Even if an attacker knows the IP of your virtual machine, they cannot even attempt a login because the NSG will drop their connection attempt at the network level.
Advanced Configurations: Service Tags and Application Security Groups
Managing individual IP addresses for hundreds of resources is inefficient and prone to human error. Azure provides two powerful abstractions to simplify this: Service Tags and Application Security Groups (ASGs).
Using Service Tags
Service Tags are predefined labels that represent a group of IP addresses from a specific Azure service. For example, Storage represents all public IP addresses used by Azure Storage. Instead of updating your NSG rules every time Azure updates its IP ranges, you simply use the tag.
- Internet: Represents all traffic outside the virtual network.
- Sql: Represents Azure SQL Database endpoints.
- Storage: Represents Azure Storage endpoints.
- AzureLoadBalancer: Represents the IP address range for the Azure health probe.
Using Application Security Groups (ASGs)
ASGs allow you to group virtual machines based on their role rather than their IP address. For instance, you can group all your web servers into an ASG-Web and your database servers into ASG-DB. You can then create an NSG rule that says "Allow ASG-Web to talk to ASG-DB on port 1433." If you add a new web server to the ASG-Web group, it automatically inherits the security rules without you needing to modify the NSG.
Callout: ASGs vs. Subnets While subnets are great for network segmentation, they are often too rigid for modern microservices architectures. ASGs provide a more flexible, application-centric way to group resources. Use subnets for logical network boundaries (e.g., separating web, app, and data tiers) and use ASGs to define the specific traffic flow between those tiers.
Best Practices for Secure Network Configuration
Maintaining a secure network requires consistent discipline. Following these industry-standard practices will help you avoid common pitfalls.
- Follow the Principle of Least Privilege: Start by denying all traffic by default and only explicitly allow the ports and protocols necessary for your application to function.
- Avoid "Any/Any" Rules: Never use
*for both source and destination in an "Allow" rule unless you have a very specific, temporary requirement. This is the fastest way to compromise your infrastructure. - Use Descriptive Names: Name your rules based on their function (e.g.,
Allow-HTTPS-From-Internet,Deny-SSH-From-External). This makes auditing much easier. - Regular Audits: Use tools like Azure Network Watcher to visualize your traffic flows and identify rules that are never hit. If a rule isn't being used, remove it to keep your configuration clean.
- Centralize Management: If you have multiple virtual networks, consider using Azure Firewall or a centralized hub-and-spoke network architecture to manage security policies from a single location rather than managing individual NSGs for every resource.
- Use Infrastructure as Code (IaC): Always define your NSG rules in Terraform or Bicep templates. This ensures your security configuration is version-controlled, repeatable, and easier to review before deployment.
Common Pitfalls and Troubleshooting
Even with careful planning, issues arise. Here is how to handle the most common problems when working with NSG rules.
The "Ghost" Rule Problem
Sometimes, you add an "Allow" rule, but the traffic is still blocked. This is almost always due to the priority order.
- The Fix: Use the Azure Portal "Effective Security Rules" view for a specific virtual machine. This view shows you the result of all rules combined, helping you see exactly which rule is blocking the traffic.
Over-Reliance on NSGs
While NSGs are excellent for basic filtering, they are not a substitute for a Web Application Firewall (WAF) or a full-featured Network Firewall.
- The Fix: Use NSGs for layer 3 and 4 filtering (IPs and ports). Use a WAF for layer 7 filtering (URL paths, SQL injection protection, cross-site scripting).
Changing Rules on Production
Modifying an NSG rule on a busy production system can cause immediate connectivity drops.
- The Fix: Always test your NSG changes in a non-production environment first. If you must make changes in production, do so during a maintenance window and have a rollback plan ready.
Summary Comparison Table: Security Components
| Feature | Network Security Group (NSG) | Azure Firewall | Web Application Firewall (WAF) |
|---|---|---|---|
| Layer | Layer 3 & 4 (TCP/UDP) | Layer 3, 4, & 7 | Layer 7 (HTTP/HTTPS) |
| Scope | Subnet or NIC | Entire VNet/Network | Application Gateway/Front Door |
| Best For | Basic traffic filtering | Centralized egress/ingress control | Protecting web apps from exploits |
| Complexity | Low | Medium | High |
Step-by-Step: Creating an NSG and Associating it with a Subnet
If you are just starting out, follow these steps to secure a new subnet:
Create the NSG: Use the Azure Portal or CLI to create an empty NSG.
az network nsg create --resource-group MyRG --name MyNewNSGAdd Your Security Rules: Add your specific rules (like the HTTPS example above) to the NSG. Ensure you have rules for management if necessary, but restrict them to your IP.
Associate with Subnet: An NSG does nothing until it is attached to a subnet or a NIC.
az network vnet subnet update \ --resource-group MyRG \ --vnet-name MyVNet \ --name MySubnet \ --network-security-group MyNewNSGVerify Flow: Once associated, attempt to connect to the resources in that subnet. If it fails, check the "Effective Security Rules" to see if your new rule is being overridden by an existing one.
Key Takeaways
- NSGs are the first line of defense: They provide essential traffic filtering at the network level and should be the foundation of any cloud security strategy.
- Priority is everything: Always remember that rules are processed in numerical order. A lower number means a higher priority.
- Use abstractions for scale: Leverage Service Tags and Application Security Groups to keep your rule sets manageable and reduce human error.
- Never expose management ports: Ports like 22 (SSH) and 3389 (RDP) should never be open to the public internet. Use VPNs, Bastion services, or restricted IP ranges.
- Audit frequently: Security is not a "set and forget" task. Regularly review your NSG rules to ensure they still meet your application's requirements and remove any outdated or unused rules.
- Keep it clean: Use descriptive names and consistent priority numbering to make your network configuration readable and maintainable for your entire team.
- Integrate with IaC: Treat your network security as code. By defining your NSG rules in templates, you create a source of truth that is easily audited and deployed consistently across environments.
By mastering the configuration of NSG rules, you transition from simply deploying cloud resources to actively securing your environment. This skill is the hallmark of a professional cloud administrator and is critical for protecting the integrity and confidentiality of your data. Remember that security is an ongoing process of refinement—always look for ways to tighten your rules and reduce your exposure, and you will build a resilient and secure infrastructure.
Frequently Asked Questions (FAQ)
Q: Can I have multiple NSGs on a single subnet? A: No, you can only associate one NSG with a subnet. However, you can associate an NSG with a subnet and another NSG with a specific network interface (NIC) on a VM within that subnet. In that case, both sets of rules are evaluated.
Q: Does an NSG block traffic between VMs in the same subnet? A: By default, traffic between VMs in the same subnet is allowed by the default rules. You can create custom rules to block this, but remember that these rules will apply to all traffic within the subnet.
Q: What is the maximum number of rules I can have in an NSG? A: You can have up to 4096 rules in an NSG. While this seems like a large number, it is good practice to keep your rule sets concise to avoid management complexity.
Q: If I delete an NSG, what happens to the attached VMs? A: You cannot delete an NSG while it is associated with a subnet or a network interface. You must first remove the association before the NSG can be deleted.
Q: How do I know if my NSG rules are working? A: Use Azure Network Watcher, specifically the "IP Flow Verify" tool. This allows you to test a packet against your current NSG rules to see if it will be allowed or denied, providing immediate feedback on your configuration.
Conclusion
Creating and configuring Network Security Group rules is an exercise in balancing accessibility with protection. It requires a deep understanding of your application's traffic patterns and a disciplined approach to rule management. By implementing the strategies discussed in this lesson—such as using Application Security Groups, keeping management ports restricted, and auditing your configuration regularly—you can build a robust defense that protects your infrastructure from the most common threats in the cloud. Remember that the security of your network is only as strong as your most permissive rule; take the time to define your rules precisely, and your environment will be significantly safer for it.
Enjoying the courses?
Everything stays free. Pro shows fewer ads, doubles your daily points limit so you progress twice as fast, and lets you read each lesson on one page.
- ✓ Fewer advertisements
- ✓ 2× daily points limit
- ✓ Distraction-free lessons