Issue while retrieving KeyVault Secret - c#

Trying to retrieve the KeyVault Secret by AD authentication using Certificate.
Documentation Reffered for Creating KeyVault & AD application using Certificate
public static async Task<string> GetAccessToken(string authority, string resource, string scope) {
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, AssertionCert);
return result.AccessToken; }
Code fails while
var result = await context.AcquireTokenAsync(resource,AssertionCert)
InnerException contains: "Keyset does not exists"
And some times "Invalid provider type specified." error occurs
Not sure where is the issue.

I have resolved this issue after running my application as Administrator.

Assuming the AssertionCert is valid, it's likely a permission issue to access the private key (which is needed for authentication here).
Try this:
Create a Microsoft Management Console (MMC) with the Certificates
snap-in that targets the Local Machine certificate store
Expand the MMC and select Manage Private Keys.
On the Security tab, add the account you're running with, with Read
access.

The KeySet does not exist usually happens when the user you are trying to read the certificate as does not have access to the private keys of the cert. Can you double check your ACLing on the certs?

Related

Azure.Identity.CredentialUnavailableException GetCertificate from AzureKeyVault using azure.Security.KeyVault.Certificates

I have an app which uses certificates ( Uploaded the cert) in Azure Azure KeyVault.
I am trying to use asp.net application 4.7 to connect to key vault and retrieve the application Certificate and the Secret associate with it
Previously I used Microsoft.Azure.KeyVault and KeyVaultClient in combination with GetCertificateAsync and GetSecretAsync to pull the certificate and its secret.
However I recognized that Microsoft.Azure.KeyVault is deprecated so i researched and I found That I should use Azure.Security.KeyVault.Certificates instead.
I wrote the below code
New Way:
using Azure.Security.KeyVault.Certificates;
public static X509Certificate2 GetCertificateFromVault(string keyVaultName, string certificateName)
{
var keyVaultUri = $"https://{keyVaultName}.vault.azure.net/";
var client = new CertificateClient(new Uri(keyVaultUri), new DefaultAzureCredential());
KeyVaultCertificateWithPolicy keyVaultCertificateWithPolicy = client.GetCertificate(certificateName);
return new X509Certificate2(keyVaultCertificateWithPolicy.Cer);
}
However I get error on calling client.GetCertificate(certificateName); in above code which is my new way
Here is the error
Multiple exceptions were encountered while attempting to authenticate. ---> Azure.Identity.CredentialUnavailableException: E
nvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information.
https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage)\r\n at
Azure.Identity.EnvironmentCredential.d__12.MoveNext()\r\n
I have KeyVaultCertificateOfficer role and I can retrieve the certificates using my old way on the local machine so I am sure I do not have access issue.
I looked at developer guide it says that I need to create
environment variables for AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID
Is that the solution? I do not understand why? Do I need to do this on all my different environment like UAT and PROD and create these variables. I kind of dont like that so i think i missing something here.
If I absolutely need to create env variables also not sure what to use as
AZURE_CLIENT_SECRET as I use Certificate not secret for my App. I saw AZURE_CLIENT_CERTIFICATE_PATH but that is the path to pfx in local machine right which we do not want that.
Maybe my understanding is totally wrong I am not sure. So any guidance would be much appreciated!
Create a key Vault and certificate in azure
And we have chosen the same .Net4.7 Framework
Used the NuGet package "Azure.Security.KeyVault.Certificates
The below namspaces are used in the application
using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
using System.Security.Cryptography.X509Certificates;
Below is the code used for fetching the certificates from azure
string certificateName = "TestCertificate";
var KeyVaultUri = #"https://KeyVaultName.vault.azure.net/";
var client = new CertificateClient(new Uri(KeyVaultUri), new DefaultAzureCredential());
KeyVaultCertificateWithPolicy keyVaultCertificateWithPolicy = client.GetCertificate(certificateName);
var res= new X509Certificate2(keyVaultCertificateWithPolicy.Cer);
Certificate details are fetched in below screens

Intermittent error accessing Azure key vault - Keyset does not exists

I am using Azure Key Vault in my MVC web application. I connect to the Key Vault using certificate. Below is my sample code
AssertionCert = GetCertificate(WebConfigurationManager.AppSettings[KeyVaultConstant.ApplicationID], WebConfigurationManager.AppSettings[KeyVaultConstant.CertificateThumbprint], false);
var keyClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback((authority, resource, scope) => GetToken(authority, resource, scope, AssertionCert)));
var secrets = keyClient.GetSecretsAsync(WebConfigurationManager.AppSettings["VaultUri"]).GetAwaiter().GetResult();
On some instances I get an error stating
Cryptographic Exception: Keyset does not exists
On research I found that I have to give IIS_IUser permission to the folder where primary key is stored. I did that, Yet once in a while I get this error. This does NOT happen everytime.
You are right about the permission issue . Here are the troubleshooting steps for the same:
Troubleshooting Steps:
First check the service account which is running CRM App pool or ADFS App pool
Now open certificate manager, in personal store, locate your certificate. Right click on the certificate and select "Managed Private Keys" option
In the permission window, check if your app pool service account is given appropriate permission (Read permission should be fine, otherwise you can give Full control)
In below screenshot I have given full permission on my wildcard certificate *.test.local to my App Pool account – "test\AppPoolSvc"
Once the permission is given, perform an IISRESET and try accessing.
For further reference , please check. Also please try to restart the machine to see if it works.

Azure web app sporadically throws CryptographicException: Keyset does not exist

I have a Identity Server web app hosted on Azure. It has a .pfx file in it's root directory for signing. The problem is that when newly published it works perfectly fine but after some time it starts throwing CryptographicException: Keyset does not exist.
Based on CryptographicException KeySet does not exists I would assume that it is a file access issue, but why out of the sudden azure is messing up with file access.
I've been seing the same exception sporadically. In my case, it was caused by Data Protection keys changing when I swap between deployment slots. When using services.AddDataProtection() with the default configuration and hosting the app on Azure App Service, the data protection keys are stored in %HOME%\ASP.NET\DataProtection-keys. This directory is backed by a network share to make sure the keys are available on all your app instances, BUT this is not the case for deployment slots. So when you switch from one deployment slot to another, the keys will change and you will see CryptographicException: Keyset does not exist when your app tries to unprotect a payload.
To make sure your app is always using the same key, you need to configure a different key storage provider. I.e. use Redis or Azure Blob Storage as backing store.
You can find more information about how to configure this in the official documentation.
I've also described the issue I had on my blog.
I recommend that you do not retrieve your signing cert from disk firstly. Rather upload the certificate to the associated web app in Azure Portal.
and retrieve the certificate on application startup
something like.
X509Certificate2 Certificate = null;
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint,"CERTIFICATE_THUMBPRINT_HERE",false);
Certificate = certCollection[0];

"The credentials supplied to the package were not recognized" error when authenticating as server with certificate generated using BouncyCastle

I'm trying to create a certificate using the BouncyCastle.Crypto dll, which is then used to authenticate a SslStream as the server in a Windows Service process, which runs under the Local System account.
However when I get to the SslStream.AuthenticateAsServer(certificate) call, it throws a Win32 exception with the error message "The credentials supplied to the package were not recognized".
There are several questions on here about this error message, but none of them seem to describe, or solve, my particular problem.
In the hope that someone may be able to offer some help, I include the code I am using to create and install the certificate:
// First create a certificate using the BouncyCastle classes
BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());
AsymmetricCipherKeyPair keyPair = GenerateKeyPair();
X509V1CertificateGenerator generator = new X509V1CertificateGenerator();
generator.SetSerialNumber(serialNumber);
generator.SetIssuerDN(new X509Name("CN=My Issuer"));
generator.SetNotBefore(DateTime.Today);
generator.SetNotAfter(DateTime.Today.AddYears(100));
generator.SetSubjectDN(new X509Name("CN=My Issuer"));
generator.SetPublicKey(keyPair.Public);
generator.SetSignatureAlgorithm("SHA1WITHRSA");
Org.BouncyCastle.X509.X509Certificate cert = generator.Generate(
keyPair.Private, SecureRandom.GetInstance("SHA1PRNG"));
// Ok, now we have a BouncyCastle certificate, we need to convert it to the
// System.Security.Cryptography class, by writing it out to disk and reloading
X509Certificate2 dotNetCert;
string tempStorePassword = "Password01"; // In real life I'd use a random password
FileInfo tempStoreFile = new FileInfo(Path.GetTempFileName());
try
{
Pkcs12Store newStore = new Pkcs12Store();
X509CertificateEntry entry = new X509CertificateEntry(cert);
newStore.SetCertificateEntry(Environment.MachineName, entry);
newStore.SetKeyEntry(
Environment.MachineName,
new AsymmetricKeyEntry(keyPair.Private),
new [] { entry });
using (FileStream s = tempStoreFile.Create())
{
newStore.Save(s,
tempStorePassword.ToCharArray(),
new SecureRandom(new CryptoApiRandomGenerator()));
}
// Reload the certificate from disk
dotNetCert = new X509Certificate2(tempStoreFile.FullName, tempStorePassword);
}
finally
{
tempStoreFile.Delete();
}
// Now install it into the required certificate stores
X509Store targetStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
targetStore.Open(OpenFlags.ReadWrite);
targetStore.Add(dotNetCert);
targetStore.Close();
Ok, now I have created and installed the certificate. I then configure my Windows Service to use this certificate by supplying it with the generated certificate's thumbprint. I then use the certificate like this:
// First load the certificate
X509Certificate2 certificate = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 certInStore in store.Certificates)
{
if (certInStore.Thumbprint == "...value not shown...")
{
certificate = certInStore;
break;
}
}
SslStream sslStream = new SslStream(new NetworkStream(socket, false), false);
// Now this line throws a Win32Exception
// "The credentials supplied to the package were not recognized"
sslStream.AuthenticateAsServer(certificate);
Does anyone have any idea what the problem could be here?
I don't get the problem if I install a certificate created with 'makecert', but that isn't suitable for production certificates.
I've also tried creating a separate x509v1 CA certificate and then x509v3 certificate for server authentication, but I get the same error, so I removed this in the example code for simplicity.
That particular error message rings a bell. I'll guess that either you did not store the private key with the certificate, or, the Windows service does not have access to the private key. To check this, open the Certificates MMC snap-in:
Run mmc (e.g. from the Start menu)
File menu > Add/Remove Snap-in
Select "Certificates" in left pane and then click Add
Select "Computer Account" (for LocalMachine) then click Next,
and then Finish
Navigate to the certificate and double-click in the right pane. On the General tab that comes up, you should see a little key icon at the bottom, along with the text, "You have a private key that corresponds to this certificate." If not, that's the problem. The private key was not saved.
If the private key is present, click Ok to dismiss this dialog, and then right-click on the certificate in the right pane and select on the pop-up menu: All Tasks > Manage Private Keys. In that dialog, make sure that the Windows account that the service runs under has read access to the private key. If it doesn't, that's the problem.
Edit: Oops, you wrote that the service runs as Local System, so it must be a missing private key, if it is one of these two problems. I'll leave the key access check in my answer anyway, for anybody else that hits this and is not running as Local System.
Sometime the problem happens when the application try to reach the certificate doesn't have enough privilege to access the certificate, the issue may resolve by running the application as administrator.
I've the same issue, tried everything from many posts, and google researching.
But looks like I found fix.
When I changed Identify from ApplicationPoolIdentity to LocalSystem everything start working perfectly.
May be will be helpful for someone.
For me works on Windows Server 2012 R2 (.net 4.6.1) - "All Tasks > Manage Private Keys" and set access to Everyone (setting to IS_IUSRS was not enough)
Found this solution online but I can't find the source to give the credit.
Since I ran into the "The credentials supplied to the package were not recognized" problem with AuthenticateAsClient() (for client verification), I'd like to document how I solved it. It's a different method with the same end goal. Since it might be useful for AuthenticateAsServer(), figured why not.
Here I convert a BC Certificate to a .NET certificate. Add an extra step in converting it to a .NET X509Certificate2 to store it's PrivateKey property.
Org.BouncyCastle.X509.X509Certificate bcCert;
X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(bcCert);
X509Certificate2 dotNetCert2 = new X509Certificate2(dotNetCert);
Problem showed up when adding a BouncyCastle private key to a .NET private key. The X509 certificates converted fine but not the private keys. I converted the BC private key to RSACryptoServiceProvider using the provided DotNetUtilities. Unfortunately it looks like the conversion isn't complete. So I created another RSACryptoServiceProvider which I then initialized. Then I imported the private key into the one I created.
// Apparently, using DotNetUtilities to convert the private key is a little iffy. Have to do some init up front.
RSACryptoServiceProvider tempRcsp = (RSACryptoServiceProvider)DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)ackp.Private);
RSACryptoServiceProvider rcsp = new RSACryptoServiceProvider(new CspParameters(1, "Microsoft Strong Cryptographic Provider",
new Guid().ToString(),
new CryptoKeySecurity(), null));
rcsp.ImportCspBlob(tempRcsp.ExportCspBlob(true));
dotNetCert2.PrivateKey = rcsp;
After that, I was able to save the X509Certificate2 object directly to the key store. I didn't need the actual file so I skipped that step.
Previously, every time I have run into this issue, I have had to delete the cert out of my local machine cert store and re-import it. Then it all seems happy. I can't see how it could be a global permissions issue or invalid cert if simply re-importing it fixes the issue.
How I finally fixed it was using the winhttpcertcfg tool from the Windows Resource Kit to grant permission to the specific user that was using the cert.
The syntax would be:
"C:\Program Files (x86)\Windows Resource Kits\Tools\winhttpcertcfg" -i cert.p12 -c LOCAL_MACHINE\My -a UserWhoUsesTheCert -p passwordforp12
I had the similar issue when calling a WCF REST service from .NET application where I need to attach the client certificate; All I had to do was provide access to the certificate in cert store[mmc console] to the "NETWORKSERVICE] off course my IIS Pool was default pool which indicates its using NETWORKService user account.
the mistake that I did was, I copied the cert from another store to Local
Machine -> Personnel store where the certificate was protected with password. should import the certificate explicitly in required store.
If you running from IIS, ensure that the Application Pool has 'Load User Profile' set to true.
This was the only solution for me.
I don't recall this error but the certificate you're creating is not a valid to be used for SSL/TLS, including:
v1 (not v3) certificate;
missing extensions;
invalid CN;
...
There are several RFC that talks about this, including RFC5246 on TLS (1.2).
Finally making your own certificates is not more suitable than using the ones made by makecert (but the last one can generate the minimum set to be usable for an SSL/TLS server certificate).
I strongly suggest you to buy, from a good known Certificate Authority (CA), a SSL/TLS certificate for production. That will get you a working certificate recognized by the most browsers and tools.
Another reason for this error is that you ran the application / server under an account which password has changed, breaking its capability of accessing the certificate it wants to use in the certificate store.
This especially may not be as obvious if you use a NuGet package like LettuceEncrypt which automatically stores the LetsEncrypt in your store.
Delete the certificate from your store and reimport it.

X509Certificate.CreateFromCertFile - the specified network password is not correct

I have a .NET application that I want to use as a client to call an SSL SOAP web service. I have been supplied with a valid client certificate called foo.pfx. There is a password on the certificate itself.
I've located the certificate at the following location: C:\certs\foo.pfx
To call the web service, I need to attach the client certificate. Here's the code:
public X509Certificate GetCertificateFromDisk(){
try{
string certPath = ConfigurationManager.AppSettings["MyCertPath"].ToString();
//this evaluates to "c:\\certs\\foo.pfx". So far so good.
X509Certificate myCert = X509Certificate.CreateFromCertFile(certPath);
// exception is raised here! "The specified network password is not correct"
return cert;
}
catch (Exception ex){
throw;
}
}
It sounds like the exception is around the .NET application trying to read the disk. The method CreateFromCertFile is a static method that should create a new instance of X509Certificate. The method isn't overridden, and has only one argument: the path.
When I inspect the Exception, I find this:
_COMPlusExceptionCode = -532459699
Source=mscorlib
Question: does anyone know what the cause of the exception "The specified network password is not correct" ?
Turns out that I was trying to create a certificate from the .pfx instead of the .cer file.
Lesson learned...
.cer files are an X.509 certificate in binary form. They are DER encoded.
.pfx files are container files. Also DER encoded. They contain not only certificates, but also private keys in encrypted form.
You might need to user X509Certificate2() with a parameter of X509KeyStorageFlags.MachineKeySet instead. This fixed a similar issue we had. Credit to the original website that suggested this: http://vdachev.net/2012/03/07/c-sharp-error-creating-x509certificate2-from-a-pfx-or-p12-file-in-production/
Quoting:
Cause
The cause of the problem doesn’t seem to have much to do with the
error messages. For some reason the constructor is trying to get
access to the private key store although the private key is in stored
in the file being opened. By default the user key store is used but
ASP.NET (and probably non-interactive Windows services in general) are
not allowed to open it. Chances are the user key store for the
selected account doesn’t even exist.
Solution
One thing you could try is creating a user key store by logging into
the account and importing a certificate in its Personal store (and
then remove it again).
Another solution is to pass an additional parameter to the constructor
– a flag indicating the private keys are (supposed to be) stored in
the local computer – X509KeyStorageFlags.MachineKeySet, like this: var
certificate = new X509Certificate2(fileName, password,
X509KeyStorageFlags.MachineKeySet);
For a PFX with no password, then password can be specified as string.Empty.
See also https://stackoverflow.com/a/8291956/130352
Depending on your situation you probably need to install the certificate on the server first to get the trust level up before you export the .cer file.
I had to do this for a similar project and here were my notes on how it was accomplished.
Replace the Foo.cer with an export of the certificate installed on the server. (Install the cert from the pfx file and then export it to a cer file.)
Command for IIS6 to allow IIS_WPG group access to the cert key. Need to install winhttpcertcfg (You can follow the link below to grab your own copy).
C:\Program Files\Windows Resource Kits\Tools>winhttpcertcfg -i (Path to pfx file, eg. e:\Certs\Foo.pfx) -c LOCAL_MACHINE\My -a IIS_WPG -p (Password for pfx file)
Spits out key info and grants privilege
Granting private key access for account:
(SERVERNAME)\IIS_WPG
Download WinHttpCertCfg.msi here that installs the exe.
More info on how to use the cert config can be found here.
Then it just goes back to how you are doing your cert push.
//Cert Challenge URL
Uri requestURI = new Uri("https://someurl");
//Create the Request Object
HttpWebRequest pageRequest = (HttpWebRequest)WebRequest.Create(requestURI);
//After installing the cert on the server export a client cert to the working directory as Foo.cer
string certFile = MapPath("Foo.cer");
X509Certificate cert = X509Certificate.CreateFromCertFile(certFile);
//Set the Request Object parameters
pageRequest.ContentType = "application/x-www-form-urlencoded";
pageRequest.Method = "POST";
pageRequest.AllowWriteStreamBuffering = false;
pageRequest.AllowAutoRedirect = false;
pageRequest.ClientCertificates.Add(cert);
This how I passed the cert but not sure exactly what you are needing to do with your cert so this might not be the same for you.
The 'the specified network password is not correct' error message is also returned when the certificate you are trying to import in one of the OS stores is already present in that store.
In my case I was trying to run in the Private Application mode and I got the same error.
The specified network password is not correct
The PrivateAuthenticator constructor (in Xero.Api.Example.Applications.Private) was trying to import the certificate assuming there is no password defined during the creation of the certificate.
_certificate = new X509Certificate2();
_certificate.Import(certificatePath);
Then I changed the import to use an overload method which uses the password,
_certificate.Import(certificatePath, "mypasswordusedtocreatethecertificate", X509KeyStorageFlags.MachineKeySet);
You might need to X509KeyStorageFlags.MachineKeySet.
I am using certificate from web job.
In my case changing Identity to NetworkService in Application Pool solved this problem.

Categories