Verify certificate is signed by ca bouce castle - ssl-certificate

I am using bouncecastle library to generate certificae using My CA.
I dont know how to verify certificate that was signed by My CA
I found this answer but its using java.security.cert
X509Certificate certificate =...
X509Certificate intermediate = ...
try{
certificate.verify(intermediate.getPublicKey());
//Verification ok. intermediate is the issuer
} catch (Exception e){}
}
How can I do this using bouncecastle library?

Related

Java TooTallNate Secure Websocket Server on FireTV with Lets Encrypt Certificate: Handshake / Chain Error

I am using a Java Websocket Server (TooTallNate). A Javascript App is connecting securely via a LetsEncrypt certificate. It is renewed automatically via certbot and is serving an Apache on the same machine too. On all tested browsers everything is working fine, for both https and wss.
I wanted to submit my app as a packaged FireTV app. I tested it in the "Web App Tester" app. As soon as the JS tries to connect to the WSS, it raises an SSL error, which reads in adb-logcat
I/X509util: Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
but sometimes just
E/chromium(13208): [ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -202
The relevant Java code filling the SSLContext from TooTallNate is:
private static SSLContext getContext() {
SSLContext context;
String password = "CHANGEIT";
String pathname = "pem";
try {
context = SSLContext.getInstance("TLS");
byte[] certBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "cert.pem")),"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "privkey.pem")),"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[]{cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, password.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
}
catch (Exception e) {
context = null;
}
return context;
}
It took some reading to get it to work. There are few information on this special problem, so I decided to answer myself:
It was truly a problem of the missing chain in the SSLContext. Couldn't believe that, because it worked on every other chromium based browser.
In my LetsEncrypt folder I have four files: privkey.pem (not at thing), cert.pem, chain.pem and fullchain.pem, where fullchain.pem is just the concatenation of chain.pem and cert.pem. cert.pem is our own certificate and chain.pem is the Digital Signature Trust DST Root CA X3 certificate which you can see yourself using:
cat chain.pem | openssl x509 -text
I compared the certificates served over https and wss using:
openssl s_client -connect myurl:443 | openssl x509 -text
and
openssl s_client -connect myurl:8080 | openssl x509 -text
The latter showed two error at the beginning of the output
verify error:num=20:unable to get local issuer certificate
while the https response from apache showed
depth=2 O = Digital Signature Trust Co., CN = DST Root CA X3
verify return:1
depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
verify return:1
depth=0 CN = myurl
verify return:1
Finally the working solution is a lot easier than my solutions I had meanwhile. Its not necessary to download any further chain certificates. Just load the chain.pem you already have in your LetsEncrypt folder like the cert.pem and add both as the chain to the keystore in the setKeyEntry function:
private static SSLContext getContext() {
SSLContext context;
String password = "CHANGEIT";
String pathname = "pem";
try {
context = SSLContext.getInstance("TLS");
byte[] certBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "cert.pem")),"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] chainBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "chain.pem")),"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(getBytes(new File(pathname + File.separator + "privkey.pem")),"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
X509Certificate chain = generateCertificateFromDER(chainBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[]{cert, chain});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, password.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
}
catch (Exception e) {
context = null;
}
return context;
}

How can we load Certificate Signing Request using x509certificates?

My Question:
From a Certificate Signing Request as below:
Example:
-----BEGIN CERTIFICATE REQUEST-----
MIIClDCCAXwCAQAwTzELMAkGA1UEBhMCVk4xEDAOBgNVBAMMB2RldmljZTMxCjAI ...
-----BEGIN CERTIFICATE REQUEST-----
I am using system.security.cryptography.x509certificates, I would load it as a CertificateRequest/X509Certificate2 object to create new certificate from Certificate Signing Request.
Anyone who know how to do?
My Try
Input:
self signed certificate as a CA
certificate signing request
My code
string rootCA = ""; // root certificate
string scrString = ""; // certificate signing request
byte[] rootRawData = Convert.FromBase64String(rootCA);
X509Certificate2 rootCert = new X509Certificate2(rootRawData);
var generator = X509SignatureGenerator.CreateForRSA(rootCert.GetRSAPrivateKey(), RSASignaturePadding.Pkcs1);
byte[] scrRawData = Convert.FromBase64String(scrString);
X509Certificate2 scrDeviceCert = new X509Certificate2(scrRawData); ------> ERROR: : 'Cannot find the requested object.'
CertificateRequest scrDeviceReq = new CertificateRequest(scrDeviceCert.IssuerName, scrDeviceCert.PublicKey, HashAlgorithmName.SHA256);
var deviceCert = scrDeviceReq.Create(rootCert.IssuerName, generator, DateTimeOffset.UtcNow.AddDays(1), DateTimeOffset.UtcNow.AddDays(6), new byte[] { 1, 2, 3, 4 });
There is no built-in functionality to read CSRs in .NET Core. You have to use 3rd party libraries to decode CSRs.

WebRequest with mutual authentication

Extra information at the end after comments from Crypt32 (thank you Crypt32!)
I have to send data to a server. I need mutual authentication: the server needs to be certain it is me, and I need to be certain that the server really is the server that I trust. This needs to be dons in a windows program.
To identify itself, the server will send me a certificate that is issued by certificate authorities that I trust: a root certificate and an intermediate certificate:
Root CA-G2.PEM
Intermediate CA-G2.PEM
To identify me, the organization gave me a certificate and a private key
Root CA-G3.PEM
Intermediate CA-G3.PEM
MyCertificate.CRT (= pem) and MyCertificate.Private.Key (=RSA)
I have imported all root certificates and intermediate certificates into the windows keystore.
To sent the message:
const string url = "https://...//Deliver";
HttpWebRequest webRequest = WebRequest.CreateHttp(url);
// Security:
webRequest.AuthenticationLevel=AuthenticationLevel.MutualAuthRequired;
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Should I add my certificate?
X509Certificate myCertificate = new X509Certificate("MyCertificate.CRT");
// Should I add Certificate authorities?
// only the CA-G2 authorities, so my WebRequest can trust the certificate
// that will be sent by the Server?
// or Should I also add the CA-G3 who issued MyCertificate
// and what about MyCertificate.Private.Key, the RSA file?
// Fill the rest of the WebRequest:
webRequest.Method = "Post";
webRequest.Accept = "text/xml";
webRequest.Headers.Add("SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
... etc
// do the call and display the result
using (WebResponse response = webRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string soapResult = reader.ReadToEnd();
Console.WriteLine(soapResult);
}
}
The WebResponse doesn't indicate any error. The returned data is an empty (non-null) string. Yet:
response.StatusCode == NoContent (204)
soapResult == String.Empty
response.IsMutuallyAuthenticated == false
The NoContent and the empty data result are expected. Does the false IsMutuallyAuthenticated indicate that something is wrong with my authentication?
Added information
Crypt32 suggested I should convert MyCertificate.CRT and MyCertificate.Private.Key into one PFX (or P12) file.
For this I use openssl.
I concatenated the CA-G3 files into one TrustG3.Pem and created the P12 file:
openssl.exe pkcs12 -export -name "<some friendly name>"
-certfile TrustG3.Pem
-in MyCertificate.CRT
-inkey MyCertificate.Private.Key
-out MyCertificate.P12
After providing a password a proper Pkcs12 file (PFX) was created. The source code changes slightly:
HttpWebRequest webRequest = WebRequest.CreateHttp(url);
// Security:
webRequest.AuthenticationLevel=AuthenticationLevel.MutualAuthRequired;
webRequest.Credentials = CredentialCache.DefaultCredentials;
var p12Certificate = new X509Certificate("MyCertificate.P12", "my password");
webRequest.ClientCertificates.Add(p12Certificate);
Alas, this didn't help. The webResponse still says:
response.IsMutuallyAuthenticated == false
Does the false IsMutuallyAuthenticated indicate that something is wrong with my authentication?
yes, it does. Because you add only public part of client certificate. There is no associated private key specified. Either, use certificate from certificate store (assuming, cert store contains private key) or import certificate from PFX.
Update:
now your client authentication code looks correct. Next step is to check if your client certificate is trusted by server.

Bouncy Castle c#, how to generate pfx file with full certification path

I have an issue with generation pfx file with full certificate chain which is correctly read as X509Certificate2 object in .net core for authentication. I tried various approaches but with no luck.
I have a chain generated by OpenSSL and I use last certificate and private key to generate user certificates for authentication.
Finally, I have PEM files with certs (each cert from a chain in a separate file)
-----BEGIN CERTIFICATE-----
MIIFR[....]Aerk=
-----END CERTIFICATE-----
etc.
In webapi controller I have
X509Certificate2 clientCertificate =
this.Request.HttpContext.Connection.ClientCertificate;
X509Chain x509Chain = new X509Chain(){ ChainPolicy = new
X509ChainPolicy({...}};
x509Chain.Build(clientCertificate))
var elements = x509Chain.ChainElements.Cast<X509ChainElement>()
// in elements variable I expect to have more than one item but I don't have
How can I generate pfx in Bouncy Castle in the correct way to achieve it?
Below some code snippet for pfx file creation which generates pfx but is read as X509Certificate2 with only one chain element. How to modify it to have all of them available?
Pkcs12Store store = new Pkcs12Store();
X509CertificateEntry[] chain = new X509CertificateEntry[5];
X509Certificate cert1 = certParser.ReadCertificate(new
MemoryStream(Encoding.UTF8.GetBytes(certString1)));
X509CertificateEntry certificateEntry1 = new X509CertificateEntry(cert1);
chain[0] = certificateEntry1;
// I adds all certs in order from user cert to root one (self signed)
store.SetKeyEntry(csr.GetCertificationRequestInfo().Subject.ToString(), new
AsymmetricKeyEntry(key.Private), chain);
using (var filestream = new FileStream("./full.cert.pfx"), FileMode.Create,
FileAccess.ReadWrite)){
store.Save(filestream, "".ToCharArray(), new SecureRandom());
}

FtpWebRequest EnableSSL error

I'm getting a "The remote certificate is invalid according to the validation procedure" exception message with the following code:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(MyCertValidationCb);
var request = (FtpWebRequest)WebRequest.Create(new Uri(myUri));
request.EnableSsl = true;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.BeginGetRequestStream(EndGetStreamCallback, _state);
public static bool MyCertValidationCb(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors)
== SslPolicyErrors.RemoteCertificateChainErrors)
{
return false;
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch)
== SslPolicyErrors.RemoteCertificateNameMismatch)
{
Zone z;
z = Zone.CreateFromUrl(((FtpWebRequest)sender).RequestUri.ToString());
if (z.SecurityZone == SecurityZone.Intranet
|| z.SecurityZone == SecurityZone.MyComputer)
{
return true;
}
return false;
}
return false;
}
The ftp server is filezilla. FTP over SSL is enabled, and Allow explicit FTP over TLS is also enabled. I've generated a certificate.crt file. Connected to the ftp location using filezilla client, and checked "Always trust this certificate" in the popup window.
In the MyCertValidationCb method, (sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors is always true.
If I change MyCertValidationCb to always return true, the ftp request goes through without a problem. I'm sure it's an issue with certificates. Anyone have any ideas?
The RemoteCertificateChainErrors was a result of not having the certificate in the Trusted Root Certification Authorities certificate store.
Filezilla generates a self signed certificate with the following format:
-----BEGIN RSA PRIVATE KEY-----
//hash
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
//hash
-----END CERTIFICATE-----
In order to import the certificate, remove the private key section and save the new file. Install that into the Trusted Root Certification Authorities certificate store.
Now the issue I'm having is RemoteCertificateNameMismatch, I'll post that in another topic.