Improve KeyVault error message when Service Principal does not have correct Graph permissions
Cmdlet(s)
Set-AzureRmKeyVaultAccessPolicy
PowerShell Version
5.1.14393.1198
Module Version
3.0.0 AzureRM.KeyVault
OS Version
BuildVersion 10.0.14393.1198
Description
I meet following error when prepare test environment for new cmdlets of customer Key.
When I logon with Service Principle, and run Set-AzureRmKeyVaultAccessPolicy. • Success to set PermissionsToKeys for a servicePriciple ID, • Fail in set PermissionsToKeys for an Account Identity PrincipalId. But when I logon by run “Login-AzureRMAccount” and authenticate with my phone, both will success.
Do you have any idea why this happen? Or do you know who should I contact for this issue? Thanks!
Debug Output
PS C:\WINDOWS\system32> Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $resourceGroup -ObjectId $a.Identity.PrincipalId -PermissionsToKeys wrapkey,unwrapkey -debug DEBUG: 4:42:50 PM - SetAzureKeyVaultAccessPolicy begin processing with ParameterSet 'ByObjectId'. DEBUG: 4:42:51 PM - using account id 'b8cec3bc-8c00-46ec-97f6-e0fb8549de1b'... DEBUG: [Common.Authentication]: Authenticating using Account: 'b8cec3bc-8c00-46ec-97f6-e0fb8549de1b', environment: 'AzureCloud', tenant: '72f988bf-86f1-41af-91ab-2d7cd011db47' DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:52: 911fa572-b9a3-4924-83d3-2e60f81cd54b - AcquireTokenHandlerBase: === Token Acquisition started: Authority: https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/ Resource: https://management.core.windows.net/ ClientId: b8cec3bc-8c00-46ec-97f6-e0fb8549de1b CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (3 items) Authentication Target: Client
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : DEBUG: 05/19/2017 08:42:52: 911fa572-b9a3-4924-83d3-2e60f81cd54b - TokenCache: Looking up cache for a token...
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:52: 911fa572-b9a3-4924-83d3-2e60f81cd54b - TokenCache: An item matching the requested resource was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : DEBUG: 05/19/2017 08:42:52: 911fa572-b9a3-4924-83d3-2e60f81cd54b - TokenCache: 45.9864928316667 minutes left until token in cache expires
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:52: 911fa572-b9a3-4924-83d3-2e60f81cd54b - TokenCache: A matching item (access token or refresh token or both) was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:52: 911fa572-b9a3-4924-83d3-2e60f81cd54b - AcquireTokenHandlerBase: === Token Acquisition finished successfully. An access token was retuned: Access Token Hash: CrLva2PU6N9Iw5Jb1GudK7WhzRII2BnBt7S9jm5kjzI= Refresh Token Hash: [No Refresh Token] Expiration Time: 05/19/2017 09:28:51 +00:00 User Hash: null
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:52: - TokenCache: Serializing token cache with 3 items.
DEBUG: ============================ HTTP REQUEST ============================
HTTP Method: GET
Absolute Uri: https://management.azure.com/subscriptions/45b60d85-fd72-427a-a708-f994d26e593e/resourceGroups/weicmk3/providers/Microsoft.KeyVault/vaults/weikeyvaultcmk3?api-version=2016-10-01
Headers: x-ms-client-request-id : 330a8912-67ed-4f6a-9f23-b5051d304ad1 accept-language : en-US
Body:
DEBUG: ============================ HTTP RESPONSE ============================
Status Code: OK
Headers: Pragma : no-cache x-ms-keyvault-service-version : 1.0.0.157 Strict-Transport-Security : max-age=31536000; includeSubDomains X-Content-Type-Options : nosniff x-ms-ratelimit-remaining-subscription-reads: 14992 x-ms-request-id : dd2d991d-6cdb-41c5-9123-9e3bc45cea21 x-ms-correlation-request-id : dd2d991d-6cdb-41c5-9123-9e3bc45cea21 x-ms-routing-request-id : JAPANEAST:20170519T084254Z:dd2d991d-6cdb-41c5-9123-9e3bc45cea21 Cache-Control : no-cache Date : Fri, 19 May 2017 08:42:53 GMT Server : Microsoft-IIS/8.5 X-AspNet-Version : 4.0.30319 X-Powered-By : ASP.NET
Body: { "id": "/subscriptions/45b60d85-fd72-427a-a708-f994d26e593e/resourceGroups/weicmk3/providers/Microsoft.KeyVault/vaults/weikeyvaultcmk3", "name": "weikeyvaultcmk3", "type": "Microsoft.KeyVault/vaults", "location": "EastUS2EUAP", "tags": {}, "properties": { "sku": { "family": "A", "name": "standard" }, "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", "accessPolicies": [ { "tenantId": "72f988bf-86f1-41af-91ab-2d7cd011db47", "objectId": "d01193d9-1f39-4fed-b37c-34f82671908d", "permissions": { "keys": [ "get", "delete", "list", "create", "import", "update", "recover", "backup", "restore", "sign", "verify", "wrapKey", "unwrapKey", "encrypt", "decrypt" ], "secrets": [], "certificates": [] } } ], "enabledForDeployment": false, "enabledForDiskEncryption": false, "enabledForTemplateDeployment": false, "vaultUri": "https://weikeyvaultcmk3.vault.azure.net/" } }
DEBUG: [Common.Authentication]: Authenticating using configuration values: Domain: '72f988bf-86f1-41af-91ab-2d7cd011db47', Endpoint: 'https://login.microsoftonline.com/', ClientId: '1950a258- 227b-4e31-a9cf-717495945fc2', ClientRedirect: 'urn:ietf:wg:oauth:2.0:oob', ResourceClientUri: 'https://graph.windows.net/', ValidateAuthrity: 'True' DEBUG: [Common.Authentication]: Renewing token using AppId: '----*********', AdalConfiguration with ADDomain: '----*********', AdEndpoint: 'https ://login.microsoftonline.com/', ClientId: '1950a258-227b-4e31-a9cf-717495945fc2', RedirectUri: 'urn:ietf:wg:oauth:2.0:oob' DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:54: 8c49eae5-ddf7-4282-9559-473ea4dc965a - AcquireTokenHandlerBase: === Token Acquisition started: Authority: https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/ Resource: https://graph.windows.net/ ClientId: b8cec3bc-8c00-46ec-97f6-e0fb8549de1b CacheType: Microsoft.Azure.Commands.Common.Authentication.AuthenticationStoreTokenCache (3 items) Authentication Target: Client
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : DEBUG: 05/19/2017 08:42:54: 8c49eae5-ddf7-4282-9559-473ea4dc965a - TokenCache: Looking up cache for a token...
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:54: 8c49eae5-ddf7-4282-9559-473ea4dc965a - TokenCache: An item matching the requested resource was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : DEBUG: 05/19/2017 08:42:54: 8c49eae5-ddf7-4282-9559-473ea4dc965a - TokenCache: 46.4776900516667 minutes left until token in cache expires
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:54: 8c49eae5-ddf7-4282-9559-473ea4dc965a - TokenCache: A matching item (access token or refresh token or both) was found in the cache
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:54: 8c49eae5-ddf7-4282-9559-473ea4dc965a - AcquireTokenHandlerBase: === Token Acquisition finished successfully. An access token was retuned: Access Token Hash: Jzb84XxnWP3OyYulb2fqK2saCE11GvcbTZoW2f7+jxs= Refresh Token Hash: [No Refresh Token] Expiration Time: 05/19/2017 09:29:23 +00:00 User Hash: null
DEBUG: Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : DEBUG: 05/19/2017 08:42:54: - TokenCache: Serializing token cache with 3 items.
Set-AzureRmKeyVaultAccessPolicy : Insufficient privileges to complete the operation. At line:1 char:1
- Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGro ...
-
+ CategoryInfo : CloseError: (:) [Set-AzureRmKeyVaultAccessPolicy], ODataErrorException + FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.SetAzureKeyVaultAccessPolicy
DEBUG: 4:42:56 PM - SetAzureKeyVaultAccessPolicy end processing. DEBUG: 4:42:56 PM - SetAzureKeyVaultAccessPolicy end processing.
Script/Steps for Reproduction
My Script:
#Login with Service Principal
$secpasswd = ConvertTo-SecureString "y*************************************=" -AsPlainText -Force #password is marked
$cred = New-Object System.Management.Automation.PSCredential ("********-****-****-****-*************", $secpasswd)
Login-AzureRMAccount -ServicePrincipal -Tenant ********-****-****-****-************* -SubscriptionId ********-****-****-****-************* -Credential $cred
$resourceGroup =
$accountName =
$keyVaultName =
$KeyName =
#create Account
New-AzureRmResourceGroup –Name $resourceGroup –Location 'EastUS2EUAP'
New-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $accountName -SkuName Standard_GRS -Location 'EastUS2EUAP' -IdentityType SystemAssigned
$a = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $accountName
# Create KeyVault
$vault = New-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $resourceGroup -Location 'EastUS2EUAP'
$vault = Get-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $resourceGroup
Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $resourceGroup -ServicePrincipalName ********-****-****-****-************* -PermissionsToKeys all #Success
Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $resourceGroup -ObjectId $a.Identity.PrincipalId -PermissionsToKeys wrapkey,unwrapkey -debug #Fail
@blueww Can you include the Vault permissions for this service principal? This may be an expected authorization failure.
Also, PrincipalId may not be the same as Graph ObjectId
for the service proncipal ,the permission is:
Tenant ID : ----* Object ID : ----* Application ID : Display Name : DMTestCredentials (b*******----*********) Permissions to Keys : get, delete, list, create, import, update, recover, backup, restore, sign, verify, wrapKey, unwrapKey, encrypt, decrypt Permissions to Secrets : Permissions to Certificates :
But the point it when I log in with phone it work, but it not work when log in with service principal.
@blueww These permissions are just about KeyVault data plane, not about management plane cmdlets. In order for an SPN to have access to the KeyVault resource, it must be given role access through RBAC to the KeyVault.
Can you leas eprovide the full script of what exacly is working and what exactly isn't working? Right now I cannpot tell if this is an expected failure, or if this is a bug.
@markcowl
The RoleDefination for the service principle is Owner
RoleAssignmentId : /subscriptions/ce4a7590-4722-4bcf-a2c6-e473e9f11778/providers/Microsoft.Authorization/roleAssignments/5381d923-3425-45ab-8d42-f9b087761a23
Scope : /subscriptions/ce4a7590-4722-4bcf-a2c6-e473e9f11778
DisplayName : weiwei's AAD app
SignInName :
RoleDefinitionName : Owner
RoleDefinitionId : 8e3af657-a8ff-443c-a75c-2fe8c4bcb635
ObjectId : d6f7e858-345d-45f6-849c-8175519656b7
ObjectType : ServicePrincipal
Following is the script that can repro the failure, the last line of the script will fail:
#Login with Service Principal
$secpasswd = ConvertTo-SecureString "F*************************************=" -AsPlainText -Force #password is marked
$cred = New-Object System.Management.Automation.PSCredential ("********-****-****-****-*************", $secpasswd)
Login-AzureRMAccount -ServicePrincipal -Tenant 72f988bf-86f1-41af-91ab-2d7cd011db47 -SubscriptionId ce4a7590-4722-4bcf-a2c6-e473e9f11778 -Credential $cred
$resourceGroup =
$accountName =
$keyVaultName =
$KeyName =
#create Account
New-AzureRmResourceGroup –Name $resourceGroup –Location 'EastUS2EUAP'
New-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $accountName -SkuName Standard_GRS -Location 'EastUS2EUAP' -AssignIdentity
$a = Get-AzureRmStorageAccount -ResourceGroupName $resourceGroup -Name $accountName
# Create KeyVault
$vault = New-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $resourceGroup -Location 'EastUS2EUAP'
$vault = Get-AzureRmKeyVault -VaultName $keyVaultName -ResourceGroupName $resourceGroup
#Following command fail when login with service priciple, success when login with mobile phone
Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $resourceGroup -ObjectId $a.Identity.PrincipalId -PermissionsToKeys wrapkey,unwrapkey
The following is the exception stack trace for the error. We can see the error happen in ValidateObjectId()
at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.DataServiceContextWrapper.
d__59 1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient.<GetObjectsByObjectIdsAsync>d__5.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Microsoft.Azure.Commands.KeyVault.KeyVaultManagementCmdletBase.ValidateObjectId(String objId) in c:\Code\PSH_Dev\src\ResourceManager\KeyVault\Commands.KeyVault\Models\KeyVaultManagementCmdletBase.cs:line 276 at Microsoft.Azure.Commands.KeyVault.KeyVaultManagementCmdletBase.GetObjectId(String objectId, String upn, String email, String spn) in c:\Code\PSH_Dev\src\ResourceManager\KeyVault\Commands.KeyVault\Models\KeyVaultManagementCmdletBase.cs:line 292 at Microsoft.Azure.Commands.KeyVault.SetAzureKeyVaultAccessPolicy.ExecuteCmdlet() in c:\Code\PSH_Dev\src\ResourceManager\KeyVault\Commands.KeyVault\Commands\SetAzureKeyVaultAccessPolicy.cs:line 331 at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord() in C:\Code\PSH_Dev\src\Common\Commands.Common\AzurePSCmdlet.cs:line 642
Adding parameter "-BypassObjectIdValidation" can make the cmdlet run success, since it will skip the ObjectID validation.
Set-AzureRmKeyVaultAccessPolicy -VaultName $keyVaultName -ResourceGroupName $resourceGroup -ObjectId $a.Identity.PrincipalId -PermissionsToKeys wrapkey,unwrapkey -BypassObjectIdValidation
@blueww So then this is occurring because the ServicePrincipal does not have access to the objects in the AD graph tenant (the service principal must be assigned sufficient permissions in AD Graph to get and list graph objects for validation to work). It would be nice to have a better error message in thei case. Assignign to KeyVaiult team for improved errors
@pomortaz @dragav Can we look at a better error message when object id validation fails - this will often happen in scenarios like this and it is unclear to the user how to correct the issue (providing sufficient graph permissions to the principal)
One thing interesting is which kind of permission does the service principle need to have the object id validation success. Do you have any idea?
BTW, when I debug the code, I see this.ServicePrincipalName input in following API is null. I am not sure is it a bug that the input ServicePrincipalName is not correctly transferred to the API.
objId = GetObjectId(this.ObjectId, this.UserPrincipalName, this.EmailAddress, this.ServicePrincipalName)
Why don't you show how the script can be ran and work?