Skip to content

07 / 13Data

Azure Key Vault security hardening

Harden Azure Key Vault: RBAC permission model, purge protection, private endpoints and firewall, key rotation, secret expiry, Defender alerts and audit logs.

Service
Key Vault
Category
Data
Baseline
12 controls
Updated
Published on 10 min read
On this page

Azure Key Vault stores the secrets, keys and certificates that unlock everything else: database passwords, API keys, TLS certificates and the customer-managed keys protecting storage, disks and SQL databases. An attacker who can read a vault rarely needs another foothold, which is why MITRE ATT&CK lists cloud secrets stores as their own technique (T1555.006). Defaults leave two gaps. Vaults that still use the legacy access policy model let anyone with Contributor (or Key Vault Contributor) on the vault grant themselves data access, a path Datadog Security Labs documented in 2024 and Microsoft acknowledged in its documentation. And a vault deleted without purge protection can take the key behind your encrypted data with it, permanently. This page maps to the Key Vault section of the CIS Microsoft Azure Foundations Benchmark and to the Microsoft cloud security benchmark (MCSB) controls PA-7, NS-2 and DP-6 to DP-8.

Baseline controls

CIS numbers refer to the CIS Microsoft Azure Foundations Benchmark v7.0.0.

ControlWhyHow to checkID
Azure RBAC permission modelAccess policies let control plane contributors grant themselves data accessproperties.enableRbacAuthorization is trueMCSB PA-7 / CIS 8.3.9
Narrow data roles, one vault per appLimits the blast radius of one compromised identityaz role assignment list --scope <vault-id>MCSB PA-7
Soft delete with 90-day retentionRecovers deleted vaults and objectsproperties.softDeleteRetentionInDaysMCSB DP-8
Purge protectionNobody can permanently destroy a key before retention endsproperties.enablePurgeProtection is trueMCSB DP-8 / CIS 8.3.8
Delete lock on production vaultsStops accidental vault deletionaz lock list --resource <vault-id>CIS 6.2
Public network access disabledRemoves the internet as an attack pathproperties.publicNetworkAccess is DisabledMCSB NS-2 / CIS 8.3.11, 8.3.12
Firewall default deny when publicOnly named networks reach the data planeproperties.networkAcls.defaultAction is DenyMCSB NS-2 / CIS 8.3.10
Expiration dates on keys and secretsDrives rotation, alerts and reportingaz keyvault secret list --query "[].attributes.expires"MCSB DP-6 / CIS 8.3.2 to 8.3.5
Key rotation policyNew key versions without manual workaz keyvault key rotation-policy showMCSB DP-6 / CIS 8.3.7
Certificate lifetime and auto-renewalAvoids outages and long-lived private keysCertificate policy validityInMonths, lifetimeActionsMCSB DP-7 / CIS 8.3.6
Defender for Key VaultDetects anomalous secret accessDefender plan KeyVaults is StandardMCSB LT-1 / CIS 8.1.8.1
Audit logs to Log AnalyticsWho read which secret, from whereDiagnostic setting with audit category groupMCSB LT-3 / CIS 6.1.1.4

RBAC permission model

Key Vault has two authorization models for the data plane:

  • Vault access policies (legacy): a list of principals with key, secret and certificate permissions, stored as a property of the vault. Any principal allowed to write the vault (Microsoft.KeyVault/vaults/write, which Contributor and Key Vault Contributor include) can edit that list and grant itself every secret. It is a privilege escalation path built into the model, and access policies also cannot be scoped below the vault or made eligible through PIM.
  • Azure RBAC: data plane roles assigned like any other Azure role, at vault or individual object scope, with PIM, conditions and central reporting.

Use RBAC for every vault. Recent Azure CLI versions create vaults with RBAC by default, but older templates, Terraform modules and API versions still create access policy vaults, so set it explicitly:

bash
az keyvault create \
  --name kv-app1-prod-weu --resource-group rg-app1 --location westeurope \
  --enable-rbac-authorization true \
  --enable-purge-protection true \
  --retention-days 90 \
  --public-network-access Disabled \
  --sku standard

Migrate an existing vault

List the access policies, create matching role assignments, then switch the model. The switch takes effect immediately and access policies stop being evaluated, so create the role assignments first.

bash
az keyvault show -n kv-legacy \
  --query "properties.accessPolicies[].{oid:objectId, secrets:permissions.secrets, keys:permissions.keys}"

az keyvault update -n kv-legacy --enable-rbac-authorization true

Portal: Key vault > Settings > Access configuration > Permission model.

Find remaining access policy vaults across the tenant with Resource Graph:

KQL
resources
| where type =~ "microsoft.keyvault/vaults"
| project name, resourceGroup, subscriptionId,
          rbac = tobool(properties.enableRbacAuthorization),
          purgeProtection = tobool(properties.enablePurgeProtection),
          retention = toint(properties.softDeleteRetentionInDays),
          publicNetwork = tostring(properties.publicNetworkAccess),
          defaultAction = tostring(properties.networkAcls.defaultAction)
| where rbac != true or purgeProtection != true or publicNetwork != "Disabled"

Enforce: assign Azure Key Vault should use RBAC permission model with Deny at a management group, after the migration. The rollout pattern is on the Azure Policy page.

bash
az policy assignment create \
  --name deny-kv-access-policies \
  --display-name "Azure Key Vault should use RBAC permission model" \
  --policy 12d4fa5e-1f9f-4c21-97a9-b99b3c6611b5 \
  --scope /providers/Microsoft.Management/managementGroups/mg-landing-zones \
  --params '{"effect":{"value":"Deny"}}'

Data plane roles and vault scope

RoleCan doTypical holder
Key Vault Secrets UserRead secret valuesApplication managed identity
Key Vault Crypto Service Encryption UserWrap and unwrap with a key, read key metadataStorage, disk encryption set or SQL server identity using a CMK
Key Vault Crypto UserUse keys (encrypt, decrypt, sign, verify)Application performing its own cryptography
Key Vault Certificate UserRead certificates and their private keys as secretsApp Service, Application Gateway
Key Vault Secrets OfficerCreate, update, delete secretsDeployment pipeline
Key Vault ReaderRead metadata, not valuesAuditors, security team
Key Vault Data Access AdministratorAssign Key Vault data roles, with conditionsPlatform team instead of User Access Administrator
Key Vault AdministratorEverything on the data planePIM eligible only

Assign roles at the narrowest scope. A single secret can be a scope:

bash
az role assignment create \
  --assignee-object-id <app-identity-principal-id> \
  --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" \
  --scope "$(az keyvault show -n kv-app1-prod-weu --query id -o tsv)/secrets/db-password"

Use one vault per application per environment. Vaults cost nothing on their own, and sharing one between applications forces broad roles and widens the blast radius of any compromised identity.

Owner and User Access Administrator on the vault, resource group or subscription can grant themselves data roles. Keep those roles eligible through Privileged Identity Management, as covered on the Entra ID and Azure RBAC pages, and alert on role assignments at vault scope (query in Logging and detection).

Soft delete and purge protection

Soft delete is always on and cannot be disabled: deleted vaults, keys, secrets and certificates are kept for 7 to 90 days, set with --retention-days at creation. During that time, anyone with purge permission can destroy them permanently.

Purge protection removes that possibility: a soft-deleted vault or object cannot be purged until the retention period ends, by anyone. Azure services that use customer-managed keys (Storage, managed disks, SQL TDE and most others) require it on the vault that holds the key.

bash
az keyvault update -n kv-app1-prod-weu --enable-purge-protection true

Purge protection cannot be turned off once enabled, and the retention period cannot be changed after the vault is created. That is the point. Use 90 days for production vaults.

Soft delete does not stop someone from deleting the vault and breaking every dependent application for hours. Add a delete lock on production vaults:

bash
az lock create --name lock-kv-app1-prod --lock-type CanNotDelete \
  --resource-group rg-app1 --resource kv-app1-prod-weu \
  --resource-type Microsoft.KeyVault/vaults

Enforce: Key vaults should have deletion protection enabled (purge protection) with Deny, and Key vaults should have soft delete enabled.

Network access

By default a vault is reachable from any network, protected only by authentication. A leaked client secret or token is then usable from anywhere.

Private endpoint, no public access

For production vaults:

bash
KV_ID=$(az keyvault show -n kv-app1-prod-weu --query id -o tsv)

az network private-endpoint create \
  --name pe-kv-app1-prod --resource-group rg-app1 \
  --vnet-name vnet-app1 --subnet snet-private-endpoints \
  --private-connection-resource-id "$KV_ID" \
  --group-id vault --connection-name kv-app1-prod

az keyvault update -n kv-app1-prod-weu --public-network-access Disabled

Link the privatelink.vaultcore.azure.net private DNS zone to the VNets that resolve it; the hub-and-spoke DNS pattern is on the Virtual Network page.

Firewall with selected networks

When a private endpoint is not possible:

bash
az keyvault update -n kv-app1-prod-weu \
  --public-network-access Enabled \
  --default-action Deny \
  --bypass None

az keyvault network-rule add -n kv-app1-prod-weu --ip-address 203.0.113.10/32
az keyvault network-rule add -n kv-app1-prod-weu \
  --vnet-name vnet-app1 --subnet snet-app --resource-group rg-app1

Set --bypass AzureServices only if a trusted Microsoft service needs the vault (Azure Disk Encryption, App Service certificate import, Azure Resource Manager template deployment). Deployment pipelines on Microsoft-hosted agents have changing IP addresses; use self-hosted agents inside your VNet instead of opening the firewall.

Portal: Key vault > Settings > Networking.

Enforce: Azure Key Vault should disable public network access (Deny) for private-only landing zones, or Azure Key Vault should have firewall enabled or public network access disabled where selected networks are allowed. Azure Key Vaults should use private link audits the endpoint side.

Expiration and rotation

CIS asks for expiration dates on all keys and secrets, in both RBAC and access policy vaults. An expiry date does not stop a secret from working for reads (Key Vault still returns it), but it drives Event Grid notifications, Defender for Cloud recommendations and your own reporting.

bash
az keyvault secret set --vault-name kv-app1-prod-weu \
  --name db-password --file ./db-password.txt \
  --expires 2027-05-01T00:00:00Z \
  --content-type "text/plain"

Read values from a file or a pipe, not from --value on the command line, which ends up in shell history and process listings.

Key rotation policy

Define a rotation policy so Key Vault creates new key versions on schedule:

JSON
{
  "lifetimeActions": [
    { "trigger": { "timeAfterCreate": "P180D" }, "action": { "type": "Rotate" } },
    { "trigger": { "timeBeforeExpiry": "P30D" }, "action": { "type": "Notify" } }
  ],
  "attributes": { "expiryTime": "P1Y" }
}
bash
az keyvault key rotation-policy update --vault-name kv-app1-prod-weu \
  --name cmk-storage --value @rotation-policy.json

Services that reference the key without a version (Storage, disk encryption sets and SQL TDE with auto-rotation) pick up the new version automatically. For secrets, subscribe to the Microsoft.KeyVault.SecretNearExpiry Event Grid event and trigger a rotation function.

Better still, remove the secret. Most "database password in Key Vault" cases become a managed identity with Entra authentication to the database; see the SQL Database page.

Enforce: Key Vault secrets should have an expiration date, Key Vault keys should have an expiration date and Keys should have a rotation policy ensuring that their rotation is scheduled within the specified number of days after creation. Note that these data plane policies use the Microsoft.KeyVault.Data mode and only evaluate vaults that the policy engine can reach.

Certificates

Let Key Vault own the certificate lifecycle instead of uploading PFX files by hand:

  • Set validityInMonths in the certificate policy to what your CA allows. Public TLS certificate lifetimes are shrinking under CA/Browser Forum rules, so plan for automated renewal rather than yearly manual swaps.
  • Add a lifetime action AutoRenew (for integrated CAs such as DigiCert and GlobalSign) or EmailContacts (for others) a fixed number of days before expiry.
  • Set certificate contacts on the vault (az keyvault certificate contact add) so expiry warnings reach a team mailbox.
  • Mark the key as non-exportable ("exportable": false in keyProperties) when the consuming service does not need the private key outside the vault.

Enforce: Certificates should have the specified maximum validity period and Certificates should not expire within the specified number of days.

Microsoft Defender for Key Vault

Defender for Key Vault flags access from suspicious IPs and Tor exit nodes, unusual applications or users reading secrets, and high volumes of operations. Enable it at subscription level:

bash
az security pricing create -n KeyVaults --tier Standard

Alerts land with the rest of your Defender for Cloud alerts and can be streamed to Microsoft Sentinel.

Enforce: Configure Microsoft Defender for Key Vault plan (DeployIfNotExists) at the management group, and Azure Defender for Key Vault should be enabled to audit.

Logging and detection

Send the audit category group (which contains AuditEvent) to Log Analytics. Resource logs only exist from the moment you enable them, so do it at creation, at scale, with the built-in Enable logging by category group for Key vaults (microsoft.keyvault/vaults) to Log Analytics policy. The pattern is on the Azure Monitor page.

bash
az monitor diagnostic-settings create --name to-law \
  --resource "$KV_ID" --workspace "$LAW_ID" \
  --logs '[{"categoryGroup":"audit","enabled":true}]'

Hunt for an identity reading many different secrets in a short window, a common sign of credential harvesting:

KQL
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.KEYVAULT"
| where OperationName in ("SecretGet", "SecretList", "KeyDecrypt", "KeyUnwrap")
| summarize Calls = count(), Secrets = dcount(id_s)
    by identity_claim_oid_g, CallerIPAddress, Resource, bin(TimeGenerated, 1h)
| where Secrets > 20

Depending on the diagnostic setting's destination table, newer workspaces store Key Vault logs in the resource-specific AZKVAuditLogs table instead of AzureDiagnostics; adjust column names accordingly.

On the control plane, alert on changes that open access: model switches, access policy edits, network changes, role assignments at vault scope and vault deletion.

KQL
AzureActivity
| where ActivityStatusValue == "Success"
| where OperationNameValue in~ (
    "MICROSOFT.KEYVAULT/VAULTS/WRITE",
    "MICROSOFT.KEYVAULT/VAULTS/ACCESSPOLICIES/WRITE",
    "MICROSOFT.KEYVAULT/VAULTS/DELETE")
   or (OperationNameValue =~ "MICROSOFT.AUTHORIZATION/ROLEASSIGNMENTS/WRITE"
       and _ResourceId has "/providers/microsoft.keyvault/vaults/")
| project TimeGenerated, Caller, CallerIpAddress, OperationNameValue, _ResourceId

Common mistakes

  • Granting Contributor on a vault that still uses access policies, which silently gives that principal every secret.
  • Sharing one vault across applications and environments, so a dev pipeline identity can read production secrets.
  • Creating a vault for customer-managed keys without purge protection: one delete and purge, and the encrypted storage or database is unrecoverable.
  • Leaving publicNetworkAccess enabled with defaultAction=Allow after adding a private endpoint, so the public path still works.
  • Setting expiry dates but no rotation or notification, so expired secrets keep working and nobody notices until an audit.
  • Passing secret values with --value in pipeline scripts, which leaks them to logs and shell history.
  • Enabling diagnostic settings after an incident: there are no data plane logs for the period before.

References

Filed under key-vault, data-protection, identity, cis-benchmark

Written by

, Cloud Security Engineer & Editor

Security engineer writing practical hardening pages for Microsoft Azure tenants and subscriptions, aligned with the CIS Microsoft Azure Foundations Benchmark.

Related services

  1. SQL DatabaseHarden Azure SQL Database: Entra-only authentication, firewall without Azure-wide rules, private endpoints, TLS, TDE with customer-managed keys, auditing and Defender.
  2. Storage accountsHarden Azure Storage accounts: no anonymous blob access, no shared keys, short SAS, private endpoints, TLS 1.2, customer-managed keys, soft delete and logging.
  3. Entra IDHarden a Microsoft Entra ID tenant: Conditional Access, consent and guest settings, PIM, emergency access accounts and secretless workload identities.