自动轮换使用两组身份验证凭据的资源的机密Automate the rotation of a secret for resources with two sets of authentication credentials

向 Azure 服务进行身份验证的最佳方法是使用托管标识,但某些情况下无法做到这一点。The best way to authenticate to Azure services is by using a managed identity, but there are some scenarios where that isn't an option. 在此类情况下,将使用访问密钥或密码。In those cases, access keys or passwords are used. 访问密钥和密码应经常轮换。Access keys and passwords should be rotated frequently.

本教程介绍如何定期自动轮换使用两组身份验证凭据的数据库和服务的机密。This tutorial shows how to automate the periodic rotation of secrets for databases and services that use two sets of authentication credentials. 具体而言,本教程将使用 Azure 事件网格通知触发的函数来将 Azure Key Vault 中存储的 Azure 存储帐户密钥作为机密轮换。Specifically, this tutorial rotates Azure Storage account keys stored in Azure Key Vault as secrets using a function triggered by Azure Event Grid notification. 解码的字符::

备注

通过为“针对存储帐户的委托访问”提供共享访问签名令牌,可以自动管理 Key Vault 中的存储帐户密钥。Storage Account Keys can be automatically managed in Key Vault by providing shared access signature tokens for delegated access to Storage Account. 有些服务需要带有访问密钥的存储帐户连接字符串,对于这种情况,建议使用此解决方案There are services which require storage account connection string with access key and for that scenario this solution is recommended

轮换解决方案示意图

在上面的解决方案中,Azure Key Vault 将存储帐户的单个访问密钥存储为同一机密的不同版本,在后续版本中作为主密钥和辅助密钥交替使用。In above solution, Azure Key Vault stores Storage Account individual access keys as versions of the same secret alternating between primary and secondary key in subsequent versions. 当一个访问密钥存储到最新版本的机密中时,将重新生成备用密钥并作为新的最新版本的机密添加到密钥库中。As one access key is stored in latest version of the secret, alternate key gets regenerated and added to Key Vault as new and latest version of the secret. 该解决方案为应用程序提供了完整的轮换周期,以便刷新到再生成的最新密钥。That solution provides applications entire rotation cycle to refresh to newest regenerated key.

  1. 在机密过期之前的 30 天,Key Vault 会向事件网格发布“即将过期”事件。30 days before the expiration date of a secret, Key Vault publishes the "near expiry" event to Event Grid.
  2. 事件网格会检查事件订阅,并使用 HTTP POST 调用已订阅该事件的函数应用终结点。Event Grid checks the event subscriptions and uses HTTP POST to call the function app endpoint subscribed to the event.
  3. 函数应用标识备用密钥(而不是最新密钥)并调用存储帐户以再生成该密钥The function app identifies alternate key (other than latest) and calls Storage Account to regenerate it
  4. 函数应用将新的再生成的密钥添加到 Azure Key Vault 中,作为密钥的新版本。The function app adds new regenerated key to Azure Key Vault as new version of the secret.

先决条件Prerequisites

如果没有现成的密钥保管库和存储帐户,可以使用下面的部署链接:Below deployment link can be used, if you don't have existing key vault and storage accounts:

图像显示标记为“部署到 Azure”的按钮。Image showing a button labeled "Deploy to Azure".

  1. 在“资源组”下,选择“新建”。Under Resource group, select Create new. 将组命名为“akvrotation”,然后单击“确定” 。Name the group akvrotation and click Ok.

  2. 选择“查看 + 创建”。Select Review+Create.

  3. 选择“创建”Select Create

    创建资源组

现在,你拥有一个密钥保管库和两个存储帐户。You'll now have a key vault, and two storage accounts. 可以在 Azure CLI 中运行以下命令来验证此设置:You can verify this setup in the Azure CLI by running the following command:

az resource list -o table -g akvrotation

结果类似于以下输出:The result will look something the following output:

Name                     ResourceGroup         Location    Type                               Status
-----------------------  --------------------  ----------  ---------------------------------  --------
akvrotation-kv         akvrotation      chinaeast      Microsoft.KeyVault/vaults
akvrotationstorage     akvrotation      chinaeast      Microsoft.Storage/storageAccounts
akvrotationstorage2    akvrotation      chinaeast      Microsoft.Storage/storageAccounts

创建和部署存储帐户密钥轮换函数Create and deploy storage account key rotation function

接下来,创建一个使用系统托管标识的函数应用以及其他所需组件,并部署存储帐户密钥轮换函数Next, create a function app with a system-managed identity, in addition to the other required components, and deploy storage account key rotation functions

函数应用轮换函数需要以下组件和配置:The function app rotation functions require these components and configuration:

  • 一个 Azure 应用服务计划An Azure App Service plan
  • 进行函数应用触发器管理时所需的存储帐户A storage account required for function app trigger management
  • 用于访问 Key Vault 中的机密的访问策略An access policy to access secrets in Key Vault
  • 将存储帐户密钥操作员服务角色分配给函数应用,用于访问存储帐户访问密钥Assign Storage Account Key Operator Service role to function app to access Storage Account access keys
  • 具有事件触发器和 http 触发器的存储帐户密钥轮换函数(按需轮换)Storage Account key rotation functions with event trigger and http trigger (on-demand rotation)
  • “SecretNearExpiry”事件的 EventGrid 事件订阅EventGrid event subscription for SecretNearExpiry event
  1. 选择 Azure 模板部署链接:Select the Azure template deployment link:

    图像显示标记为“部署到 Azure”的按钮。Image showing a button labeled "Deploy to Azure".

  2. 在“资源组”列表中选择“akvrotation” 。In the Resource group list, select akvrotation.

  3. 在“存储帐户名称”中,键入包含要轮换的访问密钥的存储帐户名称In the Storage Account Name, type the storage account name with access keys to rotate

  4. 在“密钥保管库名称”中,键入密钥保管库名称In the Key Vault Name, type the key vault name

  5. 在“函数应用名称”中,键入函数应用名称In the Function App Name, type the function app name

  6. 在“机密名称”中,键入存储了访问密钥的机密的名称In the Secret Name, type secret name where access keys would be stored

  7. 在“存储库 Url”中,键入函数代码 GitHub 位置 (https://github.com/jlichwa/KeyVault-Rotation-StorageAccountKey-PowerShell.git ) In the Repo Url, type function code GitHub location (https://github.com/jlichwa/KeyVault-Rotation-StorageAccountKey-PowerShell.git)

  8. 选择“查看 + 创建”。Select Review+Create.

  9. 选择“创建”Select Create

    查看并创建第一个存储帐户

完成上述步骤后,你将获得一个存储帐户、一个服务器场、一个函数应用、应用程序见解。After you complete the preceding steps, you'll have a storage account, a server farm, a function app, application insights. 部署完成后,应会看到以下屏幕:部署完成You should see below screen once deployment completed: Deployment complete

备注

如果出现任何故障,可以单击“重新部署”来完成其余组件的部署。In case of any failures you can click Redeploy to finish deployment of remaining components.

部署模板和轮换函数代码可以在 GitHub 上找到。Deployment templates and rotation functions code can be found on GitHub.

将存储帐户访问密钥添加到 Key VaultAdd Storage Account access key to Key Vault

首先,设置访问策略,以向用户授予“管理机密”权限:First, set your access policy to grant manage secrets permissions to users:

az keyvault set-policy --upn <email-address-of-user> --name akvrotation-kv --secret-permissions set delete get list

现在,可以使用存储帐户访问密钥作为值来创建新的机密。You can now create a new secret with a Storage Account access key as value. 还需要存储帐户资源 ID、机密有效期和要添加到机密的密钥 ID,以便轮换函数可以在存储帐户中再生成密钥。You will also need the Storage Account resource ID, secret validity period, and the key ID to add to secret, so rotation function can regenerate key in Storage Account.

检索存储帐户资源 ID。Retrieve Storage Account resource ID. 可在 id 属性下找到值Value can be found under id property

az storage account show -n akvrotationstorage

列出存储帐户访问密钥以检索密钥值List the Storage Account access keys to retrieve key values

az storage account keys list -n akvrotationstorage 

填充“key1Value”和“storageAccountResourceId”的检索值Populate retrieved values for key1Value and storageAccountResourceId

$tomorrowDate = (get-date).AddDays(+1).ToString("yyy-MM-ddThh:mm:ssZ")
az keyvault secret set --name storageKey --vault-name akvrotation-kv --value <key1Value> --tags "CredentialId=key1" "ProviderAddress=<storageAccountResourceId>" "ValidityPeriodDays=60" --expires $tomorrowDate

创建过期时间较短的机密会在几分钟内发布 SecretNearExpiry 事件,而该事件又会触发函数来轮换该机密。Creating a secret with a short expiration date will publish a SecretNearExpiry event within several minutes, which will in turn trigger the function to rotate the secret.

可以通过检索和比较存储帐户密钥和保管库机密来验证是否再生成了访问密钥。You can verify that access keys are regenerated by retrieving and comparing Storage Account keys and Key Vault secret.

可以使用以下命令显示机密信息:You can show secret information using below command:

az keyvault secret show --vault-name akvrotation-kv --name storageKey

请注意,CredentialId 已更新为备用 keyName,并且已重新生成 value第一个存储帐户的 az keyvault secret show 的输出Notice that CredentialId is updated to alternate keyName and value is regenerated Output of az keyvault secret show for the first storage account

检索访问密钥以验证值Retrieve access keys to validate value

az storage account keys list -n akvrotationstorage 

第一个存储帐户的 az storage account keys list 的输出

添加用于轮换的其他存储帐户Add additional Storage Accounts for rotation

可以重复使用同一函数应用来轮换多个存储帐户。Same function app can be reused to rotate multiple Storage Accounts.

若要在现有功能中添加用于轮换的其他存储帐户密钥,需要:Adding additional storage account keys for rotation to existing function requires:

  • 将存储帐户密钥操作员服务角色分配给函数应用,用于访问存储帐户访问密钥Assign Storage Account Key Operator Service role to function app to access Storage Account access keys
  • “SecretNearExpiry”事件的 EventGrid 事件订阅EventGrid event subscription for SecretNearExpiry event
  1. 选择 Azure 模板部署链接:Select the Azure template deployment link:

    图像显示标记为“部署到 Azure”的按钮。Image showing a button labeled "Deploy to Azure".

  2. 在“资源组”列表中选择“akvrotation” 。In the Resource group list, select akvrotation.

  3. 在“存储帐户名称”中,键入包含要轮换的访问密钥的存储帐户名称In the Storage Account Name, type the storage account name with access keys to rotate

  4. 在“密钥保管库名称”中,键入密钥保管库名称In the Key Vault Name, type the key vault name

  5. 在“函数应用名称”中,键入函数应用名称In the Function App Name, type the function app name

  6. 在“机密名称”中,键入存储了访问密钥的机密的名称In the Secret Name, type secret name where access keys would be stored

  7. 选择“查看 + 创建”。Select Review+Create.

  8. 选择“创建”Select Create

    查看并创建第二个存储帐户

将其他存储帐户访问密钥添加到 Key VaultAdd Another Storage Account access key to Key Vault

检索存储帐户资源 ID。Retrieve Storage Account resource ID. 可在 id 属性下找到值Value can be found under id property

az storage account show -n akvrotationstorage2

列出存储帐户访问密钥以检索密钥 2 值List the Storage Account access keys to retrieve key2 value

az storage account keys list -n akvrotationstorage2 

填充“key2Value”和“storageAccountResourceId”的检索值Populate retrieved values for key2Value and storageAccountResourceId

tomorrowDate=`date -d tomorrow -Iseconds -u | awk -F'+' '{print $1"Z"}'`
az keyvault secret set --name storageKey2 --vault-name akvrotation-kv --value <key2Value> --tags "CredentialId=key2" "ProviderAddress=<storageAccountResourceId>" "ValidityPeriodDays=60" --expires $tomorrowDate

使用以下命令显示机密信息:Show secret information using below command:

az keyvault secret show --vault-name akvrotation-kv --name storageKey2

请注意,CredentialId 已更新为备用 keyName,并且已重新生成 value第二个存储帐户的 az keyvault secret show 的输出Notice that CredentialId is updated to alternate keyName and value is regenerated Output of az keyvault secret show for the second storage account

检索访问密钥以验证值Retrieve access keys to validate value

az storage account keys list -n akvrotationstorage 

第二个存储帐户的 az storage account keys list 的输出

可用的保管库双重凭据轮换函数Available Key Vault dual credential rotation functions

了解详细信息Learn more