error while trying to decrypt using azure vault certificate key: "Operation returned an invalid status code 'Forbidden'" - azure

I am trying to decrypt a encrypted string through C# code and azure key vault certificate key, the encryption part works fine but while decrypting, an exception occurs saying : "Operation returned an invalid status code 'Forbidden'", "Operation decrypt is not permitted on this key."
I have allowed all the permissions while registering this to Azure AD "App registrations" option from the AD blade. Is there any other place where I need to add any more permissions. Have followed this article to setup the Certificate and association with AD.
A line of the code I am using for decryption:
var decryptedData = kv.DecryptAsync(key.Key.Kid,JsonWebKeyEncryptionAlgorithm.RSAOAEP, encryptedTextNew).GetAwaiter().GetResult();
If any one has done this, please write back in the comment, will be of great help.

Maybe my situation is difference, but I'm going to drop some detail here just in case someone runs into the same problem.
I created a certificate (note: a certificate, not a key) on Azure Key Vault UI and used it for encrypt/decrypt and got the Operation returned an invalid status code 'Forbidden' error.
I tried to create a new certificate but this time I checked all the Advanced Policy Configuration options (you should only check the options you need though) and the new one worked for me:

Operation returned an invalid status code 'Forbidden'
As I have tested, It seems that you do not configure the Access Policy in Key Vault for your application, to access keys or to process encryption/decryption.
Also, please have a check that if you add the role assignments of app registered to azure keyvault.
For more details, you could refer to this article which I have a test and it works fine.

This error also occurs if you try to use this kind of certificate in a Logic app with AS2Decode.
The error you will get then is:
Integration account operation failed with status code: Forbidden and
error KeyVaultOperationFailed : Communication with key vault
'..........KeyVault' failed. Please authorize logic apps to perform
operations on key vault by granting access for the logic apps service
principal '7cd684f4-8a78-49b0-91ec-6a35d38739ba' for 'list', 'get',
'decrypt' and 'sign' operations.
Thank you for this solution!

I had the same issue. Make sure that during certificate upload or generation, you set the Data encipherment option in Advanced Policy Configuration. This can only be done during initial set-up. Changing it later does not work.
Advanced Policy Configuration

Related

Azure Container Apps with Dapr state store failing

I am using Azure Container apps with Azure Blob Store as a state store. It is a simple Hello World (weather service) app using dotnet 6. App starts up fine, on Post I am trying to save the generated weather information to Azure Blob Store as JSON. I have configured Dapr components in Azure Container Apps for StateStore using Azure blob storage. I am using storage key (secondary key) as explained in this Microsoft documentation
Upon doing a Swagger and looking at log I get the following error.
Dapr.DaprException: State operation failed: the Dapr endpoint indicated a failure. See InnerException for details.
2022-07-17T01:10:35.716245402Z ---> Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="failed saving state in state store statestore: -> github.com/Azure/azure-storage-blob-go/azblob.newStorageError, /home/vsts/work/1/go/pkg/mod/github.com/!azure/azure-storage-blob-go#v0.10.0/azblob/zc_storage_error.go:42
2022-07-17T01:10:35.716524109Z ===== RESPONSE ERROR (ServiceCode=AuthenticationFailed) =====
2022-07-17T01:10:35.716795515Z Description=Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
2022-07-17T01:10:35.716812515Z RequestId:863bcef4-401e-0069-5f7a-99724b000000
2022-07-17T01:10:35.716820115Z Time:2022-07-17T01:10:35.7137648Z, Details:
2022-07-17T01:10:35.716825516Z AuthenticationErrorDetail: Issuer validation failed. Issuer did not match.
2022-07-17T01:10:35.716831516Z Code: AuthenticationFailed
Error is Authentication Failed. I am unsure what I am missing since I am not making any additional config in storage account such as VNET service end point etc. Account is enabled for Key access. Any help is appreciated.
Below is the code that I am using
using var client = new DaprClientBuilder().Build();
var forecast = new WeatherForecast()
{
Date = DateTime.Now.AddDays(1),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
};
await client.SaveStateAsync<WeatherForecast>(stateStoreName,key,forecast);
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
i think i found the answer. The issue was with metadata since the key set in metadata of the component.yaml as mentioned in the Microsoft documentation is not working. I changed it to use secretref and referred in metadata directly in the portal. Not sure why the error was showing Authentication error but it is finally working.

Key Vault returns 401 using ManagedIdentityCredential for App Service (Azure.Identity 1.3.0)

In my Startup.cs I add key vault clients as such:
services.AddAzureClients(s =>
{
var keyVaultUri = new Uri(Configuration["KeyVault:Uri"]);
s.AddCertificateClient(keyVaultUri);
s.AddSecretClient(keyVaultUri);
s.UseCredential(new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
VisualStudioTenantId = Configuration["AzureAd:TenantId"]
}));
});
Locally, I can authenticatie with the VisualStudioCredential. All works fine. When deployed I run into the following error:
The key vault returns a 401 even though I successfully got a token. I am using Access Control on the key vault and it my Managed Identity is a Key Vault Administrator.
What could be going on here and how can I debug this further? I have been stuck on this for a while now.
EDIT:
Title is misleading and what I thought was happening was not happening. There was no authentication issue but it looked as such in the logs due to another exception I was getting. This was occurring due to the fact my App Service Plan didn't have SSL/TLS functionality required to work with certificates, I needed a more expensive App Service Plan.
Please see this GitHub issue: https://github.com/dotnet/runtime/issues/30658#issuecomment-523987878
You need to give your Managed Identity an access policy on the Key Vault, not an RBAC access.
RBAC in this case is for management plane operation. Access policies are for data plane operations - which is what you want.
https://learn.microsoft.com/en-us/azure/key-vault/general/secure-your-key-vault

Unable to create an index/synonym map in Azure Cognitive Search with "Customer" managed encryption key option

I am trying to create an index/synonym map with encryption using "Customer" managed key option however I am not able to do so.
I am constantly getting the following error back from the service:
Failed to verify account key (HTTP Status Code: 403).
Here's what my request body for synonym map looks like:
{
"name":"test",
"format":"solr",
"synonyms":"",
"encryptionKey":
{
"keyVaultKeyName":"AzSearchKey2",
"keyVaultKeyVersion":"02cc721e41654f079c173744313f24b0",
"keyVaultUri":"https://mykeyvault.vault.azure.net"
}
}
I have completely followed the instructions specified here: https://learn.microsoft.com/en-gb/azure/search/search-security-manage-encryption-keys.
Here's what I have done so far:
I created a search service with "Basic" SKU (as this functionality is not available in "Free" tier).
I went to the "Identity" section of my search service and assigned that as managed identity.
I created a brand new Key Vault with "Standard" tier and defined an access policy for the above mentioned identity. I granted necessary "Key" permissions ("Get", "Wrap Key", "Unwrap Key") as mentioned in the documentation link above to the Search Service. This Key Vault is in the same region and resource group as that of the Search Service. Key vault also has "Soft Delete" and "Purge Protection" enabled.
I created a key and copied down the details (URI, key name and key version).
I believe I am doing everything that is mentioned in the documentation so I am not sure what am I doing wrong.
Interesting thing is that I was able to do this without any problem yesterday with another search service and key vault.
My guess is that I am missing some minor detail. Would appreciate if someone could point it out for me.
UPDATE
Big thanks to Cognitive Search team for working with me on this. The error message I am getting is because of an issue with the code (I was returning a standard message whenever the service returned 403 status code).
The service is still returning the error. The actual error message returned by the service is:
Could not use key vault key https://mykeyvault.vault.azure.net:443/keys/AzSearchKey2/02cc721e41654f079c173744313f24b0
to wrap/unwrap the encryption key. The key vault key deletion-recovery level is insufficient.
Soft-Delete and Purge Protection must be enabled on Key vault, see: https://aka.ms/key-vault-soft-delete
After following up privately with Gaurav, we came to the conclusion that it was due to the key retention period being too short (7 days retention instead of 90 days). We just updated the product code to support shorter retention periods (down to 7 days), and the patch will be deployed globally in the upcoming weeks. In the meantime, if you hit the same issue, please update your key retention policy to 90 days. You can recognize this error state if you receive the following message from Azure Search when creating an encrypted index or synonym map:
DataPlaneApiException : Could not use key vault key (YOUR_KEY_URL) to wrap/unwrap the encryption key. The key vault key deletion-recovery level is insufficient. Soft-Delete and Purge Protection must be enabled on Key vault, see: https://aka.ms/key-vault-soft-delete.
Thank you

Error getting SAML Metadata for Azure AD B2C Policy - AADB2C90022

Setting up a custom policy in Azure AD B2C to connect to an ADFS Identity Provider. This requires a SAML metadata endpoint as specified in the documentation at the link below.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-custom-setup-adfs2016-idp#configure-an-adfs-relying-party-trust
The error being encountered is:
AADB2C90022: Unable to return metadata for the policy [my-policy] in tenant [my-tenant].onmicrosoft.com.
and is being encountered when I go to the endpoint:
https://login.microsoftonline.com/te/[my-tenant].onmicrosoft.com/[my-policy]/samlp/metadata?idptp=[my-technical-profile]
I have tried making the request from the b2clogin.com endpoint with the same result as above.
E.g. https://[my-tenant].b2clogin.com/te/[my-tenant].onmicrosoft.com/[my-policy]/samlp/metadata?idptp=[my-technical-profile]
I have also tried using my tenantId GUID in place of [my-tenant].onmicrosoft.com which resulted in the exact same result.
E.g. https://login.microsoftonline.com/te/[my-tenant-id]/[my-policy]/samlp/metadata?idptp=[my-technical-profile]
Re-visit the process by which you created the certificate, uploaded it to your 'Policy Keys' and referenced it in your custom policy files.
My scenario was similar, I had the same error and no output via Application Insights / Journey Recorder.
I had tried to avoid using 'makecert.exe' and instead used another SSC generation tool. This simply did not work, I think because the private key was not being incorporated in the certificate file.
This guide has been invaluable, see also this test facility

Vault: How to tell response wrapped-token was already read

Im using Vault by HashiCorp to store my secrets, and as was advised in this blog: on target_application-startup I provide to a Response-Wrapped token via the ENV_PARAM to authenticate with vault.
Next, the target_application tries to get the permanentToken but fails
due to 2 possible cases where I cant access Vault:
The token the target_application got is already expired.
The token was already read by somebody else so I cant read it now.
In both cases I get "permission denied" from vault.
How can I check that the 2nd case happened?
A solution that works for me:
when creating a response-wrapped token you get: 1.token creation time 2. token's time to live
Adding these two and passing the result to the target-application helps you (in case of getting denial of token) determine which of the 2 occurred.

Resources