Filter network traffic with a network security group using PowerShell

You can filter network traffic inbound to and outbound from a virtual network subnet with a network security group. Network security groups contain security rules that filter network traffic by IP address, port, and protocol. Security rules are applied to resources deployed in a subnet. In this article, you learn how to:

  • Create a network security group and security rules
  • Create a virtual network and associate a network security group to a subnet
  • Deploy virtual machines (VM) into a subnet
  • Test traffic filters

If you don't have an Azure subscription, create a free account before you begin.

Azure Cloud Shell

Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can use either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell preinstalled commands to run the code in this article, without having to install anything on your local environment.

To start Azure Cloud Shell:

Option Example/Link
Select Try It in the upper-right corner of a code or command block. Selecting Try It doesn't automatically copy the code or command to Cloud Shell. Screenshot that shows an example of Try It for Azure Cloud Shell.
Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. Button to launch Azure Cloud Shell.
Select the Cloud Shell button on the menu bar at the upper right in the Azure portal. Screenshot that shows the Cloud Shell button in the Azure portal

To use Azure Cloud Shell:

  1. Start Cloud Shell.

  2. Select the Copy button on a code block (or command block) to copy the code or command.

  3. Paste the code or command into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux, or by selecting Cmd+Shift+V on macOS.

  4. Select Enter to run the code or command.

If you choose to install and use PowerShell locally, this article requires the Azure PowerShell module version 1.0.0 or later. Run Get-Module -ListAvailable Az to find the installed version. If you need to upgrade, see Install Azure PowerShell module. If you are running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

Create a network security group

A network security group contains security rules. Security rules specify a source and destination. Sources and destinations can be application security groups.

Create application security groups

First create a resource group for all the resources created in this article with New-AzResourceGroup. The following example creates a resource group in the eastus location:

New-AzResourceGroup -ResourceGroupName myResourceGroup -Location EastUS

Create an application security group with New-AzApplicationSecurityGroup. An application security group enables you to group servers with similar port filtering requirements. The following example creates two application security groups.

$webAsg = New-AzApplicationSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Name myAsgWebServers `
  -Location eastus

$mgmtAsg = New-AzApplicationSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Name myAsgMgmtServers `
  -Location eastus

Create security rules

Create a security rule with New-AzNetworkSecurityRuleConfig. The following example creates a rule that allows traffic inbound from the internet to the myWebServers application security group over ports 80 and 443:

$webRule = New-AzNetworkSecurityRuleConfig `
  -Name "Allow-Web-All" `
  -Access Allow `
  -Protocol Tcp `
  -Direction Inbound `
  -Priority 100 `
  -SourceAddressPrefix Internet `
  -SourcePortRange * `
  -DestinationApplicationSecurityGroupId $webAsg.id `
  -DestinationPortRange 80,443

The following example creates a rule that allows traffic inbound from the internet to the *myMgmtServers* application security group over port 3389:

$mgmtRule = New-AzNetworkSecurityRuleConfig `
  -Name "Allow-RDP-All" `
  -Access Allow `
  -Protocol Tcp `
  -Direction Inbound `
  -Priority 110 `
  -SourceAddressPrefix Internet `
  -SourcePortRange * `
  -DestinationApplicationSecurityGroupId $mgmtAsg.id `
  -DestinationPortRange 3389

In this article, RDP (port 3389) is exposed to the internet for the myAsgMgmtServers VM. For production environments, instead of exposing port 3389 to the internet, it's recommended that you connect to Azure resources that you want to manage using a VPN or private network connection.

Create a network security group

Create a network security group with New-AzNetworkSecurityGroup. The following example creates a network security group named myNsg:

$nsg = New-AzNetworkSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -Name myNsg `
  -SecurityRules $webRule,$mgmtRule

Create a virtual network

Create a virtual network with New-AzVirtualNetwork. The following example creates a virtual named myVirtualNetwork:

$virtualNetwork = New-AzVirtualNetwork `
  -ResourceGroupName myResourceGroup `
  -Location EastUS `
  -Name myVirtualNetwork `
  -AddressPrefix 10.0.0.0/16

Create a subnet configuration with New-AzVirtualNetworkSubnetConfig, and then write the subnet configuration to the virtual network with Set-AzVirtualNetwork. The following example adds a subnet named mySubnet to the virtual network and associates the myNsg network security group to it:

Add-AzVirtualNetworkSubnetConfig `
  -Name mySubnet `
  -VirtualNetwork $virtualNetwork `
  -AddressPrefix "10.0.2.0/24" `
  -NetworkSecurityGroup $nsg
$virtualNetwork | Set-AzVirtualNetwork

Create virtual machines

Before creating the VMs, retrieve the virtual network object with the subnet with Get-AzVirtualNetwork:

$virtualNetwork = Get-AzVirtualNetwork `
 -Name myVirtualNetwork `
 -Resourcegroupname myResourceGroup

Create a public IP address for each VM with New-AzPublicIpAddress:

$publicIpWeb = New-AzPublicIpAddress `
  -AllocationMethod Dynamic `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -Name myVmWeb

$publicIpMgmt = New-AzPublicIpAddress `
  -AllocationMethod Dynamic `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -Name myVmMgmt

Create two network interfaces with New-AzNetworkInterface, and assign a public IP address to the network interface. The following example creates a network interface, associates the myVmWeb public IP address to it, and makes it a member of the myAsgWebServers application security group:

$webNic = New-AzNetworkInterface `
  -Location eastus `
  -Name myVmWeb `
  -ResourceGroupName myResourceGroup `
  -SubnetId $virtualNetwork.Subnets[0].Id `
  -ApplicationSecurityGroupId $webAsg.Id `
  -PublicIpAddressId $publicIpWeb.Id

The following example creates a network interface, associates the myVmMgmt public IP address to it, and makes it a member of the myAsgMgmtServers application security group:

$mgmtNic = New-AzNetworkInterface `
  -Location eastus `
  -Name myVmMgmt `
  -ResourceGroupName myResourceGroup `
  -SubnetId $virtualNetwork.Subnets[0].Id `
  -ApplicationSecurityGroupId $mgmtAsg.Id `
  -PublicIpAddressId $publicIpMgmt.Id

Create two VMs in the virtual network so you can validate traffic filtering in a later step.

Create a VM configuration with New-AzVMConfig, then create the VM with New-AzVM. The following example creates a VM that will serve as a web server. The -AsJob option creates the VM in the background, so you can continue to the next step:

# Create user object
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

$webVmConfig = New-AzVMConfig `
  -VMName myVmWeb `
  -VMSize Standard_DS1_V2 | `
Set-AzVMOperatingSystem -Windows `
  -ComputerName myVmWeb `
  -Credential $cred | `
Set-AzVMSourceImage `
  -PublisherName MicrosoftWindowsServer `
  -Offer WindowsServer `
  -Skus 2016-Datacenter `
  -Version latest | `
Add-AzVMNetworkInterface `
  -Id $webNic.Id
New-AzVM `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -VM $webVmConfig `
  -AsJob

Create a VM to serve as a management server:

# Create user object
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create the web server virtual machine configuration and virtual machine.
$mgmtVmConfig = New-AzVMConfig `
  -VMName myVmMgmt `
  -VMSize Standard_DS1_V2 | `
Set-AzVMOperatingSystem -Windows `
  -ComputerName myVmMgmt `
  -Credential $cred | `
Set-AzVMSourceImage `
  -PublisherName MicrosoftWindowsServer `
  -Offer WindowsServer `
  -Skus 2016-Datacenter `
  -Version latest | `
Add-AzVMNetworkInterface `
  -Id $mgmtNic.Id
New-AzVM `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -VM $mgmtVmConfig

The virtual machine takes a few minutes to create. Don't continue with the next step until Azure finishes creating the VM.

Test traffic filters

Use Get-AzPublicIpAddress to return the public IP address of a VM. The following example returns the public IP address of the myVmMgmt VM:

Get-AzPublicIpAddress `
  -Name myVmMgmt `
  -ResourceGroupName myResourceGroup `
  | Select IpAddress

Use the following command to create a remote desktop session with the myVmMgmt VM from your local computer. Replace <publicIpAddress> with the IP address returned from the previous command.

mstsc /v:<publicIpAddress>

Open the downloaded RDP file. If prompted, select Connect.

Enter the user name and password you specified when creating the VM (you may need to select More choices, then Use a different account, to specify the credentials you entered when you created the VM), then select OK. You may receive a certificate warning during the sign-in process. Select Yes to proceed with the connection.

The connection succeeds, because port 3389 is allowed inbound from the internet to the myAsgMgmtServers application security group that the network interface attached to the myVmMgmt VM is in.

Use the following command to create a remote desktop connection to the myVmWeb VM, from the myVmMgmt VM, with the following command, from PowerShell:

mstsc /v:myvmWeb

The connection succeeds because a default security rule within each network security group allows traffic over all ports between all IP addresses within a virtual network. You can't create a remote desktop connection to the myVmWeb VM from the internet because the security rule for the myAsgWebServers doesn't allow port 3389 inbound from the internet.

Use the following command to install Microsoft IIS on the myVmWeb VM from PowerShell:

Install-WindowsFeature -name Web-Server -IncludeManagementTools

After the IIS installation is complete, disconnect from the myVmWeb VM, which leaves you in the myVmMgmt VM remote desktop connection. To view the IIS welcome screen, open an internet browser and browse to http://myVmWeb.

Disconnect from the myVmMgmt VM.

On your computer, enter the following command from PowerShell to retrieve the public IP address of the myVmWeb server:

Get-AzPublicIpAddress `
  -Name myVmWeb `
  -ResourceGroupName myResourceGroup `
  | Select IpAddress

To confirm that you can access the myVmWeb web server from outside of Azure, open an internet browser on your computer and browse to http://<public-ip-address-from-previous-step>. The connection succeeds, because port 80 is allowed inbound from the internet to the myAsgWebServers application security group that the network interface attached to the myVmWeb VM is in.

Clean up resources

When no longer needed, you can use Remove-AzResourceGroup to remove the resource group and all of the resources it contains:

Remove-AzResourceGroup -Name myResourceGroup -Force

Next steps

In this article, you created a network security group and associated it to a virtual network subnet. To learn more about network security groups, see Network security group overview and Manage a network security group.

Azure routes traffic between subnets by default. You may instead, choose to route traffic between subnets through a VM, serving as a firewall, for example. To learn how, see Create a route table.