Azure NSGs provide a quick and easy way to deploy networks. The article will cover the fundamentals of what an NSG is, how it works with PowerShell, basic steps for setting up your first Azure network using PowerShell, and common pitfalls you may run into when setting them up.
Azure NSGs are a type of network security group that can be used to control access to your Azure resources. They also provide protection from DDoS attacks and other threats. In this blog, we will walk through the process of setting up an NSG with PowerShell. Read more in detail here: get-aznetworksecurityruleconfig.
Azure Network Security Groups, or Azure NSGs, enable you to filter network traffic from one or more Azure services, both incoming and outgoing. You must understand how NSGs function if you ever need to block access to an Azure resource.
The purpose of the Azure NSG and how to set them up using the PowerShell scripting language are covered in this article.
Prerequisites
- A target Azure resource. A pay-as-you-go membership and a Windows Server 2019 Azure virtual machine will be used in this tutorial.
- PowerShell 7+ is required. Although older versions of PowerShell may work, the setting in this guide is done using PowerShell 7.0.1.
- Azure’s Az module Module for PowerShell
Azure NSGs: An Overview
Consider an Azure NSG to be a firewall. A firewall is made up of rulesets, which define the actions to be taken on incoming and outgoing traffic. Default rulesets, which are rules that determine what may and cannot pass through a firewall, are often included with firewalls; Azure NSGs are no different.
Azure NSGs, unlike conventional firewalls, feature a cloud notion called service tags. Azure uses services tags to abstract address ranges and make them simpler to manage.
Let’s take a quick look at each of these vital areas.
Simplifying Rule Configuration using Service Tags
IP addresses and ranges are often changed in cloud services. This might make manually created Azure IP range rulesets difficult to maintain. Fortunately, Azure has a large number of service tags that your NSG rule can target.
Service tags are a notion that always uses the most recent address list available. For better administration, service tags are a technique of designating placeholders to groupings of address ranges.
The Azure portal’s Azure service tags
Recognize the Default Rule Sets
Before you can construct and apply an Azure NSG, you must first understand the rules that such NSGs apply automatically. These default rulesets are established for both incoming and outgoing traffic and are immutable.
A priority is assigned to each rule in an Azure NSG ruleset. Priority determines the sequence of operations or which rules take precedence over others. If you write a rule with a priority of 64999 that permits port 80 and a rule with a priority of 65000 that restricts all incoming traffic, the Azure NSG will block all traffic except port 80.
Priorities for Azure NSG rules by default
Default rulesets cannot be altered, however a higher priority rule may be used to override them, as demonstrated above. These guidelines apply to all protocols, including TCP, UDP, and ICMP.
To override the default rules, make sure your rules use a value lower than 65500!
You’ll notice many preset rules when you build an Azure NSG:
Inbound Guidelines
- AllowVNetInBound — This inbound rule includes all virtual network IP address ranges as well as any associated on-premises address spaces. Peered virtual networks, virtual networks linked to a virtual network gateway, the host’s virtual IP address, and any address prefixes used on user-defined routes are also included in this rule. This rule has a priority of 65000.
- AllowAzureLoadBalancerInBound — The AzureLoadBalancer service tag corresponds to the host’s virtual IP address, 168.63.129.16, from which the Azure health probe comes. Actual traffic does not pass through here, and this rule may be modified if you do not utilize Azure Load Balancing. In all areas, the host’s virtual IP address is used to deliver important infrastructure services including DHCP, DNS, IMDS, and health monitoring. This regulation has a priority of 65001.
- AllInbound Deny – This rule, which is set as the very last rule and has priority 65500, refuses all non-explicitly approved incoming traffic.
Outbound Procedures
- AllowVNetOutBound — This includes all virtual network IP address ranges, all linked on-premises address spaces, peered virtual networks, virtual networks connected to a virtual network gateway, the host’s virtual IP address, and any address prefixes used on user-defined routes. This rule has a priority of 65000.
- AllowInternetOutBound – IP address space outside of the virtual network that may be accessed over the internet. Includes the Azure-owned public IP address space’s address range. This regulation has a priority of 65001.
- DenyAllOutBound – Like in the Inbound Guidelineset, this rule is set as the very last rule, using priority 65500. This outbound rule will deny all non-explicitly allowed traffic.
Using PowerShell to create Azure NSGs
Enough with the rhetoric; let’s get our hands dirty and start creating Azure NSGs using PowerShell! Continue reading assuming you’re logged in to your PowerShell console.
Connect-AzAccount: Your Azure Gateway using PowerShell is related.
With PowerShell, you just need to run one command to establish an Azure NSG: New-AzNetworkSecurityGroup. Provide the name, the resource group name to create the NSG under, and the location to establish an NSG using this command.
The New-AzNetworkSecurityGroup cmdlet is used in the code below to build an NSG named NSG-MyVM in the Articles resource group in the eastus Azure datacenter.
@’Name’ = ‘NSG-MyVM’ ‘ResourceGroupName’ = ‘Articles’ ‘Location’ = ‘centralus’ $Params = @’Name’ = ‘NSG-MyVM’ ‘ResourceGroupName’ = ‘Articles @Params $NSG = New-AzNetworkSecurityGroup
Using PowerShell to create Azure NSG Rules
The default set of rules is usually insufficient if you have the NSG. You’ll have to make your own set of rules.
Setting up a Remote Desktop Protocol Inbound Rule
The requirement to define an incoming rule for the Remote Desktop Protocol is a typical administrative chore (RDP). Perhaps the instruction will be applied to a Windows Server Azure VM, and you will need to reach the VM using RDP. In such scenario, you must allow incoming traffic on port 3389.
There are three stages to adding a new incoming rule to an existing NSG:
- To get an existing NSG, use the Get-AzNetworkSecurityGroup command.
- To build the rule, run Add-AzNetworkSecurityRuleConfig.
- To apply the rule to the NSG, use the Set-AzNetworkSecurityGroup command.
The Get-AzNetworkSecurityGroup cmdlet is used to obtain an existing NSG in the code below. The Add-AzNetworkSecurityRuleConfig cmdlet is then used to create a rule, which is then applied to an existing NSG using the Set-AzNetworkSecurityGroup cmdlet.
Get-AzNetworkSecurityGroup -Name ‘NSG-MyVM’ -ResourceGroupName ‘Articles’ $NSG = Get-AzNetworkSecurityGroup -Name ‘NSG-My ‘Name’ = ‘allowRDP’ ‘NetworkSecurityGroup’ = $NSG $Params = @ ‘TCP’ as the protocol ‘Inbound’ is the direction, and ‘Priority’ is 200. ‘SourceAddressPrefix’ =’my.ip.address’ ‘SourcePortRange’ = ‘*’ ‘DestinationAddressPrefix’ = ‘*’ ‘DestinationPortRange’ = 3389 ‘DestinationAddressPrefix’ = ‘*’ ‘DestinationAddressPre ‘Allow’ = ‘Access’ Set-AzNetworkSecurityGroup | Add-AzNetworkSecurityRuleConfig @Params
The Priority parameter controls when the rule is assessed; 200 is towards the top, with 4096 being the lowest priority rule.
Denying SANS Recommended Outbound Traffic
Outbound traffic is often not banned since it is difficult to know all of the various ports that a program could use. Fortunately, the SANS Institute, a globally respected organization for information security standards, has some professional egress filtering options.
We may utilize the same three steps outlined above to apply SANS’ advice, but this time build a rule with multiple ports and a Direction of Outbound rather than Inbound.
- MS RPC – TCP & UDP port 135
- NetBIOS/IP – TCP & UDP ports 137-139
- TCP port 445 for SMB/IP
- UDP port 69 for the Trivial File Transfer Protocol (TFTP).
- UDP port 514 for Syslog
- UDP ports 161-162 for the Simple Network Management Protocol (SNMP).
Using the Get-AzNetworkSecurityGroup cmdlet, the code below obtains an existing NSG rule. The Add-AzNetworkSecurityRuleConfig cmdlet is used to create an outward rule, which is then implemented using the Set-AzNetworkSecurityGroup cmdlet.
Get-AzNetworkSecurityGroup -Name ‘NSG-MyVM’ -ResourceGroupName ‘Articles’ $NSG = Get-AzNetworkSecurityGroup -Name ‘NSG-My ‘Name’ = ‘DenySANSOutBound’ ‘NetworkSecurityGroup’ = $NSG ‘Protocol’ = ‘*’ ‘Direction’ = ‘Outbound’ ‘Priority’ = 4000 $Params = @ ‘Name’ = ‘DenySANSOutBound’ ‘NetworkSecurityGroup’ ‘DestinationAddressPrefix’ = ‘Internet’ ‘DestinationPortRange’ = @(‘135’, ‘137’,’139′,’445′,’69’,’514′,’161′,’162′) ‘Access’ = ‘Deny’ Set-AzNetworkSecurityGroup | Add-AzNetworkSecurityRuleConfig @Params
Of course, depending on the services you provide, some of these ports are useful and required. Most likely, you’ll need to adjust this list based on the requirements of your application, which are often supplied by the manufacturer or discovered using a tool like netstat.
Related: Using Netstat and PowerShell to Find Ports
Setting up an Azure Network Security Group for a Specific Subnet
Subnets may have been used to divide your virtual network area. To go even more detailed, you may apply NSGs to a single subnet, allowing you to manage traffic in that subnet.
The Python snippet below finds and applies an NSG to a whole address prefix.
# Get a Virtual Network that already exists. Get-AzVirtualNetwork -Name ‘Articles-vnet’ -ResourceGroupName ‘Articles’ $VNet = Get-AzVirtualNetwork -Name ‘Articles-vnet # Get an NSG that already exists. Get-AzNetworkSecurityGroup -Name ‘NSG-MyVM’ -ResourceGroupName ‘Articles’ $NSG = Get-AzNetworkSecurityGroup -Name ‘NSG-My # Using array notation, choose the first subnet and the first record at the 0 position. $Params = @ ‘Name’ = ($VNet.Subnets[0]) ‘VirtualNetwork’ = $VNet ($VNet.Subnets[0]) name ‘AddressPrefix’ ‘NetworkSecurityGroup’ AddressPrefix = $NSG # Set-AzVirtualNetworkSubnetConfig @Params Set-AzVirtualNetwork -VirtualNetworkSet-AzVirtualNetworkSet-AzVirtualNetworkSet-AzVirtualNetworkSet-AzVirtualNetworkSet-AzVir $VNet
Then, see how to leverage network interfaces to further divide and confine NSGs to just what is required, such as a network interface.
An Azure NSG is applied to a network interface.
NSG rules may be applied directly to a network interface, similar to how subnets function. This degree of granularity is normally unneeded, but when a virtual machine has numerous network interfaces, it might make sense to apply various rulesets to the individual NICs as needed.
You may apply rules to an individual NIC in the same way that subnet limitation is established. In this scenario, the Get-AzNetworkInterface cmdlet is being used to fetch a particular NIC on the specified VM. The previously formed NSG will now be assigned to the NetworkSecurityGroup property.
Get-AzNetworkSecurityGroup -Name “MyVM-nsg” -ResourceGroupName “Articles” $NSG = Get-AzNetworkSecurityGroup -Name “MyVM-ns Get-AzNetworkInterface -name “MyVM-vm-nic” $NIC = Get-AzNetworkInterface Set-AzNetworkInterface $NIC.NetworkSecurityGroup = $NSG $NIC
What about using an NSG to diagnose and analyze traffic? Continue reading to discover more about NSG flow logs and how to utilize them.
Using NSG Flow Logs for Debugging and Troubleshooting
You may need further debugging to troubleshoot a malfunctioning rule or analyze traffic during the design and use of NSG. The Azure Network Watcher’s Flow Logs feature records information about IP traffic passing through an NSG.
The Azure Network Watcher records network activity and saves it to an Azure Storage Account. You may use PowerShell to setup Azure NSG flow logs to parse through that Azure storage account and diagnose and solve issues.
Related: How to Get the AzCopy Tool and Install It
In PowerShell, there are three steps to enable NSG flow logs:
- The Microsoft.Insights provider must be registered.
- To store the data, create an Operational Insights Workspace.
- The Set-AzNetworkWatcherConfigFlowLog command enables the NSG flow log.
The PowerShell code below will simplify the various essential procedures for configuring Azure NSG Flow Logs. This code, for example, builds an Operational Insights Workspace and links a Flog Log configuration to the appropriate subscription, workspace, and NSG.
$resourceGroupName = ‘<some resource group name>’ $NetworkWatcher = Get-AzNetworkWatcher -Name ‘<some name>’ -ResourceGroupName $resourceGroupName $NSG = Get-AzNetworkSecurityGroup -Name ‘NSG-MyVM’ -ResourceGroupName $resourceGroupName $StorageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name ‘<storage account name>’ $Subscription = Get-AzSubscription -SubscriptionName ‘<your subscription name>’ $Workspace = New-AzOperationalInsightsWorkspace -Location ‘centralus’ -Name “DefaultWorkspace-$($NSG.Name)-Articles” -Sku ‘Standard’ -ResourceGroupName $resourceGroupName $Params = @{ ‘NetworkWatcher’ = $NetworkWatcher ‘TargetResourceId’ = $NSG.Id ‘StorageAccountId’ = $StorageAccount.Id ‘EnableFlowLog’ = $True ‘FormatType’ = ‘JSON’ ‘FormatVersion’ = 2 ‘EnableTrafficAnalytics’ = $True ‘WorkspaceResourceId’ = $Workspace.ResourceId ‘WorkspaceGUID’ = $Workspace.CustomerId ‘WorkspaceLocation’ = ‘centralus’ } Set-AzNetworkWatcherConfigFlowLog @Params
Flow logs, like firewall logs, have a lot of various attributes. This covers things like source and destination IP addresses, ports, protocols, and time stamps. Version 1 and 2 logs vary greatly in that version 2 includes the idea of flow state. This indicates when a flow will continue or end, as well as traffic bandwidth information.
Steps to Follow
Azure NSGs are strong tools for limiting and auditing resource flow. When used correctly, you can appropriately safeguard your resources and infrastructure. You have the freedom to scope rules as required and verify that all traffic is as anticipated thanks to auditing features provided by NSG flow logs and the option to confine NSGs to subnets or network adapters.
The “set-azvirtualnetworksubnetconfig” is a PowerShell command that allows users to set up and configure Azure NSGs.
Related Tags
- get-aznetworksecuritygroup
- how to import nsg rules in azure
- create or update network security group rule
- azure powershell nsg
- microsoft network networksecuritygroups/securityrules