Certificate not found on Azure Web App - azure

I deployed a web application as a Web App on Azure App Service.
I uploaded some certificates to the Azure Portal, since the Web App runs over SSL, and we use another certificate to perform some decryption.
For the latter case I have a method (which works fine locally) to find a certificate:
public static X509Certificate2 FindCertificate(KnownCertificate certificate)
{
return FindCertificate(StoreName.My, StoreLocation.CurrentUser, X509FindType.FindByThumbprint, certificate.Thumbprint);
}
But I get an error that the certificate with thumbprint XYZ is not found. Although, on the Azure Portal it is present. (I had uploaded and imported it)
I am using StoreLocation.CurrentUser as suggested in THIS POST but it still does not work. Am I using the wrong store or what else am I missing?
EDIT: I have managed to remotetly debug my WebApp and with the ImmediateWindow feature of VisualStudio I have executed this code
new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser).Certificates.Find(findType, findValue, false).Count;
testing all possible combinations of StoreNames and StoreLocations but to no avail.
Is it possible like stated here that for using certificate with purposes other than https traffic you would need a Cloud Service and that (I suppose that) App Services do not support it?

You need to add WEBSITE_LOAD_CERTIFICATES to your web app App Settings. Set the value to either ' * ' or to the thumbprint of your certificate you want loaded into the web app environment. My personal preference is to set this value to ' * ', which means, load all certificates that have been uploaded.
After you apply this change you should be able to load your certificate from within your web app code.
More information on how to use certificates is available here. The article is a bit dated (in today's standards) but still relevant.

Related

Deploying a split-merge service for Azure SQL Elastic (sharded) databases

I am trying to follow the tutorial for deploying a split-merge service (Azure Elastic Database... tools).
The first complication is that the doc instructs me to create an "Azure Cloud Service." The closest thing to that seems to be "Cloud service (classic)," so that's what I created.
When it came to creating a self-signed cert, I had to translate the parameters for makecert (which is deprecated and no longer seems to be present in any SDKs) to the powershell New-SelfSignedCertificate cmdlet. The relevant params I passed to the cmdlet were:
Subject: CN=*.cloudapp.net
KeySpec: KeyExchange
TextExtension: 2.5.29.37={text}1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2
I finally got the certificate created/exported/uploaded, got the service configuration file completed and created the service. Azure portal reports the web and workers running, but I can't hit the service URL (403 access denied even after prompting me to select my certificate). I confirmed that my certificate thumbprint shows correctly in the various places in the service configuration (DataEncryptionPrimaryCertificateThumbprint, DataEncryptionPrimary, AdditionalTrustedRootCertificationAuthorities, AllowedClientCertificateThumbprints, DataEncryptionPrimaryCertificateThumbprint). My certificate's thumbprint also shows as the thumbprint in configuration under the "Certificates" section as SSL, CA, and DataEncryptionPrimary.
The only thing I can think of that is causing the access denied is something mentioned in this doc, "If you are using self-signed certificates, you will need to disable certificate chain validation." The PowerShell cmdlet that it shows to use to disable chain validation in that case (for an API service; no clue how that differs from my service) fails with InvalidOperation.
Is there some way for me to disable certificate chain validation for my "classic" cloud service? Other suggestions of things to check?

X509Certificate2 on Azure App Services (Azure Websites) since mid-2017?

I have a .NET Framework 4.7 application that allows users to upload X.509 certificates in PFX or PKCS#12 format (think: "SSL certificates" with the private key included), it then loads the certificate into a System.Security.Cryptography.X509Certificates.X509Certificate2 instance. As my application code also needs to re-export the certificate I specify the X509KeyStorageFlags.Exportable option.
When running under IIS on my production web-server, the Windows user-profile for the identity that w3wp.exe runs under is not loaded, so I do not specify the UserKeySet flag.
String filePassword = ...
Byte[] userProvidedCertificateFile = ...
using( X509Certificate2 cert = new X509Certificate2( rawData: userProvidedCertificateFile, password: filePassword, keyStorageFlags: X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet )
{
...
}
In early 2017 I deployed this code to an Azure App Service (aka Azure Website) instance and it worked okay - after initially failing because I did have the UserKeySet flag set (as Azure App Services do not load a user-profile certificate store.
However, since mid-2017 (possibly around May or June) my application has stopped working - I assume the Azure App Service was moved to an updated system (though Kudu reports my application is running on Windows Server 2012 (NT 6.2.9200.0).
It currently fails with two error messages that varied depending on input:
CryptographicException "The system cannot find the file specified."
CryptographicException "Access denied."
I wrote an extensive test-case that tries different combinations of X509Certificate2 constructor arguments, as well as with and without the WEBSITE_LOAD_CERTIFICATES Azure application setting.
Here are my findings when working with an uploaded PFX/PKCS#12 certificate file that contains a private key and does not have password-protection:
Running under IIS Express on my development box:
Loading the certificate file always succeeds, regardless of X509KeyStorageFlags value.
Exporting the certificate file requires at least X509KeyStorageFlags.Exportable.
Running under IIS on a production server (not an Azure App Service) where the w3wp.exe user-profile is not loaded:
Loading the certificate file requires that X509KeyStorageFlags.UserKeySet is not set, but otherwise always succeeds.
Exporting the certificate file requires at least X509KeyStorageFlags.Exportable, but otherwise always succeeds, otherwise it fails with "Key not valid for use in specified state."
Running under Azure App Service, without WEBSITE_LOAD_CERTIFICATES defined:
Loading the certificate with MachineKeySet set and UserKeySet is not set fails with a CryptographicException: "Access denied."
Loading the certificate with any other keyStorageFlags value, including values like UserKeySet | MachineKeySet | Exportable or just DefaultKeySet fails with a CryptographicException: "The system cannot find the file specified."
As I was not able to load the certificate at all I could not test exporting certificates.
Running under Azure App Service, with WEBSITE_LOAD_CERTIFICATES defined as the thumbprint of the certificate that was uploaded:
Loading the certificate with MachineKeySet and UserKeySet is not set, fails with CryptographicException: "Access denied." .
So values like UserKeySet and UserKeySet | MachineKeySet and Exportable will work.
Exporting certificates requires X509KeyStorageFlags.Exportable - same as all other environments.
So it seems that WEBSITE_LOAD_CERTIFICATES seems to work - but only if the certificate being loaded into an X509Certificate2 instance has the same thumbprint as specified in WEBSITE_LOAD_CERTIFICATES.
Is there any way around this?
I thought more about how WEBSITE_LOAD_CERTIFICATES seems to make a difference - but I had a funny feeling about it really only working with the certificate thumbprint that's specified.
So I changed the WEBSITE_LOAD_CERTIFICATES value to a dummy thumbprint - an arbitrary 40-character Base16 string, and re-ran my test - and it worked, even though the thumbprint had no relation to the certificate I was working with.
It seems that simply having WEBSITE_LOAD_CERTIFICATES defined will enable the the Azure website's ability to use X509Certificate and X509Certificate2 - even if the loaded certificate is never installed into, or even retrieved from, any systemwide or user-profile certificate store (as seen in the Certificates snap-in for MMC.exe).
This behaviour does not seem to be documented anywhere, so I'm mentioning it here.
I've contacted Azure support about this.
Regarding the behavioural change I noticed at mid-year - it's very likely that I did have WEBSITE_LOAD_CERTIFICATES originally set for a testing certificate we were using. When I made a new deployment later in the year around June I must have reset the Application settings which removed the WEBSITE_LOAD_CERTIFICATES and so broke X509Certificate2 instances.
TL;DR:
Open your Azure App Service (Azure Website) blade in portal.azure.com
Go to the Application settings page
Scroll to App settings
Add a new entry key: WEBSITE_LOAD_CERTIFICATES, and provide a dummy (fake, made-up, randomly-generated) value for it.
The X509Certificate2( Byte[], String, X509KeyStorageFlags ) constructor will now work, but note:
keyStorageFlags: X509KeyStorageFlags.MachineKeySet will fail with "Access denied"
All other keyStorageFlags values, including MachineKeySet | UserKeySet will succeed (i.e. MachineKeySet by itself will fail, but MachineKeySet used in conjunction with other bits set will work).

Azure webapp "Certificate with thumbprint 'XXXXXX...' not found" error

I'm having the following issue with one of my webapps at Azure. It was working fine and suddenly I'm getting the following error, even though no changes were made to the webapps:
"Certificate with thumbprint 'XXXX' not found at
APP.Security.CertificateEncryptionServiceProvider.FindCertificate(X509Store
certStore, String thumbprint) at
APP.Security.CertificateEncryptionServiceProvider.Decrypt(String
thumbprint, String encryptedSetting) at
APP.Configuration.CloudConfiguration.GetSetting"
The other web apps who are using the same certificates are working perfectly fine.
When I navigate to the KUDU powershell console https://MyAppThatHasProblems.scm.azurewebsites.net/DebugConsole/?shell=powershell and navigate to the Certificate Store
cd cert:/currentuser/my
I cannot see any certificate. If I do the same for any other working web app I can see my certificates listed. I tried to remove and add again the certificates, but no luck.
Anyone had a similar issue before?
I have managed to solve the issue with the help of Azure Support. After a series of investigations on the app service they told me to scale up from S2 Standard to S3 Standard and then back to S2. Apparently this changes the virtual machine where the app service is hosted.
Problem fixed!

Upload certificate to azure with exportable flag

I want to make Azure WebApp instance (with .Net WebAPI2) to use Google service account certificate.
Steps I went through:
Create and download .pfx from Google developers console.
Upload .pfx to Azure WebApp -> Custom domains and SSL.
Introduce new variable in AppSettings. Key: WEBSITE_LOAD_CERTIFICATES Value:
(or thumbprint)
After completing these steps I am getting:
CryptographicException. Key not valid for use in specified state.
One of the reasons I would think of is that it needs an exportable private key, but there are no options (or at least I have not found) to change while uploading it.
I have tested the certificate it works locally.
How to solve this?

Cannot add a certificate in local Azure Web role VM

I have some difficulties in managing Azure certificates from my code.
Indeed I'm trying to use Azure REST Services API (e.g. creating HTTP requests) in order to know my services state from my Azure web site.
It works well in local debugging, but my web role seams to have some limitation with the certificates manager. Bellow is what I do:
// this method stores a certificate from the resources
// to the local certificates manager
private X509Certificate2 StoreCertificate(Certificates certName)
{
X509Certificate2 newCert = null;
// get certificate from resources
newCert = this.GetCertificateFromResources(certName);
// store it into the local certificate manager
if (newCert != null)
{
var store = new X509Store(
StoreName.TrustedPeople,
StoreLocation.LocalMachine
);
store.Open(OpenFlags.ReadWrite);
store.Add(newCert);
}
// reset ref and try to load it from manager
newCert = null;
newCert = this.GetCertificate(certName);
return newCert;
}
An Access is denied error appends when I try to add the certificate.
Any idea ? Can I store certificates into the Azure VM ?
Should I use a special location to store those ?
Are you using a Cloud Service (web/worker role)? If so, which OS family? I've seen some reports that with a worker role using OS family 3, you need to run the role with elevated permissions in order to read certs from the local cert store. Not sure if that applies to web roles as well and adding to the cert store.
Has the service cert been added via the Azure management portal as well (or via the REST API or PowerShell)?
Well I have found lot of things:
I was deploying my code in a web site so that I cannot add a certificate to the Shared VM in Azure
I have tried to connect to the VM in a remote desktop session and I added a certificate manually.
Even in this case, I have an (403) Forbidden error in an InvalidOperationException.
So here is the current state:
a certificate has been created (makecert) and added manually in the VM that hosts my web role (deployed in a service)
this certificate has been uploaded to both the Azure Account certificates and to the Azure service certificates (the one that deploys my web role)
the thumbprint of this certificate has been added in my code and I can access to the certificate when my code is executed
So 2 questions:
Is there something I should do with my certificate ?
When I try my web role locally in the Azure emulator, everything works. Is there a special setting to update during the publish / deploy step ?
Thanks for your help.
In order to save the time of other developers, here is what I did to solve the main problem:
connect to the VM that deploys the web role: see there
create the certificate: see there
Eventually plays with the certificates manager (mmc.exe)
Then the certificate is available from the code.

Resources