How To Assign A Public Static IP Address In Azure Using Azure Resource Manager

In this post I’m going to show you how to assign a public static IP address in Azure using Azure Resource Manager, if you are using the classic deployment model use this link.

Contrasting Classic Deployment With ARM
In ARM you don’t have a cloud service that is the container for your VM, load balancer, public IP and other functionality any more. The different components that make up your environment is clearly separated and you compose your environment by stitching together the pieces you need. For example, you can create a network interface card on it’s own, it doesn’t have to be part of a VM and you can move it between VMs or attach it to a load balancer etc. Same goes for your public IP addresses, load balancers, network groups etc. That said you can create everything you need for your environment in the same ARM template giving you that feeling of cohesion.

Creating A Public IP address Using The Portal
When you create a new VM in the portal the default setting is to create a new dynamic public IP address along with the VM. You can change it to be static or use an existing public IP address if need be or you can choose None if you don’t want your VM to be directly accessible from the internet.

Nic

Note that even if you choose to have a public IP address for your VM it won’t have a DNS name, at the time of writing you can’t assign a DNS name when you create the VM in the portal, you have to do it  afterwards, instructions here.

Creating a public IP address using ARM templates

{
  "apiVersion": "2015-06-15",
  "type": "Microsoft.Network/publicIPAddresses",
  "name": "mynewpublicip",
  "location": "[resourceGroup().location]",
  "properties": {
  "publicIPAllocationMethod": "static", //or dynamic
    "dnsSettings": {
    "domainNameLabel": "testing8423"
    }
  }
}

The DNS settings are optional and will create a DNS entry with your label and the name of the Azure region for example: testing8423.westus.cloudapp.azure.com. On your NIC template you reference the public IP address.

...
 "name": "defaultNICName",
  "dependsOn": [
 "Microsoft.Network/publicIPAddresses/mynewpublicip",
 "Microsoft.Network/virtualNetworks/virtualNetworkName"],
 "properties": {
 "ipConfigurations": [
 {
  "name": "DefaultNicIpconfig",
  "properties": {
  "privateIPAllocationMethod": "Dynamic",
  "publicIPAddress": {
   "id":"[resourceId(Microsoft.Network/publicIPAddresses       /mynewpublicip)]"
 },...

Note: I removed some of the JSON elements for sake of readability.

Creating a public IP address using PowerShell
I didn’t try it myself since I’ve been using ARM Templates of late but it looks easy enough. You create a new public IP address with New-AzureRmPublicIpAddress and then you create a new NIC and assign the IP address to it using New-AzureRmNetworkInterface and the -PublicIpAddress or -PublicIpAddressID parameter.

New-AzureRmPublicIpAddress -Name IPName -AllocationMethod Static/Dynamic -ResourceGroupName ... 

New-AzureRmNetworkInterface-PublicIpAddress<PSPublicIpAddress> -ResourceGroupName... -IpConfiguration ... -Location ... -Name ...

White Listing Public IPs
When you create a new public IP address you get one from the block of IP addresses Microsoft owns, so you can’t choose a specific one. If you have a requirement to white list specific public IP addresses for the long term you’ll have to create the public static IP upfront and retrieve the allocated IP address.  You can assign the public IPs to NICs as required. You can white list a range of Azure IP addresses downloaded from here but that isn’t always practical.

Francois Delport

Azure Network Security Groups

This post is a summary and some links to documentation regarding Azure network security groups, it might useful if you are in need of a quick introduction to the subject.

Exposing a virtual machine to the internet
Before I get into network security groups I want to talk about the way Azure virtual machines are exposed to the internet using the Azure resource manager deployment method. By default when you create a new virtual machine using ARM in the new portal it will have a public IP address, the public IP address will be dynamic so it can change when the machine is restarted, you can make it static if need be for a monthly fee. The VM will not have a DNS name and you can’t specify one in the create VM wizard. You can add the DNS label after the machine is created or you can create the public IP separately with a DNS label and then point the new VM to use the existing public IP when you create it. The default network security group created with the VM will have a rule to allow RDP connections to this VM and some default rules used by Azure infrastructure. You can also use load balancers but that is a different story all together.

What Are Network Security Groups?
Short version (based on documentation link below): A network security group contains a list of rules that allow or deny traffic to a specified port or port range at a subnet or network interface card level. The rules also take into account the direction of the traffic, so it is not just for inbound traffic, you can also restrict outbound traffic. Applying the network security group at a subnet level will apply the rules to all the network cards in the subnet. Applying the network security group at network card level will only apply to that network card, if you have multiple network cards in a VM each one can have it’s own network security group. When you create your own rules take care not to block traffic to the 168.63.129.16 IP address and also port 1688, these are used by Azure internally for DHCP, DNS, Windows Licensing etc. Take note when using load balancers, your load balancer is backed by a pool of NICs, you should apply the network security group to the backend NIC pool to ensure all traffic passes through to the network security group, even traffic that didn’t pass though the load balancer.

Official documentation, very long but very informative read.

Practical Application Of Network Security Groups
Creating a DMZ is one of the important capabilities we get from network security groups, that said there are various options when creating a DMZ and it gets quite complicated. Options include using network security groups only, using vendor firewall devices and creating custom routes for traffic. I’ll briefly talk about the simplest option using only network security groups. At a very simplified level creating a DMZ for you application involves separating the physical layers of your application based on the traffic they will receive/send and restricting the traffic to the absolute minimum between the layers and the internet. In this example below the IIS front end and SQL back end are on different subnets and each subnet has its own network security group. All traffic from the internet and between subnets are interrogated by the network security groups against their rules. All traffic should be blocked by default and then you add rules to allow specific ports. In this example the allowed traffic are the orange lines for RDP to both subnets, HTTP traffic to the website and SQL traffic between the front end subnet and the back end subnet. There are no rules for the outgoing traffic in this example. Setting up outgoing rules can be a bit tricky since most application can respond on a range of addresses.

Azure Network Security Groups

The links to the official documentation and DMZ examples are below:

Build a Simple DMZ with NSGs

Build a DMZ to protect applications with a Firewall and NSGs

Build a DMZ to Protect Networks with a Firewall, UDR, and NSG

Francois Delport

Manage Azure Networks Using The .NET Azure Management Libraries

In this post I’m going to show you how to manage Azure Networks using the .NET Azure Management libraries.

In general I find the Azure Management Libraries a pleasure to work with except for the network management library. Retrieving your network configuration is easy enough but using it to configure your network is more difficult than it should be. I did this investigation out of curiosity more than anything else and I recommend using PowerShell to manage Azure instead of the management library. But enough ranting and on to the demo.

I used Visual Studio 2015 for this demo and .Net 4.5, I already had the Azure SDK installed in my environment so I’m not sure if it is a requirement for the management libraries but I doubt it.

For this demo I used an empty console project but there are project templates for Azure management projects in Visual Studio if you want to do something more complicated.

Manage Azure Networks Using The .NET Azure Management Libraries

After creating the your console application install the management library nuget packages.

install-package microsoft.windowsazure.management

It will install a slew of other packages so it might take a few minutes on a slow internet connection.

To create the credentials you need to manage Azure you have to download your .publishsettings file, if you are not sure how to do it look here it is in the first part of the post. Open the .publishsettings file in a text editor and copy the Id and ManagementCertificate strings and paste them into the code below.

var cred = new Microsoft.Azure.CertificateCloudCredentials("yoursubid", new X509Certificate2(Convert.FromBase64String("yourcert")));

The retrieve your network settings use the NetworkManagementClient class with your credentials created above and iterate over the properties in the Networks object, for example to list subnets:

using (var netclient = new NetworkManagementClient(cred))
{
var networks = netclient.Networks.List();
Console.WriteLine("Networks:");
networks.VirtualNetworkSites.ToList().ForEach(x =>
{
Console.WriteLine(x.Name);
x.Subnets.ToList().ForEach(y => Console.WriteLine(y.Name + " " +              y.AddressPrefix));
}
);
}

This was the easy part, to configure your network you have to retrieve the current configuration as xml, manipulate it and then send it back to Azure.

var config = netclient.Networks.GetConfiguration();


XmlDocument doc = new XmlDocument();
doc.LoadXml(config.Configuration);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

string rootns = @"http://schemas.microsoft.com/ServiceHosting/2011/07/NetworkConfiguration";
nsmgr.AddNamespace("ns1",rootns );

var subnets = doc.SelectSingleNode("//ns1:Subnets",nsmgr);

//Create SubNet node
XmlNode newsub = doc.CreateNode(XmlNodeType.Element, "Subnet", rootns);
XmlAttribute subname = doc.CreateAttribute("name");
subname.Value = "NewSubName";
newsub.Attributes.Append(subname);

//Create AddressPrefix node
XmlNode newaddr = doc.CreateNode(XmlNodeType.Element, "AddressPrefix", rootns);
newaddr.InnerText = "10.32.1.0/24";
newsub.AppendChild(newaddr);

//Add to Subnets
subnets.AppendChild(newsub);

var sw = new System.IO.StringWriter();
doc.WriteContentTo(new XmlTextWriter(sw));
var newconfig = new NetworkSetConfigurationParameters(sw.ToString());

var result = netclient.Networks.SetConfiguration(newconfig);

Console.WriteLine(result.Status);

At least it is worth all the trouble and you end up with a new subnet.

Manage Azure Networks Using The .NET Azure Management Libraries

Francois Delport

How To Assign A Public Static IP Address In Azure

In this post I’m going to show you how to assign a public static IP address in Azure. There are a few different IP address concepts in Azure to discuss before I get to assigning public static IPs.

VIP
When you create a Cloud Service you get a virtual IP address (VIP), this is your public IP address for the Cloud Service, your Cloud Service DNS name resolves to this IP address. By default it is randomly assigned from a pool of addresses but you can reserve one. There is a limit of 5 reserved public IP addresses per subscription. This is also the source IP address for traffic originating from VMs in the service. You can only assign a reserved VIP when you create the Cloud Service. When traffic hits your VIP it goes through the Azure Load Balancer and then it is forwarded to the endpoints you setup in your Cloud Service.

DIP
The VMs you create also get an internal IP address (DIP) for each NIC attached to the VM. The DIP is used to communicate with VMs in the same Cloud Service or VNET. The NIC will keep the same DIP until it is stopped or deallocated. The DIP is assigned via DHCP but you can reserve one by adding your VM to a subnet and reserving a static IP.

PIP/ILPIP
Instance level public IP (ILPIP) is assigned directly to a VM and bypasses the Azure Load Balancer. Outgoing traffic from the VM will show the ILPIP as the source instead of the VIP. You don’t have to map endpoints to forward ports like you do with endpoints in the VIP since all ports are open to the internet but you have to setup the firewall on your VM to protect it. ILPIP is useful for passive FTP or anything that requires a large number of open ports. You cannot reserve a ILPIP. You can assign a ILPIP to existing VMs. You can access your VM directly over the internet using the ILPIP but since it changes when you stop the VM it is not very useful unless you also assign a DNS name to the VM.

Reserved VIP
When you reserve an IP in Azure it is not assigned to a Cloud Service by default, it goes into a pool of reserved IP addresses in your subscription. You then assign them to Cloud Services and roles or release them back into your pool. You pay for reserved IP addresses in your subscription even when it is not assigned to a Cloud Service so it is better to delete them if you know you will not need it again soon.

Assigning A Reserved VIP
To reserve a new IP address run:
New-AzureReservedIP –ReservedIPName "MyReservedIP" –Location "AzureRegionName"

To see the list of reserved IP addresses for you subscription:
Get-AzureReservedIP

To remove the the reserved IP address from your subscription:
Remove-AzureReservedIP -ReservedIPName "MyReservedIP"

You can assign the reserved IP address to a virtual machine when creating it but not to an existing one so it is important to plan the IP address assignment before the time. You have specify at least one endpoint when you use a reserved IP.

$VM = New-AzureVMConfig -Name $VmName -InstanceSize $InstanceSize -ImageName $SourceName

$VM |  Add-AzureEndpoint -Name "Remote Desktop" -Protocol "tcp" -PublicPort 3389 -LocalPort 3389

$VM |  Add-AzureEndpoint -Name "PowerShell" -Protocol "tcp" -PublicPort 5986 -LocalPort 5986

New-AzureVM -ServiceName "NewServiceName" -ReservedIPName "MyReservedIP" -Location "AzureRegionName" -VM $VM

Although you add the reserved IP to a VM when creating it, it will actually be the VIP for your cloud service.

Assigning A LPIP
You can assign LPIPs to existing VMs or new ones but keep in mind you cannot reserve the IP. You can see full example here, but the syntax is the same, you pipe Set-AzurePublicIP to Get-AzureVM or New-AzureVM.

Get-AzureVM -ServiceName "ServiceName" -Name VMName | Set-AzurePublicIP -PublicIPName "LPIPName" | Update-AzureVM

You can also pass in the DomainNameLabel parameter if you have a DNS entry you want to use with this IP.

Update: This post covers the classic deployment model, the ARM version is here.

Francois Delport

Change The MAC Address On Your Azure Virtual Machine

Today I’m going to show you how to add a second NIC to an Azure Virtual Machine and how to change the MAC Address on your Azure Virtual Machine.

I had this requirement while automating the deployment of a component that is license locked to the MAC address of a NIC. In itself this is not a problem but combined with Azure and our deployment workflow it presented some challenges. As part of the deployment workflow the Azure VM is deleted and restored from a VHD image. Since this process creates a new VM and new NICs you also get a new MAC address every time which caused the license check to fail.

To avoid interfering with the normal operation of the networking in Azure I thought it best to add a second NIC on its own subnet and use it for the license while leaving the default NIC intact.

So the first step was to create a new subnet and to give it a different IP address range from the default NIC.

Change The MAC Address On Your Azure Virtual Machine

The second step is to add another NIC to the VM when you create it:

Add-AzureNetworkInterfaceConfig -Name "LicenseNIC" -SubnetName "License" -VM $NewVM

Thirdly there is the PowerShell script to change the MAC address when the new VM is created. Credit to Jason Fossen for the original script. This script is executed on the VM itself not against Azure. You can use Invoke-Command for instance as part of your deployment script to execute it remotely on the VM.

In the script I identify the NIC  used for licencing based on it’s IP address 10.32.2.* and then I  retrieve the index number for this NIC. This index is the same one used to find this NIC in the registry.

$indexobj = Get-WmiObject win32_networkadapterconfiguration -Filter "ipenabled = 'true'" | Where-Object {$_.IPAddress -like "10.32.2.*" } | Select-Object -Property Index
$index = $indexobj.index

The registry key for the NIC always has four digits, so padleft, then get the key.

$index = $index.tostring().padleft(4,"0")
$regkey = get-item "hklm:\system\CurrentControlSet\control\class\{4D36E972-E325-11CE-BFC1-08002BE10318}\$index"

Set a new value for MAC address, in this case 30-D5-1E-DD-F2-A5.
$regpath = "hklm:\system\CurrentControlSet\control\class\{4D36E972-E325-11CE-BFC1-08002BE10318}\$index"
set-itemproperty -path $regpath -name "NetworkAddress" -value $("30-D5-1E-DD-F2-A5")

If the NIC is not refreshed the new MAC address is not picked up by the licensing component we used. This may not be neccesary depending on your use case.

ipconfig.exe /release """$($thenic.netconnectionid)""" | out-null
$thenic.disable() | out-null
$thenic.enable() | out-null
ipconfig.exe /renew """$($thenic.netconnectionid)""" | out-null

If you now look at your NIC properties you will see the new MAC address.

Change The MAC Address On Your Azure Virtual Machine

PS. On my Windows 10 machine it didn’t display properly on the NIC properties but you can use ipconfig /all to see the MAC address.

Francois Delport