I'm trying to deploy a certificate into a windows-my store in order to use it for SSL in IIS6.0.
When the application is running I don't see any errors in SSLDiag output and everything works perfectly, but once I close the application SSLDiag shows an error:
#WARNING: You have a private key that corresponds to this certificate
but CryptAcquireCertificatePrivateKey failed
I checked the machine keyset and noticed that after I close my application it removes the file with a key which was created. Here is the location I checked:
C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
How can I preserve the create key file in a machine keyset?
Here is the code I'm using:
using(var openFileDialog = new OpenFileDialog())
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var password = "password";
var certificate = new X509Certificate2(openFileDialog.FileName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var keystore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
keystore.Open(OpenFlags.MaxAllowed);
keystore.Add(certificate);
keystore.Close();
}
}
I tried different variations of X509KeyStorageFlags, but the file is still removed from machine keyset once I close the app. Why the file is removed and how can I prevent it?
I found the solution:
certificate.PrivateKey.PersistKeyInCsp = true;
This lets the private key to remain in the machine key set.
I suppose the key was removed when the X509Certificate2 object was freeing its resources.
Related
Just as this person, I've been struggling a bit with browsers caching SSL sessions. In short, if a client certificate is selected, there is no way to clear the state programmatically, except in IE using document.execCommand("ClearAuthenticationCache").
One of the answers mentions that making a request to "a URL on the same hostname that requires a client certificate but rejects all certificates" it would force the browser to clear the SSL session. How can I set up such an endpoint in IIS? Because I presume I need more than just a simple endpoint returning http status 403 or similar.
The SSL negotiation happens before the endpoint request is sent, so there is no way of "rejecting a certificate" based on the endpoint (you can perhaps force renegotiation, but I'm not sure IIS supports it).
But you can maybe set up the same hostname and a different port and disable client certificates there. Since the hostname matches (being the same...), I'd expect the browser to try them, and fail.
Short Answer: delete sslcert [ipport=]IP Address:port ref
If you want to script/automate it in code, you could do it in C# in two steps below, you would need to adapt the code to suit your needs
1. Get your certs
using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
// Get /Display a list of all the certificates
foreach (var x in store.Certificates)
{
// *** TODO
// add it to a drop down
// SomeDropDownListControl_IISCert.Items.Add(new SomeDropDownListControl_IISCert(x.FriendlyName, x.SerialNumber));
//or delete it, see Below
}
}
2. Build the command and pass the cert and delete it with the Shell Command
StringBuilder str = new StringBuilder();
ProcessStartInfo psi = new ProcessStartInfo() {CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true};
psi.FileName = "netsh";
psi.Arguments = $"http show sslcert ipport=0.0.0.0:{port}";
Process procShow = Process.Start(psi);
while (procShow != null && !procShow.StandardOutput.EndOfStream)
{
str.Append(procShow.StandardOutput.ReadLine());
}
Log.Warn(str.ToString);
// delete IPV4.
psi.Arguments = $"http delete sslcert ipport=0.0.0.0:{port}";
Process procDel = Process.Start(psi);
//exitCode = procDel.ExitCode;
I was not able to make http client code in .net 5 to send both intermediate and leaf certificates (in 3 certificate hierarchy) to the server. However I was able to send the leaf certificate from client to the server successfully. Here is my setup:
I have 3 certificates on my windows box:
TestRoot.pem
TestIntermediate.pem
TestLeaf.pem (without private key for server - windows box)
TestLeaf.pfx (with private key for client - windows box)
The none of the above certificates were NOT added to windows certificate manager as I would like to be able to run the same code on non-windows machines eventually. For my testing, I am running following client and server code on the same windows box.
On my windows box, I have following simple client side code using .net 5:
HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
X509Certificate2 leafCert = new X509Certificate2(File.ReadAllBytes(#"C:\Temp\TestLeaf.pfx"), "<password>");
handler.ClientCertificates.Add(leafCert);
HttpClient httpClient = new HttpClient(handler);
StringContent content = new StringContent("{}"); //Test json string
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(MediaTypeNames.Application.Json);
//With local.TestServer.com resolving to localhost in the host file
HttpResponseMessage response = httpClient.PostAsync("https://local.TestServer.com/...", content).Result;
if (response.IsSuccessStatusCode)
{
var responseString = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseString);
}
else
{
Console.WriteLine(x.StatusCode);
Console.WriteLine(x.ReasonPhrase);
}
On same window box, I have following example snippet of server side code using kestrel in .net 5:
services.Configure<KestrelServerOptions>(options =>
{
// Keep track of what certs belong to each port
var certsGroupedByPort = ...;
var certsPerDistinctSslPortMap = ...;
// Listen to each distinct ssl port a cert specifies
foreach (var certsPerDistinctSslPort in certsPerDistinctSslPortMap)
{
options.Listen(IPAddress.Any, certsPerDistinctSslPort.Key, listenOptions =>
{
var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions();
httpsConnectionAdapterOptions.ClientCertificateValidation = (clientCertificate, chain, sslPolicyErrors) =>
{
bool trusted = false;
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
{
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
X509Certificate2 certRoot = new X509Certificate2(#"C:\Temp\TestRoot.pem");
X509Certificate2 certIntermdiate = new X509Certificate2(#"C:\Temp\TestIntermediate.pem");
chain.ChainPolicy.CustomTrustStore.Add(certRoot);
chain.ChainPolicy.ExtraStore.Add(certIntermdiate);
trusted = chain.Build(clientCertificate);
}
return trusted;
};
httpsConnectionAdapterOptions.ServerCertificateSelector = (connectionContext, sniName) =>
{
var defaultCert = //Get default cert
return defaultCert;
};
httpsConnectionAdapterOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsConnectionAdapterOptions.SslProtocols = SslProtocols.Tls12;
listenOptions.UseHttps(httpsConnectionAdapterOptions);
});
}
options.Listen(IPAddress.Any, listeningPort);
});
The above code works as expected because the client code sends the leaf certificate to the server and the server code has access to both intermediate as well as root certificates. The server code can successfully rebuild the certificate hierarchy with received leaf certificate and its configured intermediate and root certs for the leaf certificate.
My following attempt to send the intermediate certificate (along with leaf certificate) to the server (so that it can only use the root certificate and incoming leaf and intermediate certificates in the request to build the certificate hierarchy) failed.
Tried to add the intermediate certificate by doing following in my client code:
X509Certificate2 leafCert = new X509Certificate2(File.ReadAllBytes(#"C:\Temp\TestLeaf.pfx"), "");
X509Certificate2(Convert.FromBase64String(File.ReadAllText(#"C:\Temp\TestIntermediate.pem"));
handler.ClientCertificates.Add(leafCert);
handler.ClientCertificates.Add(intermediateCert);
This did not send the intermediate certificate to the server. I verified this with the code block for httpsConnectionAdapterOptions.ClientCertificateValidation on the server side.
Question:
Is there a way to ensure that intermediate certificate is sent by the client (in addition to the leaf cert) to the server?
Vaultsharp is not able to authenticate with vault for TLS AUTH method
C# code on windows 10, cert and key in personal store
environment windows
X509Certificate2 clientCertificate = null;
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificateList =
store.Certificates.Find(X509FindType.FindBySubjectName, "subject name", false);
if (certificateList.Count > 0)
{
clientCertificate = certificateList[0];
};
store.Close();
// got clientCertificate here, it has private key as well
try
{
IAuthMethodInfo authMethod = new CertAuthMethodInfo(clientCertificate);
var vaultClientSettings = new VaultClientSettings("endpoint:8200", authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
Secret<Dictionary<string, object>> secret = null;
Task.Run(async () =>
{
secret = await vaultClient.V1.Secrets.KeyValue.V1.ReadSecretAsync("dummy_app/dev/connection_strings");
}).GetAwaiter().GetResult();
Above code is throwing error
{"errors":["client certificate must be supplied"]}
It should return the secret instead of throwing exception
Please check the following.
That the certificate really has a private key. (HasPrivateKey check on the object) Typically you read a private key from a store using a passphrase. I don't see that above, so it maybe that what you have is a public key.
Please ensure that the certificate is a valid cert with the full chain. The Vault API (not VaultSharp) throws an error if it cannot find the parent chain.
Please inspect the http or tcp connection to see if the cert is truly attached.
Here's the code I'm using to fetch:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
var fetchOpts = new FetchOptions {Credentials = creds};
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
but it fails during fetch with the following exception:
LibGit2Sharp.LibGit2SharpException: Too many redirects or authentication replays
Result StackTrace:
at LibGit2Sharp.Core.Ensure.HandleError(Int32 result)
at LibGit2Sharp.Core.Proxy.git_remote_fetch(RemoteSafeHandle remote, Signature signature, String logMessage)
at LibGit2Sharp.Network.DoFetch(RemoteSafeHandle remoteHandle, FetchOptions options, Signature signature, String logMessage)
at LibGit2Sharp.Network.Fetch(Remote remote, FetchOptions options, Signature signature, String logMessage)
I have verified that the config file has the required remote name and that git fetch works from the command line. I found that the exception originates from libgit2\src\transport\winhttp.c but I couldn't come up with a workaround/solution.
I tried #Carlos' suggestion in the following way:
public static void GitFetch()
{
var creds = new UsernamePasswordCredentials()
{Username = "user",
Password = "pass"};
CredentialsHandler credHandler = (_url, _user, _cred) => creds;
var fetchOpts = new FetchOptions { CredentialsProvider = credHandler };
using (repo = new Repository(#"C:\project");)
{
repo.Network.Fetch(repo.Network.Remotes["origin"], fetchOpts);
}
}
I could fetch from public repos on github as well as from password protected private repos on bitbucket; however, I couldn't do the same for the repositories hosted over LAN at work. Turns out they were configured in a way which does not accept UsernamePasswordCredentials provided by libgit2sharp. The following modification allowed me to fetch from repositories over LAN:
CredentialsHandler credHandler = (_url, _user, _cred) => new DefaultCredentials();
(I'm trying to find out what is the exact difference between the two; if I get further insight into it, I'll update the answer.)
The shim that should make the Credentials option work is currently buggy (and is deprecated anyway), pass a CredentialsProvider instead as a callback.
This seems to be a very common error message.
We were getting it on pushes to GitHub, because credentials were disabled for security:
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
We've solved it by enabling SAML SSO and doing the push outside the C# code, but perhaps using SSH keys somehow with the library or personal access tokens fixes the problem too.
I'm trying to migrate an existing application to Mono (v2.10.2).
Therefore I created a test WCF service with BasicHttpBinding and message security. The client works perfectly with .NET, but when running with Mono it fails.
The client factory is instantiated as follows:
//var certificate = CertificateUtil.GetCertificate(StoreLocation.LocalMachine,
// StoreName.My, X509FindType.FindBySubjectDistinguishedName, CertName, true);
var certificate = new X509Certificate2("certificate.pfx", "password");
var binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Message;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
var epa = new EndpointAddress(
new Uri("http://localhost:53076/Service1.svc"),
new X509CertificateEndpointIdentity(certificate));
var factory = new ChannelFactory<IService1>(binding, epa);
factory.Credentials.ServiceCertificate.DefaultCertificate = certificate;
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
factory.Credentials.ClientCertificate.Certificate = certificate;
var client = factory.CreateChannel();
In Mono the application fails within CreateChannel throwing the exception:
System.InvalidOperationException: The binding does not support any of the channel types that the contract 'IService1' allows.
I debugged into the Mono source code and found out that the problem is that AsymmetricSecurityBindingElement.InitiatorTokenParameter == null.
I'm new to Mono, maybe you could point me to a documentation/tutorial which covers this topic.
UPDATE:
With the aid of konrad.kruczynski the certificate object has a private key now. The exception is still the same. So this is not a certificate store issue.
Yes, certificates created on Windows usually does not contain private key. They can be found in some kind of cache. You should be able to create certificate with private key using this instruction. X509Certificate2 should consume the file without problems. You can also try procedure described here. In case of any problems just write.
It is also worth adding, that certificates created such way on Linux works perfectly on Windows too.
Update:
I'm not sure whether I understood your comment correctly. You can load PFX certificate using code like that:
var myCert = new X509Certificate2("filename.pfx", "password");
Given certficate contained key, it worked for me.