Graduate Program KB

Azure Key Vault

  • Supports two types of containers: vaults and managed hardware security module (HSM) pools
  • Vaults store software and HSM-backed keys, secrets and certificates
  • Managed HSM pools only support HSM-backed keys
  • Addresses following problems:
    • Secrets Management: Used to securely store tokens, passwords, certificates, API keys and other secrets
    • Key Management: Easy to create and control encryption keys for data encryption
    • Certificate Management: Allows you to easily provision, manage and deploy public and private SSL/TLS certificates
  • Two service tiers available: Standard (software key encryption) and Premium (HSM-protected keys)
  • Benefits:
    • Centralised application secrets
    • Securely store secrets and keys
    • Monitor access and use
    • Simplified administration of application secrets

Best Practices

  • You must be authenticated before being able to use an Key Vault operations, there are three ways to do so:
    • Managed identities for Azure resources
    • Service principal and certifcate
    • Service principal and secret
  • Key Vault enforces TLS protocol to protect traveling data between itself and clients
    • Clients negotiate TLS connection, receiving strong authentication, message privacy, integrity, interoperability, algorithm flexibility and ease of deployment
    • Perfect Forward Secrecy (PFS) protects connections between clients and Microsoft cloud services
  • Use separate key vaults
  • Control access to your vault
  • Backup
  • Logging
  • Recovery options

Authenticate to Azure Key Vault

  • Integrates with Microsoft Entra ID for authenticating the identity of any given security principal
  • Two ways to obtain a service principal:
    • Enable system-assigned managed identity for the application
    • If you can't use managed identity, register the application with your Mircosoft Entra tenant
  • Example of authentication to Key Vault with REST:
    PUT /keys/MYKEY?api-version=<api_version>  HTTP/1.1  
    Authorization: Bearer <access_token>
    
    401 Not Authorized  
    WWW-Authenticate: Bearer authorization="…", resource="…"
    

Managed Identities

  • A common challenge is management of secrets, credentials and keys used to secure communication between services
  • Managed identities eliminate the need for developers to manage these credentials
  • There are two types of managed identities:
    • System-assigned managed identity: Enabled directly on Azure service instance
      • Shared lifecycle with the Azure resource the identity is created with
      • Can't be shared across Azure resources
      • Use cases: Workloads needing independent identities, contained with a single resource or an app running on a VM
    • User-assigned managed identity: Created as a standalone Azure resource
      • Independent lifecycle
      • Can be shared across Azure resources
      • Use cases: Workloads running on multiple resources as one identity, recycled resources, multiple VMs or requiring pre-authorisation to a secure resource

Managed Identities Authentication Flow

  • System-assigned managed identity with an Azure VM
    1. ARM receives a request to enable system-assigned managed identity on VM
    2. ARM creates a service principal in Entra ID for the identity of the VM
    3. ARM configures identity on VM by updating Azure Instance Metadata Service identity endpoint with the service principle client ID and certificate
    4. When VM has identity, the service principal information is used to grant VM access to Azure resources
    5. Code running on the VM can request a token from the Azure Instance Metadata service endpoint (http://169.254.169.254/metadata/identity/oauth2/token)
    6. Call is made to Microsoft Entra ID to request an access token by using the client ID and certifcate (Entra returns JWT access token)
    7. Code sends access token on a call to a service that supports Entra authentication
  • User-assigned managed identity with an Azure VM
    1. ARM receives a request to create a user-assigned managed identity
    2. ARM creates a service principal in Entra ID for the user-assigned managed identity
    3. ARM receives a request to configure the user-assigned managed identity on a VM and updates the Azure Instance Metadata Service identity endpoint with the principal client ID and certifcate
    4. When the user-assigned managed identity is created, the service principal information is used to grant identity access to Azure resources
    5. Code running on the VM can request a token from the Azure Instance Metadata service endpoint (http://169.254.169.254/metadata/identity/oauth2/token)
    6. Call is made to Microsoft Entra ID to request an access token by using the client ID and certifcate (Entra returns JWT access token)
    7. Code sends access token on a call to a service that supports Entra authentication

Configure Managed Identities

  • You can configure a VM with a managed identity during or after the creation of it
  • System-assigned managed identity:
    • Need the Virtual Machine Contributor role assignment, no other Entra directory role assignments are required
    • During creation of VM:
    az vm create --resource-group myResourceGroup \ 
    --name myVM --image win2016datacenter \ 
    --generate-ssh-keys \ 
    --assign-identity \ 
    --role contributor \
    --scope mySubscription \
    --admin-username azureuser \ 
    --admin-password myPassword12
    
    • On existing VM:
    az vm identity assign -g myResourceGroup -n myVm
    
  • User-assigned managed identity:
    • Need the Virtual Machine Contributor and Managed Identity Operator role assignments, no other Entra directory role assignments are required
    • During creation of VM:
    az vm create \
    --resource-group <RESOURCE GROUP> \
    --name <VM NAME> \
    --image Ubuntu2204 \
    --admin-username <USER NAME> \
    --admin-password <PASSWORD> \
    --assign-identity <USER ASSIGNED IDENTITY NAME> \
    --role <ROLE> \
    --scope <SUBSCRIPTION>
    
    • On existing VM:
    az vm identity assign \
        -g <RESOURCE GROUP> \
        -n <VM NAME> \
        --identities <USER ASSIGNED IDENTITY>
    

Acquiring Access Token

  • A client app can request managed identities for resources app-only access token for accessing a given resource
    • Token is based on managed identities for Azure resources service principal
  • Recommended method is to use DefaultAzureCredential
    • Attempts to authenticate via the following mechanisms in order, stopping when one succeeds:
      • Environment: Reads account information via environment variables
      • Managed Identity
      • Visual Studio
      • Azure CLI: Authenticated via az login command
      • Azure PowerShell: Authenticated via the Connect-AzAccount command
      • Interactive browser: If enabled, authenticates developer via current system's default browser
    • Example authenticating the SecretClient from Key Vault client library
    var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), new DefaultAzureCredential());
    
    • Example of specifying a user-assigned managed identity:
    string userAssignedClientId = "<your managed identity client Id>";
    var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });
    
    var blobClient = new BlobClient(new Uri("https://myaccount.blob.core.windows.net/mycontainer/myblob"), credential);
    
    • Example of defining custom authentication flow with ChainedTokenCredential
    var credential = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential());
    
    var eventHubProducerClient = new EventHubProducerClient("myeventhub.eventhubs.windows.net", "myhubpath", credential);
    

Implement Azure App Configuration

  • Provides a service to centrally manage app settings and feature flags
  • Benefits:
    • Fully managed
    • Flexible key representations and mappings
    • Tagging with labels
    • Point-in-time replay of settings
    • Dedicated UI for feature flag management
    • Comparison of two sets of configurations on custom-defined dimensions
    • Enhanced security through Azure-managed identities
    • Encryption of sensitive information at rest and in transit
    • Native integration with popular frameworks
  • Scenarios which complement Key Vault:
    • Centralised management and distribution of hierarchical configuration data for different environments and geographies
    • Dynamically change application settings without the need to redeploy or restart an application
    • Control feature availability in real-time

Create Paired Keys and Values

  • Example of key names structured in hierarchy based on component services:
    • Keys stored in App Configuration are case-sensitive unicode-based strings (app1 and App1 are distinct)
    AppName:Service1:ApiEndpoint
    AppName:Service2:ApiEndpoint
    
    • Two general approaches for naming keys are flat or hierarchical
      • Hierarchical is easier to read, manage and use
    • A label attribute can be added optionally to create variants of a key
    Key = AppName:DbEndpoint & Label = Test
    Key = AppName:DbEndpoint & Label = Staging
    Key = AppName:DbEndpoint & Label = Production
    
  • Values are also assigned to keys as unicode strings

Manage Application Features

  • Concepts:
    • Feature flag: Variable with a binary state of on or off to conditionally execute pieces of code
    • Feature manager: Application package handling lifecycle of all feature flags
    • Filter: A rule for evaluating the state of a feature flag
  • Effective implementation of feature management consists of apps using feature flags and a separate repository storing the flags and their current states
  • Example of feature flag in code:
    if (featureFlag) {
        // Run the following code
    }
    
  • Feature flag declaration consists of two parts: a name and list
    • Feature flags with multiple filters are traversed in order until one filter determines the feature should be enabled
    • Feature manager supports appsettings.json as a configuration source for flags
    "FeatureManagement": {
        "FeatureA": true, // Feature flag set to on
        "FeatureB": false, // Feature flag set to off
        "FeatureC": {
            "EnabledFor": [
                {
                    "Name": "Percentage",
                    "Parameters": {
                        "Value": 50
                    }
                }
            ]
        }
    }
    
  • A feature flag repository allows you to externalise your feature flags used in the application, allowing you to change states without modifying and redeploying the application itself

Secure App Configuration Data

  • Encrypt configuration data via customer-managed keys
    • Azure App Configuration encrypts sensitive information at rest using a 256-bit AES encryption key provided by Microsoft
    • The following components are required to successfully enable the customer-managed key capability for Azure App Configuration:
      • Standard tier Azure App Configuration instance
      • Key Vault with soft-delete and purge-protection features enabled
      • RSA or RSA-HSM key within the Key Vault (key must not be expired, must be enabled and must have both wrap and unwrap capabilities enabled)
    • Once the resources are configured, just assign a managed identity to an app configuration instance and grant the identity GET, WRAP and UNWRAP permissions in the target Key Vault's access policy
  • You can use private endpoints for Azure App Configuration to allow clients on a virtual network to securely access data over a private link
    • Enables you to:
      • Secure app configuration details by configuring the firewall to block all connections to App Configuration on the public endpoint
      • Increase security for the virtual network
      • Securely connect App Configuration store from on-premises networks that connect virtual network using VPN or ExpressRoutes with private-peering
  • A managed identity from Entra ID allows App Configuration to easily access other Entra ID protected resources such as Key Vault
    • Can use either system-assigned identity or user-assigned identity
    • Adding system-assigned identity:
    az appconfig identity assign \ 
    --name myTestAppConfigStore \ 
    --resource-group myResourceGroup
    
    • Adding user-assigned identity:
    az identity create --resource-group myResourceGroup --name myUserAssignedIdentity
    
    az appconfig identity assign --name myTestAppConfigStore \ 
        --resource-group myResourceGroup \ 
        --identities /subscriptions/[subscription id]/resourcegroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myUserAssignedIdentity