Enable CORS Support in Cosmos DB using PowerShell

Support for Cross-Origin Resource Sharing (CORS) was recently added to Cosmos DB. If you want to enable CORS on an existing Cosmos DB account or create a new Cosmos DB account with CORS enabled it is very easy to do with Azure Resource Manager (ARM) templates or the Azure Portal.

But what if you’re wanting to find out the state of the CORS setting on an account or set it using PowerShell? Well, look no further.

The Cosmos DB PowerShell module (version 3.0.0 and above) supports creating Cosmos DB accounts with CORS enabled as well as updating and removing the CORS headers setting on an existing account. You can also retrieve the CORS setting for an existing Cosmos DB account.

Installing the CosmosDB Module

The first thing you need to do is install the CosmosDB PowerShell module from the PowerShell Gallery by running this in a PowerShell console:

ss_cosmosdbcors_installmodule

This will also install the Az PowerShell modules Az.Accounts and Az.Resources modules if they are not installed on your machine. The *-CosmosDbAccount functions in the CosmosDB module are dependent on these modules.

Note: The CosmosDB PowerShell module and the Az PowerShell modules are completely cross-platform and support Linux, MacOS and Windows. Running in either Windows PowerShell (Windows) or PowerShell Core (cross-platform) is supported.

Versions of the CosmosDB PowerShell module earlier than 3.0.0.0 use the older AzureRm/AzureRm.NetCore modules and do not support the CORS setting.

Authenticating to Azure with ‘Az’

Before using the CosmosDB PowerShell module accounts functions to work with CORS settings you’ll first need to authenticate to Azure using the Az PowerShell Modules. If you’re planning on automating this process you’ll want to authenticate to Azure using a Service Principal identity.

Side note: if you’re using this module in an Azure DevOps build/release pipeline the Azure PowerShell task will take care of the Service Principal authentication process for you:

ss_cosmosdbcors_azuredevopspowershelltask

But if you’re just doing a little bit of experimentation then you can just use an interactive authentication process.

To use the interactive authentication process just enter into your PowerShell console:

then follow the instructions.

ss_cosmosdbcors_authenticateaz.png

Create a Cosmos DB Account with CORS enabled

Once you have authenticated to Azure, you can use the New-CosmosDbAccount function to create a new account:

ss_cosmosdbcors_newcosmosdbaccountThis will create a new Cosmos DB account with the name dsrcosmosdbtest in the resource group dsrcosmosdbtest-rgp in the West US location and with CORS allowed origins of https://www.fabrikam.com and https://www.contoso.com.

Important: the New-CosmosDbAccount command assumes the resource group that is specified in the ResourceGroup parameter already exists and you have contributor access to it. If the resource group doesn’t exist then you can create it using the New-AzResourceGroup function or some other method.

It will take Azure a few minutes to create the new Cosmos DB account for you.

Side note: But if you want your PowerShell automation or script to be able to get on and do other tasks in the meantime, then add the -AsJob parameter to the New-CosmosDbAccountcall. This will cause the function to immediately return and provide you a Job object that you can use to periodically query the state of the Job. More information on using PowerShell Jobs can be found here.

Be aware, you won’t be able to use the Cosmos DB account until the Job is completed.

If you look in the Azure Portal, you will find the new Cosmos DB account with the CORS allowed origin values set as per your command:

ss_cosmosdbcors_cosmosdbinportalwithcors

Get the CORS Allowed Origins on a Cosmos DB Account

Getting the current CORS Allowed Origins value on an account is easy too. Just run the following PowerShell command:

ss_cosmosdbcors_getcosmosdbcors

This will return a string containing all the CORS Allowed Origins for the Cosmos DB account dsrcosmosdbtest.

You could easily split this string into an array variable by using:

ss_cosmosdbcors_getcosmosdbcorssplit

Update the CORS Allowed Origins on an existing Cosmos DB Account

To set the CORS Allowed Origins on an existing account use the Set-CosmosDbAccount function:

ss_cosmosdbcors_setcosmosdbcors

This will take a few minutes to update. So you can use the -AsJob parameter to run this as a Job.

Remove the CORS Allowed Origins from an existing Cosmos DB Account

You can remove the CORS Allowed Origins setting by setting using the Set-CosmosDbAccount function but passing in an empty string to the AllowedOrigin parameter:

ss_cosmosdbcors_removecosmosdbcors

This will take a few minutes to update as well. As always, you can use the -AsJob parameter to run this as a Job.

 

Final Words

Hopefully, you can see it is fairly simple to automate and work with the Cosmos DB CORS Allowed Origins setting using the PowerShell Cosmos DB module.

If you have any issues or queries or would like to contribute to the PowerShell Cosmos DB module, please head over to the GitHub repository.

 

Advertisements

Use Pester to Test Azure Resource Manager Templates for Best Practices

Recently I came across the amazing Secure DevOps Kit for Azure (AzSK). This contains a really useful AzSK PowerShell Module that contains cmdlets for performing different types of security scanning on Azure Resources, Subscriptions and Resource Manager Templates.

The feature of this module that I was most interested in for my current project was being able to scan ARM templates for best practice violations. The module contains several

To install the module, open a PowerShell Window and run:

Important: At the time of writing this post, the AzSK module has dependencies on the AzureRM.Profile and other AzureRM.* PowerShell modules. As of December 2018, the AzureRM.* PowerShell Modules are going to be renamed to Az.* (see this post). The AzureRM and Az modules can not be installed side-by-side, so if you’ve installed the Az PowerShell modules on your system then the installation of AzSK will fail because the AzureRM modules will also be installed and a conflict will occur.

The cmdlet we’re most interested in is the Get-AzSKARMTemplateSecurityStatus. It can be used to scan one or more ARM templates or entire folders of ARM templates for best practice violations:

ss_azsk_scanning

This will scan the ARM templates and produce a CSV report in a folder Microsoft\AzSKLogs\ARMChecker within your $ENV:LOCALAPPDATA folder and open the folder in Explorer. This isn’t ideal for automation scenarios or using during Continuous Integration or Continuous Delivery pipelines. I’ve raised an issue with the AzSK team on GitHub to see if this can be improved.

In my case, I wanted to be able to use the PowerShell Pester Module, a PowerShell testing framework, to execute tests on the output and then use the nUnit output Pester generates to publish into a Continuous Integration pipeline. To do that I needed to create a custom test script that would take the CSV report, count the failures of each level (High, Medium or Low) and fail if any are counted in the specific level.

This is what the script looks like:

You can download the script from GitHub Gist directly or get it from the PowerShell Gallery by running:

Install-Script -Name AzSKARMTemplateSecurityStatus.Test

To use it you will need to install Pester 4.3.0 and AzSK 3.6.1 modules:

Once that is done, you can use Invoke-Pester and pass in the TemplatePath and Severity parameters to the test script:

This will execute the Pester tests in the file above on the specified ARM template. The tests will fail when there are any best practice violations with the specified Severity or above. If you didn’t pass in a Severity then it will default to failing on Medium and High.

ss_azsk_invokepester

If you use the OutputFile and OutputFormat parameters to cause Pester to output an NUnit format file that most Continuous Integration tools will happily accept and use to display the output of the tests.

If you installed the script from the PowerShell Gallery, you can also run the tests like this:

AzSKARMTemplateSecurityStatus.Test -TemplatePath D:\101-webapp-basic-windows\azuredeploy.json

Finally, if you’re using Azure DevOps, you can also get this function as part Secure DevOps Kit (AzSK) CICD Extensions for Azure in the Azure DevOps Marketplace.

Which ever way you choose to consume AzSK, it is a great module and well worth including in your CI/CD pipelines to ensure your ARM templates meet best practices.

 

 

List Global Assembly Cache using PowerShell

The list of assemblies stored in the Global Assembly Cache (GAC) can be found in the registry under the HKEY_CLASSES_ROOT\Installer\Assemblies\Global key.

If you want to get a list of the assemblies registered in the GAC using PowerShell you can use this snippet:

ss_gac_getcontent

The first line registers a new drive called HKCR in PowerShell that maps to the HKEY_CLASSES_ROOT in the registry. This is required because, by default only the HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE registry hives are registered as drives in PowerShell.

The second line just gets the list of registry properties in the HKEY_CLASSES_ROOT\Installer\Assemblies\Global key and displays them.

 

 

Install Windows Admin Center (WAC) using DSC

Windows Admin Center (WAC) is a locally deployed, browser-based app for managing servers, clusters, hyper-converged infrastructure, and Windows 10 PCs. It was previously known as Project Honolulu.

ss_wacdsc_overview

WAC really shines when being used to manage headless Windows Servers (e.g. Windows Server Core). The benefits of deploying Windows Server Core are huge, but it can be a bit daunting to system administrators that have only used the Windows GUI experience to manage servers.

It is pretty easy to install WAC, but if you want to install it with PowerShell DSC, then here is a config for you to use:

The config is parameterized and supports specifying the port for the WAC to listen on  and using either a self-signed certificate or a local machine certificate in the by specifying a thumbprint.

To apply the DSC using a self-signed certificate and on the default port of 6516, run the following in an Administrator PowerShell console:

ss_wacdsc_defaultport

You can run this on a Windows Server Core machine by logging in and typing powershell to start a PowerShell console, then entering the commands above.

To apply the DSC configuration specifying a certificate with a thumbprint from the local machine store and on Port 4000, run these commands instead:

ss_wacdsc_installwiththumbprint

This DSC configuration can also be used on Virtual Machines deployed to Azure, using either the Azure DSC Extension Handler or a Azure Automation DSC Pull Server.

Easy as all that. Now you can use the awesome WAC GUI and still run headless while also taking advantage of the benefits that DSC brings.

Get the ForceChangePassword Office 365 User Setting with PowerShell

Recently I was asked by a friend if I knew of a way to get the value of the setting that forces a user to change their password when the next log in to Office 365. The friend wanted to get this value for all users using PowerShell.

Changing this setting is fairly straight forward either in the Office 365 portal or using the Set-MsolUserPassword cmdlet in the MSOnline PowerShell module:

ss_o365_setmsoluserpassword

However retrieving the current value of the setting isn’t possible using Get-MoslUser cmdlet – the attribute does not appear in the returned object:

ss_o365_getmsoluser

Instead, we need to use the Get-AzureADUser cmdlet in the AzureAD PowerShell Module to query the Azure Active Directory for the Office 365 tenant.

If you don’t have the AzureAD module installed, use Install-Module cmdlet to install it from the PowerShell Gallery:

Then connect to the AzureAD using the Connect-AzureAD cmdlet. Once connected you can run the following command to get the user object and show only the appropriate property (ForceChangePasswordNextLogin of the PasswordProfile object):

ss_o365_getazureadallforcechangepasswordnextlogin

This is all fairly straight forward once you figure out which object in Azure AD contains the information required.

Disable TLS 1.0, TLS 1.1 and 3DES in Azure API Management using an ARM Template

Recently, I’ve been putting together a continuous delivery pipeline (using VSTS) for our Azure API Management service using Azure Resource Manager (ARM) templates. One of the things I needed to be able to do to secure this service properly is to disable TLS 1.0, TLS 1.1 and 3DES. This is pretty easy to do in the portal:

ss_apim_disabletls3des

However, we only allow changes to be made via our continuous delivery pipeline (a good thing by the way) then I had to change the ARM template.

Side note: Disabling TLS 1.0, TLS 1.1 and 3DES is pretty important for keeping your system secure. But if you have an Azure Application Gateway in front of your API Management service, then you’ll also need to configure the Azure Application Gateway to disable TLS 1.0 and TLS 1.1. This is done in a slightly different way, but can also be done in an ARM Template (post a comment if you’re not sure how to do this and I’ll write another post).

I found the documentation for the API Management service resource here. This shows it can be done by setting the customProperties object in the ARM Template. But the documentation isn’t completely clear.

But after a little bit of trial and error I managed to figure it out and get it working. What you need to do is add the following customProperties to the properties of the API Management service resource:

This is what the complete ARM template looks like:

Side note: the template above is based off the Azure Quickstart Template for API Management.

Hopefully you find this if you’re looking for an example of how to do this and it saves you some time.