Azure Snippets

11 minute read

Collection of information and tools for Azure configuration reviews and security testing.

Common Terminology

Geo - A defined boundary for data residency that typically contains two or more regions. The boundaries may be within or beyond national borders and are influenced by tax regulation. Every geo has at least one region.

Portal - The secure web portal used to deploy and manage Azure services.

Region - An area within a geo that does not cross national borders and contains one or more datacentres.

Resource - An item that is part of your Azure solution. Each Azure service enables you to deploy different types of resources, such as databases or virtual machines.

Service Level Agreement - The agreement that describes Microsoft’s commitments for uptime and connectivity. Each Azure service has a specific SLA.

Shared Access Signatures (SAS) - A signature that enables you to grant limited access to a resource, without exposing your account key.

Subscription - A customer’s agreement with Microsoft that enables them to obtain Azure services. The subscription pricing and related terms are governed by the offer chosen for the subscription. (The subscription name and/or ID are often parsed to PowerShell cmdlets and security-related tools)


Domains / Associated Services

Domain Associated Service
azurewebsites.net App Services
scm.azurewebsites.net App Services - Management
p.azurewebsites.net App Services
cloudapp.net App Services
file.core.windows.net Storage Accounts-Files
blob.core.windows.net Storage Accounts-Blobs
queue.core.windows.net Storage Accounts-Queues
table.core.windows.net Storage Accounts-Tables
redis.cache.windows.net Databases-Redis
documents.azure.com Databases-Cosmos DB
database.windows.net Databases-MSSQL
vault.azure.net Key Vaults
onmicrosoft.com Microsoft Hosted Domain
mail.protection.outlook.com Email
sharepoint.com SharePoint
azureedge.net CDN
search.windows.net Search Appliance
azure-api.net API Services


Deployment Models

Azure Service Management (ASM) The original website, set of APIs, and tools used to manage Azure resources. It has been superseded by Azure Resource Manager (ARM). https://manage.windowsazure.com/

Azure Resource Manager (ARM) The newer management model used to configure and deploy resources in Azure. ARM is a replacement for Azure Service Management (ASM). https://portal.azure.com/

PowerShell cmdlets vary for each deployment mode. ARM cmdlets will usually contain the string Rm :

Get-AzureVm         // ASM 
Get-AzureWebsite 

Get-AzureRmVM       // ARM 
Get-AzureRmWebApp 


Defensive Services

Azure Defender

Azure Defender provides security alerts and advanced threat protection for virtual machines, SQL databases, containers, web applications, your network, and more.

Azure Antimalware

Microsoft Antimalware for Azure is a free real-time protection that helps identify and remove viruses, spyware, and other malicious software. It generates alerts when known malicious or unwanted software tries to install itself or run on your Azure systems.

Azure WAF

Web Application Firewall (WAF) provides centralized protection of your web applications from common exploits and vulnerabilities. You can deploy WAF on Azure Application Gateway or WAF on Azure Front Door Service.

Azure DDoS Protection

Azure DDoS Protection Standard, combined with application design best practices, provides enhanced DDoS mitigation features to defend against DDoS attacks. It is automatically tuned to help protect your specific Azure resources in a virtual network.

Azure Sentinel

Microsoft Azure Sentinel is a scalable, cloud-native, security information event management (SIEM) and security orchestration automated response (SOAR) solution. Azure Sentinel delivers intelligent security analytics and threat intelligence across the enterprise, providing a single solution for alert detection, threat visibility, proactive hunting, and threat response.


Azure CLI

Linux (Debian) Install

NOTE If installing on Kali, the lsb_release -cs command won’t be recognised when querying the Microsoft package repos. You’ll have to parse buster to the AZ_REPO= command instead:

AZ_REPO="buster"
sudo apt-get update
sudo apt-get install ca-certificates curl apt-transport-https lsb-release gnupg

curl -sL https://packages.microsoft.com/keys/microsoft.asc |
    gpg --dearmor |
    sudo tee /etc/apt/trusted.gpg.d/microsoft.gpg > /dev/null

AZ_REPO=$(lsb_release -cs)

echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" |
    sudo tee /etc/apt/sources.list.d/azure-cli.list

sudo apt-get update
sudo apt-get install azure-cli

Authentication

The article above lists various ways in which you’re able to authenticate with Azure, the simplest method is to run az login.

Available Commands

Refer to the documentation linked above for a detailed overview of all commands, some examples are provided below:

az help
az account list
az resource list
az vm list
az security alert list

Azure PowerShell on Windows

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

Select [A] Yes to All when prompted and wait for the install to finish.

Az Module

Start an admin PowerShell terminal and run the following:


PS C:\> Set-ExecutionPolicy Bypass -Force
PS C:\> Import-Module Az

Connect the Azure account by running the following command and entering your credentials on the browser login portal:

PS C:\> Connect-AzAccount

Account                        SubscriptionName TenantId            Environment
-------                        ---------------- --------            -----------
Matthew.Coady@fidusinfosec.com Free Trial       3310d048-...        AzureCloud
Once successfully logged in you'll see output within the PowerShell window verifying the Account, SubscriptionName, TennantId, and Environment.

A specific SubscriptionName and TenantId can also be parsed to Connect-AzAccount:


PS C:\test\> Connect-AzAccount -SubscriptionId "df859bf7-..." -TenantId "9c7d9dd3-..."
Account                   SubscriptionName TenantId     Environment
-------                   ---------------- --------     -----------
account@fidusinfosec.com  s102-...          9c7d9dd3-... AzureCloud



AzureRM PowerShell

In order to use AzureRM PowerShell commands you’ll have to install the the AzureRM module as shown below:

Install-Module -Name AzureRM -AllowClobber  // select A (yes to all)

Once installation is complete you can connect the relevant account:

Connect-AzureRmAccount

Upon logging in you are then able to use AzureRM cmdlets.



Azure Security Module

Azure Security Centre gives you control over the security of your Azure subscriptions and other machines that you connected to it outside of Azure.

Installing and importing the Az.Security module:

PS C:\WINDOWS\system32> Install-Module Az.Security

Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from
'PSGallery'?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A

PS C:\WINDOWS\system32> ipmo Az.Security



ScoutSuite

Follow the setup wiki page linked above to install ScoutSuite in your preferred method.

ScoutSuite Usage

In order to run scoutsuite we need to authenticate to Azure, information on the different ways in which to authenticate can be found in the link above.

The easiest method is to authenticate via the azure-cli tool and then parse the –cli option when running scoutsuite:

pip install azure-cli
az login  // login with account credentials when prompted
scoute azure --cli  // runs scoute against clients azure environment

You can specify specific subscriptions within the target environment with the –subscriptions flag which take the subscription ID as parameters:

scoute azure --cli --subscriptions a8736e42-...-54b2137562ba 7226bf32-...-e5f6a3546d14 

This is useful if the client has multiple subscriptions and only wants one or two tested.

ScoutSuite Services

Scoutsuite allows you to list and specify specific services within the client’s Azure environment:

scout azure --cli --list-services

The available services are then returned:

"aad", "appservice", "keyvault", "network", "rbac", "securitycenter", "sqldatabase", "storageaccounts", "virtualmachines"

The –services parameter can then be used to name in-scope services for scoutsuite to test, this is useful if you have access to the client’s entire environment but they only want their storage accounts tested:

scout azure --cli --services storageaccounts



PowerZure

PowerZure is a PowerShell project created to assess and exploit resources within Microsoft’s cloud platform, Azure. PowerZure was created out of the need for a framework that can both perform reconnaissance and exploitation of Azure.

Connect to the target Azure account using the steps in the previous sections (Windows or Linux), once connected you can import the PowerZure module:

PS C:\> Import-Module .\PowerZure.ps1
Install AzureAD PowerShell Module?
 ( y / n ) : y                               

You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy value by running the Set-PSRepository cmdlet. 
Are you sure you want to install the modules from 'PSGallery'?

[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A
Successfully installed AzureAD module. Please open a new PowerShell window and re-import PowerZure to continue

Be sure that you Set-AzureSubscription -Id {id} if there are multiple subscriptions within the account you’re testing.

The PowerZure help provides a brief description of the functions available:

PS C:\> PowerZure -h

                          PowerZure Version 2.0

                                List of Functions

------------------Info Gathering -------------

Get-AzureADRole -------------------- Gets the members of one or all Azure AD role. Roles does not mean groups.
Get-AzureAppOwner -----------------  Returns all owners of all Applications in AAD
Get-AzureDeviceOwner --------------  Lists the owners of devices in AAD. This will only show devices that have an owner.
Get-AzureGroup --------------------- Gathers a specific group or all groups in AzureAD and lists their members.
Get-AzureIntuneScript -------------- Lists available Intune scripts in Azure Intune
Get-AzureLogicAppConnector --------- Lists the connector APIs in Azure
Get-AzureRole ---------------------- Gets the members of an Azure RBAC role.
Get-AzureRunAsAccounts ------------- Finds any RunAs accounts being used by an Automation Account
Get-AzureRolePermission ------------ Finds all roles with a certain permission
Get-AzureSQLDB --------------------- Lists the available SQL Databases on a server
Get-AzureTargets ------------------- Compares your role to your scope to determine what you have access to
Get-AzureUser ---------------------- Gathers info on a specific user or all users including their groups and roles in Azure & AzureAD
Show-AzureCurrentUser -------------- Returns the current logged in user name and any owned objects
Show-AzureKeyVaultContent ---------- Lists all available content in a key vault
Show-AzureStorageContent ----------- Lists all available storage containers, shares, and tables

------------------Operational --------------

Add-AzureADGroup ---------------- Adds a user to an Azure AD Group
Add-AzureADRole ----------------- Assigns a specific Azure AD role to a User
Add-AzureSPSecret --------------- Adds a secret to a service principal
Add-AzureRole ------------------- Adds a role to a user in Azure
Create-AzureBackdoor ------------ Creates a backdoor in Azure via Service Principal
Export-AzureKeyVaultContent ----- Exports a Key as PEM or Certificate as PFX from the Key Vault
Get-AzureKeyVaultContent -------- Get the secrets and certificates from a specific Key Vault or all of them
Get-AzureRunAsCertificate ------- Will gather a RunAs accounts certificate if one is being used by an automation account, which can then be used to login as that account.
Get-AzureRunbookContent --------- Gets a specific Runbook and displays its contents or all runbook contents
Get-AzureStorageContent --------- Gathers a file from a specific blob or File Share
Get-AzureVMDisk ----------------- Generates a link to download a Virtual Machiche’s disk. The link is only available for 24 hours.
Invoke-AzureCommandRunbook ------ Will execute a supplied command or script from a Runbook if the Runbook is configured with a “RunAs” account
Invoke-AzureRunCommand ---------- Will run a command or script on a specified VM
Invoke-AzureRunMSBuild ---------- Will run a supplied MSBuild payload on a specified VM.
Invoke-AzureRunProgram ---------- Will run a given binary on a specified VM
New-AzureUser ------------------- Creates a user in Azure Active Directory
New-AzureIntuneScript ----------- Uploads a PS script to Intune
Set-AzureElevatedPrivileges ----- Elevates the user’s privileges from Global Administrator in AzureAD to include User Access Administrator in Azure RBAC.
Set-AzureSubscription ----------- Sets default subscription. Necessary if in a tenant with multiple subscriptions.
Set-AzureUserPassword ----------- Sets a user’s password
Start-AzureRunbook -------------- Starts a Runbook

PowerZure operates in a similar fashion to PowerView with cmdlets offering specific functionality, the documentation provides greater detail on the commands available.



MicroBurst

MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping. It is intended to be used during penetration tests where Azure is in use.

Ensure you’re connected to the Azure account you’re testing from beforehand.

PS C:\> Import-Module .\MicroBurst.psm1
Function Description
Get-AzPasswords Dumps all available credentials from an Azure subscription
Invoke-EnumerateAzureBlobs Enumarate public Azure Blobs and Containers
Invoke-EnumerateAzureSubDomains Enumerate public Azure services via DNS
Get-AzDomainInfo Dump information from Azure subscriptions via authenticated ASM and ARM connections
Invoke-AzRmVMBulkCMD Runs PowerShell scripts against all (or select) VMs in a subscription/resource group
Get-AzKeyVaults-Automation Dump all available Key Vault Keys/Secrets from an Azure subscription via Automation Accounts
Get-AzVMExtensionSettings Dump information from Azure VM Extension Settings

The MicroBurst github page provides greater detail on the available functions. Including syntax, example usage, and related articles by NetSPI.



Azure User Artefacts/Credentials

The following sections refer to artefacts/credentials that can be commonly found on domain joined machines.

TokenCache.dat

The TokenCache.dat file is stored as plaintext JSON after any sign in, which exposes token credentials for all available subscriptions of a signed in user.

C:\Users\<username>\.Azure\TokenCache.dat

Save-AzContext

Saves the current authentication information for use in other PowerShell sessions.

Can search for Save-AzContext usage and file location:

PS C:\> Get-PSReadLineOption

EditMode                               : Windows
AddToHistoryHandler                    : System.Func`2[System.String,System.Object]
HistoryNoDuplicates                    : True
HistorySavePath                        : C:\Users\username\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
HistorySaveStyle                       : SaveIncrementally
HistorySearchCaseSensitive             : False
HistorySearchCursorMovesToEnd          : False

PS C:\> Select-String -Path <path/to/consolehost_history.txt> -Pattern 'Save-AzContext'

ARM Profile Tokens

Files may contain tokens which are a stored representation of saved Azure credentials (Save-AzureRmProfile).

Tend to have .json extension but not always the case. Search for the following keywords:

  • TokenCache
  • Tenant
  • PublishSettingsFileUrl
  • ManagementPortalUrl

Management Certificates

Intended to manage classic ASM-based resources (ARM uses services principles).

Azure uses asymmetric X.509 certifcates - each certifacte has a public and private key. Private key is required for authentication.

.pfx files will usually contain the private key and .cer the public key.

Publish Settings Files

XML documents that contain details about an Azure subscription (subscription name, ID, and Base64 encoded management certicate).

.publishsettings file extension.

Configuration Files

Commonly have .config or .xml extension e.g. web.config, app.config, azure.xml.

Cloud Service Packages

When a developer creates app to deploy to Azure, Visual Studio packages up the entire deployment into a Cloud Service Package .cspkg file.

ZIP file containing compiled code, configuration files, manifests, and dependencies.

May find embdedded certificates/credentials.

Mimikatz

Need admin privs:

mimikatz # privilege::debug
mimikatz # sekurlsa::logonpasswords

Reused Certificates - Mimikatz

Some admins may reuse the same certificate everywhere, need admin privs to extract the certs with mimikatz:

mimikatz # crypto::capi
mimikatz # privilege::debug
mimikatz # crypto::cng
mimikatz # crypto::certificates /systemstore:local_machine /store:my /export



Issue Verification

e.g. enumeration tools have highlighted that there is a storage container that can be accessed anonymously.

Searching the site referenced above you’ll find the following page which provides information on the finding, risk level, and step-by-step instructions on how to confirm the finding either via the azure-cli or azure console:


Recommended remediation/resolutiion is also provided.



References and Resources

Enumeration and Exploitation

  • https://github.com/rootsecdev/Azure-Red-Team
  • https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20Azure%20Pentest.md
  • https://github.com/hausec/PowerZure
  • https://github.com/NetSPI/MicroBurst
  • https://github.com/dirkjanm/ROADtools
  • https://github.com/cyberark/SkyArk
  • https://github.com/FSecureLABS/Azurite
  • https://github.com/nccgroup/azucar
  • https://github.com/nccgroup/ScoutSuite
  • https://github.com/fox-it/adconnectdump
  • https://github.com/dirkjanm/BloodHound-AzureAD
  • https://notsosecure.com/identifying-exploiting-leaked-azure-storage-keys/
  • https://blog.netspi.com/attacking-azure-with-custom-script-extensions/
  • https://blog.netspi.com/get-azurepasswords/
  • https://www.lares.com/blog/hunting-azure-admins-for-vertical-escalation/
  • https://labs.f-secure.com/assets/BlogFiles/mwri-a-penetration-testers-guide-to-the-azure-cloud-v1.2.pdf

Azure AD

  • https://www.synacktiv.com/en/publications/azure-ad-introduction-for-red-teamers.html
  • https://portswigger.net/daily-swig/cloud-security-attacking-azure-ad-to-expose-sensitive-accounts-and-assets
  • https://www.varonis.com/blog/azure-skeleton-key/
  • https://posts.specterops.io/attacking-azure-azure-ad-and-introducing-powerzure-ca70b330511a
  • https://blog.xpnsec.com/azuread-connect-for-redteam/
  • https://www.blackhillsinfosec.com/red-teaming-microsoft-part-1-active-directory-leaks-via-azure/
  • https://adsecurity.org/wp-content/uploads/2019/08/2019-BlackHat-US-Metcalf-Morowczynski-AttackingAndDefendingTheMicrosoftCloud.pdf
  • https://speakerdeck.com/tweekfawkes/blue-cloud-of-death-red-teaming-azure-1
  • https://www.slideshare.net/DirkjanMollema/im-in-your-cloud-reading-everyones-email-hacking-azure-ad-via-active-directory
  • https://dirkjanm.io/azure-ad-privilege-escalation-application-admin/

Cheatsheets and References

  • https://www.whizlabs.com/blog/microsoft-azure-cheat-sheet/
  • https://microsoft.github.io/AzureTipsAndTricks/
  • https://docs.microsoft.com/en-gb/azure/cloud-adoption-framework/

Defence and Hardening

  • https://logrhythm.com/blog/six-tips-for-securing-your-azure-cloud-environment/
  • https://posts.specterops.io/detecting-attacks-within-azure-bdc40f8c0766
  • https://github.com/Azure/Azure-Sentinel/tree/master/Hunting%20Queries
  • https://github.com/puresec/awesome-serverless-security/#azure-functionssecurity
  • https://www.cloudconformity.com/knowledge-base/azure/
  • https://www.blackhillsinfosec.com/azure-security-basics-log-analytics-security-center-and-sentinel/
  • https://www.infosecmatter.com/top-20-microsoft-azure-vulnerabilities-and-misconfigurations/