Network Security Group: Restrict Access between Azure Subnets

In this post we will be going through configuring Network Security Group’s to restrict access between subnets under a single vNet.

Routing between subnets happens automatically and is allowed by default.

This can allow resources communicate over any port and there is no network access control.

To make the Azure network more secure this should be restricted as much as possible to only allow the required communication.

Below is a link to the Microsoft network best practice.

https://learn.microsoft.com/en-us/azure/security/fundamentals/network-best-practices?toc=https%3A%2F%2Flearn.microsoft.com%2Fen-us%2Fazure%2Farchitecture%2Ftoc.json&bc=https%3A%2F%2Flearn.microsoft.com%2Fen-us%2Fazure%2Farchitecture%2Fbread%2Ftoc.json#logically-segment-subnets

One way to limit the communication is to use NSG’s.

In this example we will be using a 10.10.1.0/24 address space

Address Space

Then we will be creating multiple subnets with /28 mask.

Subnets

I have added one server to both the Ops and Mgmt subnets. Now if we make a connection between each VM the traffic will be routed directly between both VM’s.

trace route

Next, we will setup the NSG to only allow connection between the subnets for RDP and SMB. In this case we will be creating an NSG per subnet, but this could be done in one NSG.

Network Security Group

Next, we need to create two new inbound rules one to allow the required ports and the second to deny all other access.

Go to inbound rules and select Add.

Add rule

Added in the required details

·       Source: IP Address

·       Source Port: 

·       Destination: IP Address

·       Destination IP Address:

·       Service: Custom

·       Destination Port Ranges:

·       Protocol TCP

·       Action: Allow

·       Priority: 110

·       Name: Allow_Mgmt_Subnet_Access

Allow inbound rule

Next, we will create the deny rule.

 

Deny inbound rule

I would usually set the deny to a much lower priority, so that if more rules are required in the future there won’t be an issue with the deny rule having a higher priority and blocking the traffic. 

Once saved, the allow and deny rule should show under inbound rules.

Now when we try to run tracert again, this time we won’t be able to connect.

 

Tracert

If we try open a connection using SMB, we can connect without issue.

To block access back to the other subnet we will need to create the same rules but with the opposition subnet source and destination IP ranges.

After creating both set of NSG rules there will be no access between the subnets on any port other than those specified in the inbound rules.

Microsoft Graph: Restrict Access Using Conditional Access Policy

In this post we will be going through setting up a conditional access policy to allow connection’s to a Microsoft App Registration that will be used for calling Microsoft GraphAPI from only certain countries / public IP’s.

Microsoft has a preview feature in Conditional Access for workload identities. A workload identity is an identity which allows an application or service principal access to resources.

When an App Registration is created, it will create a service principal. This service principal is what we will use in the conditional access policy.

First we need to create the named location to define where we want to allow the access from.

To create a named location go to endpoint management admin page.

https://endpoint.microsoft.com/

Go to Endpoint security > Conditional access.

MEM Admin Page

Once in Conditional access, go to Named location and add the required countries locations and or IP ranges.

Named locations

To add as single IP use /32 bit subnet mask.

IP range

Once we have the named locations we can create the Conditional access policy.

Go to the policies tab and click on new policy.

Policies page

Give the policy a name and set the assignment to workload identities.

Conditional access policy

Next select the service principal for the Graph App registration.

Users or workload selection

Next on Cloud apps or actions select, All cloud apps

Cloud apps or actions selection

Next we need to specify which location will be included, which we set to any location as we will use the exclude to allow access from the named location we will connect from.

Conditions selection

Next select the location that will be excluded from the policy in my case it will be the public IP we added earlier to the named location.

Excluded Locations

Next we set the access, I will be blocking access as I only want to allow access from the one public IP we specified in the excluded location.

Access selection

With any conditional access policy I would recommend setting the policy to Report-only to confirm that only the access that we excepted to be blocked is.

Policy settings enabled section

To check if the policy is applying correctly against the service principal we can check the sign-in logs.

First connect using Graph query and then go to sign-in logs.

MEM Admin Blade

Select service principal sign-ins.

Sign-in logs

Click on the request ID and look at the Report-only tab to see if the access would have been blocked or allowed.

Sign-in logs

Once we confirm that the policy is applying the correct access, the conditional access can be set to on.

Now once we try to connect from an IP or location not on the excluded list, it will be blocked from accessing.

Graph Connection

When we connect from an allowed location, we will get back the access token and be allowed to connect.

Graph Connection Token

When creating App registration we should look at access controls for these as this can be over looked and lead to a security risk, most application do not need access from any location and should be limited to only the require location or IP address to give greater access control.

Microsoft Graph: Restrict Exchange Online Mailbox Access

Recently we have been reviewing some of our old Exchange Web Service mailbox connections and updating these to use Microsoft Graph. We wanted to restrict what mailbox’s the Azure App registration used for Microsoft Graph could connect to.

To set this up in Exchange Online we can use an Application Access Policy. In this post we will be going through setting up and confirming the mailbox’s access.

I have gone through setting up Azure App registration for Microsoft Graph before so we wont be going through that in this post.

I will also be using certificate and Microsoft MSAL PowerShell Module to get the Graph access token.

See post below if you need to know how to connect using MSAL with certificate base authentication.

Once we have the app registration setup and certificate issued and uploaded to the app registration, we can then assign the GaphApi permission to access mailboxes.

If we don’t apply the permission we will get access denied.

Graph Message Access Error

I will be giving Mail.Read API permission, this will give access to view all mailboxes.

Graph API Permissions

Grant admin consent for the API permission.

Now if we try to query the mailbox we should now be able to see the messages.

Graph Message Response

At this stage we can use the App registration to read messages from any mailboxes.

To lock this down so that the Graph query is only able to view certain mailboxes we can use

New-ApplicationAccessPolicy

to create an application access policy. The policy can be applied to a group or a single users.

To run the command, we will need Application ID of the app registration, mailbox or mail enabled security group and description. Using a group is useful if there are multiple mailboxes that they will need to allow access.

New-ApplicationAccessPolicy -AppId ApplicationID -PolicyScopeGroupId "user_group@domain.com" -AccessRight RestrictAccess -Description "Restrict this app to view mailbox or security group."

To run the command we need to connect to Exchange Online

Connect-ExchangeOnline

Then run the command to create the application access policy.

We can test what mailboxes the app registration can access using.

Test-ApplicationAccessPolicy -AppId ApplicationID -Identity user_group@domain.local

Now once we try to query the mailbox we have give access to we will see the message returned, if we try query any other mailbox we will an error message.

Applying the application access policy is a good idea for security as allowing an application to read mailboxes that it doesn’t need access to can be a risk if the app was ever compromised or there is sensitive data in mailboxes that no other users or application should have access to.

Patching VMware vCenter 7.0 Server Appliance Using CLI

There are a few different way’s to update to vCenter server appliance (VCSA). In this post we will be going through using CLI method to apply vCenter patches. Before updating VCSA make sure you have a current backup and take a snapshot before proceeding in case of any issues with the update.

First we need to connect to the vCenter server using SSH. I will be using the inbuilt OpenSSH feature in PowerShell but you can use what ever SSH client you prefer.

To enable SSH on vCenter logon to the management page using the vCenter URL with port 5480 (https://vcenter.domain.local:5480).

Go to Access and click edit to enable SSH Login.

vCenter Management UI

Next we need to connect to the vCenter server using ssh.

vCenter SSH Login

Next we can run the below command to view the vCenter update history

software-packages list --history
Patch List

We can use the below command. This will list the current update settings, if the vCenter server has no internet access then you could update the URL to use an internal web site that contains the update files.

update.get
Update configuration

We will be using the default URL from the update.get command when running the update

software-packages install --url https://vapp-updates.vmware.com/vai-catalog/valm/vmw/8d167796-34d5-4899-be0a-6daade4005a3/7.0.3.00100.latest/ --stage --acceptEulas

This command will download, stage the update and install.

Update staging

Once stage the update will then start to install.

Update Installing

The update can take awhile to complete.

Update Completion

Once the update has completed, vCenter should reboot if required to complete the install.

When the appliance boots backup we can re-connect to confirm we are now running on the updated VCSA version.

vCenter SSH Login

Azure App Registrations Cert / Client Secret MS Graph Report

In this post we will be looking at creating a report to show what Azure App registrations have expiring client secret / certificate in the specified amount of days.

There is currently no in built way to report on expiring App registrations in the Azure portal other than checking the app registration, so we will be using Microsoft Graph SDK to automate the reporting.

First to automate the report we need to create an app registration to use for the Microsoft Graph connection. I have gone through this in a previous post.

The specific Microsoft GraphApi application permission required is Application.Read.All, this needs to be added to the App Registration that we use for Microsoft Graph.

App Registration API Permission

Next we need to connect to Microsoft Graph using.

Connect-MgGraph

To list the app registration use

Get-MgApplication
Microsoft Graph Applications

Once we have the list of apps we can use PasswordCredentials to view client secret details

(Get-MgApplication).PasswordCredentials
Application Secrets Properties

and KeyCredentials to view the certificates details

Application Certificate Properties

Once we have the required properties, we can create the script to export the app registration details.

App Registration Report

There are two parameters Reportonly which returns just the result to PowerShell window and ReportExport which will export the report to the specific folder specified.

Below is what the Reportonly should look like.

.\Get-AppRegistrationDetails.ps1 -CertificateThumbprint Thumprint -ClientId ClientID -TenantId TenantID -ReportOnly -ExpiryDate 200
Report results

When using the Reportexport

.\Get-AppRegistrationDetails.ps1 -CertificateThumbprint thumbprint -ClientId ClientID -TenantId TenantID -ReportExport C:\temp\Graph\ -ExpiryDate 200

The full script can be downloaded from the below GitHub link.

https://github.com/TheSleepyAdmin/Scripts/blob/master/MSGraph/AppRegistration/Get-AppRegistrationDetails.ps1

Create Local ESXi Account Using PowerCLI

In this post we will be going through creating local ESXi account using PowerCLI.

Recently I have had to create local account to allow a monitoring tool to pull information from all ESXi hosts.

We want to automate the user creation and assign the required permissions so that they only have the permission required for a limited time.

First we need to connect to the ESXi Host using PowerCLI

Connect-VIServer
Connection to vCenter

To check what account already exist use the below.

Get-VMHostAccount
List Accounts

To create a new account we will use the New-VMHostAccount command

New-VMHostAccount -Id accountname -Password password -Description Account Description
Create new account

Next we need to assign the required permissions. We can list the current roles using

Get-VIRole
List VMware Roles

We also need an entity to set the permission or the command will error out.

Permission

To list the entity use the

Get-Folder
List Folder

Select the entity that will have the role applied. In this case we will be applying to the root object so it applies to all objects on the host and will assigning the admin role.

New-VIPermission -Entity (Get-Folder root) -Principal accountname -Role Admin
Set Permission

To remove the account use the below command.

Get-VMHostAccount -User account name | Remove-VMHostAccount -Confirm:$false

Once we have the commands, we can create the script to automate the account creation and role assignment to configure multiple hosts.

Account Creation Script

The scripts uses EsxiHost as the heading for the CSV if you want to use something different the script will need to be updated.

Below is the script running against my test hosts.

.\Create-LocalESXiUser.ps1 -ESXiHostList .\EsxiHosts.csv -ESXiUser useraccount -ESXipass password -ESXiNewUser accountname -ESXiUserPass accountpass -ESXiPermission Permission -ESXiUserdesc "Account Description"
Account creation script

This process can also be used to update the permission for a specific account.

Updating permissions

To download the full script use the below link to github.

https://github.com/TheSleepyAdmin/Scripts/blob/master/VMware/Config/Account/Create-LocalESXiUser.ps1

Configure SNMP On VMware ESXi Using PowerCLI

In this post we will be going through deploying new SNMP configuration to a list of ESXi hosts using PowerCLI. We can add SNMP using ssh and esxcli commands but this will required SSH to be enabled and connecting to each host.

We can use Set-VMHostSNMP command to set the SNMP configuration by conecting to the host using connect-viserver which uses https to connect and does not required SSH to be enabled.

First we need to connect to the ESXi host

Connect-VIServer -Server esxihost.domain.local

use a local account like root to connect

PowerCLI SNMP Command

If you get a certificate error and can’t connect you might need to update the PowerCLI Configuration or install the root cert to trust the self singed cert of the ESXi hosts.

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

Once connected we will be using the below set of command to configure the SNMP settings.

Get-VMHostSnmp | Set-VMHostSnmp

https://developer.vmware.com/docs/powercli/latest/vmware.vimautomation.core/commands/set-vmhostsnmp/#Default

First we will enabled and set the community string

Get-VMHostSnmp | Set-VMHostSnmp -Enabled:$true -ReadOnlyCommunity communityname

PowerCLI SNMP Command

Next we will set the target that traps will be sent.

Get-VMHostSnmp | Set-VMHostSnmp -TargetCommunity communityname -TargetHost snmp.domain.local -TargetPort 162 -AddTarget
PowerCLI SNMP Command

To test I have setup snmp on Ubutu

Ubuntu SNMP check

Now that we have set of command we can create the script. I will be doing a loop through each host and configuring the SNMP.

I also added in some if statement to check if SNMP is already enabled and to check if the target host matches the one that is set in the parameters.

SNMP Script

The full script can be downloaded from the below github link.

https://github.com/TheSleepyAdmin/Scripts/blob/master/VMware/Config/SNMP/Set-ESXiSNMP.ps1

Below is an example of what the csv file should look like if you want to use a different heading the script will need to be updated.

Each of the values will be called as parameter to allow easy re-use below is an example of the SNMP script running against my test hosts.

Using PowerCli can be a quicker way to set and enabled SNMP on a list of hosts rather than having to SSH and use esxcli command. This can also be used to update the existing SNMP configuration to a new traps target.

Using Stored Access Policy with Azure Storage

In this post we will be going through setting up and using stored access policy with Azure storage account. We can create SAS URL but each time we create one there is no way to revoke without rotating the storage keys.

A stored access policy can be used to control shared access signatures (SAS) on the server side. We can use a stored access policy to change the start time, expiry time, or permissions for a SAS URL that is generated from a storage account. We can also revoke access after it has been issued with out having to rotate the storage keys.

Below are the storage resources that support stored access policies:

  • Blob containers
  • File shares
  • Queues
  • Tables

First we will create a new storage account in Azure.

Logon to Azure and go to storage accounts. Click Create and add in the basic details and I left the rest as default.

Azure storage account wizard

Once the storage account is deployed, we will be creating a container in the below example its called files.

Blob Container

Go in to the container and create a policy under Access policy.

Blob Container

Give the policy a name, set the required permission and start / end date. Click ok and then save the policy.

Access Policy

Once the policy is create it will show under access policy.

Now that we have the access policy we will need to create a new SAS. There are two ways to create this.

First we can create it directly from Azure storage under Shared access tokens.

Select the Stored access policy. We can also restrict access down to a specific IP.

Next click on Generate SAS token and URL.

We can also use Azure Storage Explorer to create a new SAS.

Azure Storage can be downloaded from:

https://azure.microsoft.com/en-us/features/storage-explorer/

Logon with an account that has access to the storage account.

Select the storage account that we want to create the SAS for.

Azure Storage Explorer

Select the Access policy, this will then grey out all the options as we are now using the access policy for the SAS.

shared access signature

Click create and this will generate the URL with the SAS key and will also reference the access policy

shared access signature

To test access to the blob we can connect using Storage Explorer.

Click on the connect to Azure Storage and select Blob container.

Azure Storage Explorer Resource Selection

Select SAS

Azure Storage Explorer Connection Method

Give the connection a name and add in the SAS URL generated earlier.

Azure Storage Explorer Connection Info

The last screen is a summary of details once all are confirmed, click connect.

Azure Storage Explorer Summery

We have now connected to the Files container we created with the storage policy and SAS.

To test the policy is working we can try delete the a file as I didn’t apply that permission in the policy I get access denied.

File Explorer Activity Monitor

Now we can update the policy and add the delete permission. Click save the policy can take 30 seconds to update.

Access Policy

Now when delete the file it completes without issue.

File Explorer Activity Monitor

Using a stored access policy allow granular access control and also means if we need to change a permission or start / expiry time for an application or user that is using the SAS URL, we no longer have to re-issue each time we can just update the storage policy used for the SAS.

How to check VM SKU and VM Series Sizes Different Methods

When deploying VMs in Azure using template we need to be able to check the VM SKU and sizes to be able to update templates to deploy different OS version and VMs sizes.

There are a few different methods that can be used.

There is the Microsoft document, below is the link to the virtual machine size docs.

https://docs.microsoft.com/en-us/azure/virtual-machines/sizes-general

We can select the type in this case we will use general purpose.

Select the size, I selected ddv5-ddsv5-series. There will be table listing the VM sizes.

We also check the the VM size from the Azure portal by creating a new VM and changing the VM sizes.

Last method is to use either PowerShell or Azure CLI to query the require details on Windows Image SKU and VM sizes.

First we need to install the Azure AZ PowerShell module.

Run the below command to install the AZ module

Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force

Once the module is installed run

Connect-AzAccount

We can use the Get-AzVMImagePulisher to get the publisher name in this case I was looking for Microsoft Windows.

Get-AzVMImagePublisher -Location northeurope | Where-Object {$_.PublisherName -like 'MicrosofWindows*'}

To check all available Windows Server images we can run.

Get-AzVMImageSku -Location northeurope -PublisherName MicrosoftWindowsServer -Offer Windowsserver

We can use where-object filter to by server OS version.

Get-AzVMImageSku -Location northeurope -PublisherName MicrosoftWindowsServer -Offer Windowsserver | Where-Object {$_.Skus -like '2022*'}

To get the VM series size use the below command to check size in the specific region.

Get-AzVMSize -Location northeurope

To filter by a specific cores or name we will use where-object again.

Get-AzVMSize -Location northeurope | Where-Object {$_.Numberofcores -eq '4' -and $_.Name -like 'Standard_D*'}

Now once we have the SKU and Image size we can update our template file with the required VM size and image references.

Using Parameter File With Bicep Templates

In the previous post we went through the process of deploying an Bicep template using parameter that where called directly from PowerShell.

This is ok when deploying resources that require only a few values to be set, but this can become difficult to manage when there are a lot of parameter like when deploying virtual machines or web apps.

A parameter file for Bicep is a json file that has the specific parameter names and values set.

I used this Microsoft document as a reference to create the parameter file.

https://docs.microsoft.com/en-us/azure/azure-resource-manager/bicep/parameter-files

Below is the Bicep file we created in the last post.

A parameter file for the storage Bicep template would look like the below.

Once we have the parameter file, we are ready to test the deployment. To test without actually deploying the resource add the whatif parameter.

New-AzResourceGroupDeployment -ResourceGroupName ResourceGroupName -TemplateFile .\BicepTemplate.bicep -TemplateParameterFile .\BicepParamter.json -WhatIf

Next we will create a template to deploy a virtual machine and it network interface. To create base template in visual studio code type

res-nic to populate the network interface:

Use res-vm-windows to populate the virtual machine.

I will be creating parameters for each part that requires customization and anything that doesn’t I will leave with the hardcode values like. The @descirpiton is a Parameter decorators that allow use to add a description of what the parameter is used for.

I create two variables for the vnetId and subnetref that are used for the network interface

Below is what the updated virtual machine resource template looks like.

Once we have the Bicep template file ready the next step is to configure the parameter file. I copied the default template file code from the above Microsoft document and added in each of the required parameters.

To get the virtual network ID that will be used in the parameters file go to the virtual network and click on properties > Resource ID.

Once we have that we can fill out the reset of the parameter values.

After the template file has been configured, we can test the deployment same way as the storage account and use the whatif to confirm there are no errors.

As I have not set the admin password in the template or parameter file the deployment will prompt for the admin password to be set on the VM.

If the test deployment comes back without any issues we can check the results from the whaif deployment to confirm all the are correct.

Since the template and parameter files have returned no error we are ready to run and deploy the new VM resource.

If we check the resource group the new VM, OSDisk and network interface should be created.

Now that we have all the template and parameter file working we can just create a new parameter file for each VM resource. We can now create fully customized VM’s pretty quickly instead of having to deploy using the Azure market place and manually select the options we want to set.