Curl allows making 2-way SSL requests by specifying the certificate and private key files like the two curl requests below
First get an access token:
$ curl https://connect2.server.com/auth/token
-H "Authorization: Basic $BASIC_AUTH"
--cert ~/certs/certpath/fullchain.pem
--key ~/certs/certpath/privkey.pem
Then use the token to access the API:
$ curl https://connect2.server.com/api/public/preview1/orgs/$ORGUUID/API
-H "Authorization: Bearer $ACCESS_TOKEN"
--cert ~/certs/certpath/fullchain.pem
--key ~/certs/certpath/privkey.pem
Question:
How to implement the above requests in Java? What libraries are required? Java seems to use p12 file, however, we have .pem files.
1. You can convert PEM privatekey plus chain to a PKCS12 file using openssl pkcs12 -export. That is not programming or development and no longer ontopic here, but there are dozens of Qs about this here going back many years when topicality was broader, as well as in other Stacks (security.SX, serverfault, superuser, maybe more).
2. If you don't have or dislike OpenSSL, you can read those files (among others) into any kind of Java keystore (JCEKS, JKS, PKCS12, and several BouncyCastle variants you probably don't want) using the software from https://www.keystore-explorer.org . That's also offtopic, and I've seen some existing Qs mention it but not many.
3. If you want to do this with your own code, which is ontopic, and assuming your curl uses OpenSSL or at least those files are OpenSSL formats:
3.0 Java can read PEM cert sequence with CertificateFactory.getInstance("X.509") then generateCertificates(InputStream) (note s) -- the doc is a bit sketchy but this method actually can handle separate certs as DER or PEM (which you apparently have), or PKCS7 containing certs as a single blob (commonly called p7b or p7c) ditto.
3.1 if that privkey file is PKCS8-unencrypted, i.e. if the PEM labels are BEGIN/END PRIVATE KEY with no other word between, that case can be handled by standard Java, assuming you know what algorithm it is for (which if necessary you can determine from the first=leaf certificate). Delete the BEGIN/END lines and decode the rest from base64 to binary either ignoring linebreaks (with Base64.getMimeDecoder()) or with .getDecoder() after deleting the linebreaks. Put the result in PKCS8EncodedKeySpec and feed it to generatePrivate in a KeyFactory instance for the correct algorithm.
3.2 BouncyCastle (bcpkix+bcprov) can read all the PEM formats for privatekey used by OpenSSL with PEMParser and JcaPEMKeyConverter and if applicable a DecryptorBuilder. There are many existing Qs on this that you can find with that fairly-unique classname. This does mean a dependency on Bouncy.
3.3 if you don't have or don't want Bouncy and have a format other than PKCS8-unencrypted, life gets harder. You could avoid this by using OpenSSL to convert the privkey file to PKCS8-unencrypted putting you back in #3.1, but if you do that you might as well go way back to #1 and use OpenSSL to convert the lot to PKCS12 in one foop.
if you have an OpenSSL 'traditional' algorithm-specific format like BEGIN/END RSA PRIVATE KEY or BEGIN/END EC PRIVATE KEY, and the first two lines after BEGIN are NOT Proc-type: 4 and DEK-info, you can base64-decode the body and convert it to PKCS8 by adding a (DER) prefix in front that specifies the algorithm and 'wraps' the algorithm-specific part. I think there are dupes for this but I can't presently find any; if this case applies and you identify the algorithm I'll add it.
if you have a 'traditional' format that does have Proc-type: 4 and DEK-info, or you have BEGIN/END ENCRYPTED PRIVATE KEY, those are encrypted. Making sense of them with only standard Java is a fair bit of work which I'll do only if you can't use the other options and specify exactly what case you have.
Following are the steps & code to add SSL certificates into HTTP Post request.
STEP 1. CONVERT PEM CERTIFICATE TO P12 FORMAT
openssl pkcs12 -export -out cacert.p12 -inkey /etc/letsencrypt/archive/server/privkey21.pem -in /etc/letsencrypt/archive/server/cert21.pem -certfile /etc/letsencrypt/archive/server/chain21.pem -passin pass:PWD -passout pass:PWD
STEP 2. (OPTIONAL NOT REQUIRED) CONVERT CERTIFICATE P12 TO JKS FORMAT
keytool -importkeystore -srckeystore cacert.p12 -srcstoretype pkcs12 -destkeystore cacert.jks
STEP 3. ADD CERTIFICATE TO HTTP POST REQUEST THROUGH SSLSocketFactory
/**
* This function is responsible to create createSSLSocketFactory with SSL certificate
* #return
*/
public static SSLSocketFactory createSSLSocketFactory(){
try
{
FileInputStream f5 = new FileInputStream(new File("/etc/letsencrypt/archive/server/cacert21.p12"));
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore ks1 = KeyStore.getInstance(KeyStore.getDefaultType());
ks1.load(f5, "PWD".toCharArray());
kmf.init(ks1, "PWD".toCharArray());
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(kmf.getKeyManagers(), null, null);
f5.close();
return sslContext.getSocketFactory();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
I have an application server running some utility commands, which is programmed in C.
I have to connect to the server through Java client program using Java SSL socket with
client authentication.
The key on the server side was created using:
openssl req -new -text -out ser.req
openssl rsa -in privkey.pem -out ser.key
openssl req -x509 -in ser.req -text -key ser.key -out ser.crt
I have been provided the server key and certificate. I have combined the key and certificate
into a PKCS12 format file:
openssl pkcs12 -inkey ser.key -in ser.crt -export -out ser.pkcs12
Then loading the resulting PKCS12 file into a JSSE keystore with keytool:
keytool -importkeystore -srckeystore ser.pkcs12 -srcstoretype PKCS12 -destkeystore ser.keystore
But when I try to connect, I get the following error:
javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alert.createSSLException(Alert.java:131)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:324)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:267)
at sun.security.ssl.TransportContext.fatal(TransportContext.java:262)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:654)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:473)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:369)
at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:377)
at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444)
at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:422)
at sun.security.ssl.TransportContext.dispatch(TransportContext.java:182)
at sun.security.ssl.SSLTransport.decode(SSLTransport.java:149)
at sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1143)
at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1054)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:394)
at SSLSocketClient.main(SSLSocketClient.java:67)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:456)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:323)
at sun.security.validator.Validator.validate(Validator.java:271)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:315)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:223)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129)
at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638)
... 11 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:451)
... 17 more
On the server side log:
SSL open_server: could not accept SSL connection: sslv3 alert certificate unknown
Running command:
java -Djavax.net.ssl.keyStore=/path/to/ser.keystore -Djavax.net.ssl.keyStorePassword=passwd SSLSocketClient <server-ip> <port>
Does anyone know the cause of this problem?
Updated the client source code:
import java.net.*;
import java.io.*;
import javax.net.ssl.*;
import java.security.cert.CertificateFactory;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.net.SocketFactory;
public class SSLSocketClient {
public static void main(String [] args) throws Exception {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
SSLSocketFactory sf =
(SSLSocketFactory)SSLSocketFactory.getDefault();
Socket client = new Socket(serverName, port);
System.out.println("Connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(outToServer));
writeData(out);
out.flush();
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
readData(in);
outToServer = client.getOutputStream();
out = new DataOutputStream(new BufferedOutputStream(outToServer));
writeData2(out);
out.flush();
Socket newClient = sf.createSocket(client, serverName, port, false);
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeData(DataOutputStream out) throws IOException {
char CMD_CHAR_U = 'U';
byte b = (byte) (0x00ff & CMD_CHAR_U);
out.writeByte(b); // <U>
}
private static void writeData2(DataOutputStream out) throws IOException {
char CMD_CHAR_S = 'S';
byte b = (byte) (0x00ff & CMD_CHAR_S);
out.writeByte(b); // <S>
}
private static void readData(DataInputStream in) throws IOException {
char sChar = (char) in.readByte();
System.out.println("<S>\t\t" + sChar);
}
}
Now creating the truststore as shown in the link:
https://jdbc.postgresql.org/documentation/head/ssl-client.html
Steps to create:
openssl x509 -in server.crt -out server.crt.der -outform der
keytool -keystore mystore -alias clientstore -import -file server.crt.der
java -Djavax.net.ssl.trustStore=mystore -Djavax.net.ssl.trustStorePassword=mypassword com.mycompany.MyApp
Note - The server side is using TLSv1 protocol
But still not able to make it through. What am I doing wrong?
What I want is the server to authenticate the crt of the client.
The login protocol with server; the SSL we use is only to authenticate
not to secure the transmission:
-------------------------------------------------------------
client server
-------------------------------------------------------------
sock = connect() sock = accept()
<U><LOGIN_SSL=501>
--------------------------------->
'S'|'E'
<---------------------------------
'S'
--------------------------------->
SSL_connect(sock) SSL_accept(sock)
<R><LOGIN_SSL>
<---------------------------------
I think you have several problems with your setup.
To configure properly the SSL connection with JSSE you need several things depending if you need to authenticate the server, the client, or to perform mutual authentication.
Let's suppose the later and more complete use case of mutual authentication.
The objective is to configure a SSLSocketFactory that you can use to contact your server.
To configure a SSLSocketFactory, you need a SSLContext.
This element in turn with require at least two elements for the mutual authentication use case, a KeyManagerFactory, required for client side SSL authentication, i.e., the server to trust the client, and TrustManagerFactory, required for configuring the client to trust the server.
Both KeyManagerFactory and TrustManagerFactory require a properly configured keystore with the necessary cryptographic material.
So, the first step will consist on generating this cryptographic material.
You already created a keystore with the server certificate:
keytool -keystore serverpublic.keystore -alias clientstore -import -file server.crt.der -storepass yourserverpublickeystorepassword
Please, be aware that, in a similar way as in the server case, you also need to create a public and private key pair for your client, of course, different than the server one.
The related code you provided with OpenSSL and keytool looks appropriate. Please, repeat the process for the client side:
openssl req -new -text -out client.csr
openssl rsa -in clientpriv.pem -out client.key
openssl req -x509 -in client.csr -text -key client.key -out client.crt
// You can use PKCS12 also with Java but it is also ok on this way
openssl pkcs12 -inkey client.key -in client.crt -export -out client.pkcs12
// Do not bother yourself and, in this use case, use always the same password for the key and keystore
keytool -importkeystore -srckeystore client.pkcs12 -srcstoretype PKCS12 -destkeystore client.keystore -storepass "yourclientkeystorepassword"
With the right keystores in place, try something like the following to interact with your server:
// First, let's configure the SSL for client authentication
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
clientKeyStore.load(
new FileInputStream("/path/to/client.keystore"),
"yourclientkeystorepassword".toCharArray()
);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // SunX509
kmf.init(clientKeyStore, "yourclientkeystorepassword".toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
// Now, let's configure the client to trust the server
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
serverKeyStore.load(
new FileInputStream("/path/to/serverpublic.keystore"),
"yourserverpublickeystorepassword".toCharArray()
);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // SunX509
tmf.init(serverKeyStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null); // You can provide SecureRandom also if you wish
// Create the SSL socket factory and establish the connection
SSLSocketFactory sf = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket)sf.createSocket(serverName, port);
// Interact with your server. Place your code here
// Please, consider the following link for alternatives approaches on how to
// interchange information with the server:
// https://web.mit.edu/java_v1.5.0_22/distrib/share/docs/guide/security/jsse/samples/sockets/client/SSLSocketClient.java
// It also suggest the use of startHandshake explicitly if your are using PrintWriter for the reason explained in the example an in the docs:
// https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/net/ssl/SSLSocket.html
//...
// Close the socket
socket.close();
The described approach can be extended to use, instead of sockets, higher level of abstraction components like HttpsURLConnection and HTTP clients - with the exception of Apache HttpClient that handles SSL differently - like OkHttp which, under the hood, use SSLSocketFactory and related stuff.
Please, also consider review this great article from IBM's DeveloperWorks, in addition to explain many of the point aforementioned will provide you great guidance with the generation of keystores for your client an server if necessary.
Please, also be aware that, depending on your server code, you may need to configure it to trust the provided client certificate.
According to your comments you are using a server side code similar to the one provided by Postgresql 8.1. Please, see the relevant documentation for configuring SSL in that database, if you are using some similar server side code it maybe could be of help.
Probably the best approach will be to generate a client certificate derived from the root certificate trusted by your server instead of using a self signed one.
I think that it will be also relevant for your server side SSL certificate an associated private key: first, create a root self signed certificate, your CA certificate, configure your server side C code to trust it, and then derive both client and server side SSL cryptographic material from that CA: probably it will simplify your setup and make everything work properly.
I would like to implement a ssl connection which the RSA key pair are kept in the Hardware Security Module (HSM) in Java.
By using openssl pkcs11 engine, I achieved the TLS connection with the following engine configuration.
[openssl_def]
engines = engine_section
[engine_section]
pkcs11 = pkcs11_section
[pkcs11_section]
engine_id = pkcs11
MODULE_PATH = /home/ubuntu/Desktop/vendorlib.so
PIN = "123456"
init = 0
[req]
distinguished_name = test_name
[req_distinguished_name]
and then I create a certificate using this engine with the following command where ssl_key is kept in HSM device.
OPENSSL_CONF=engine.conf openssl req -new -x509 -days 365 -subj '/CN=test/' -sha256 -config engine.conf -engine pkcs11 -keyform engine -key slot_2-label_ssl_key -out cert.pem
I can confirm the certificate and key pair with the following openssl server and client commands.
For the server:
OPENSSL_CONF=engine.conf openssl s_server -engine pkcs11 -keyform engine -key slot_2-label_ssl_key -cert cert.pem -accept 44330
For the client:
OPENSSL_CONF=engine.conf openssl s_client -connect localhost:44330 -engine pkcs11
However, I need this connection to be established in Vertx(3.81) Java 8 connection.
When I look at the documentation of the vertx, there is an OpenSSLEngineOptions which can be set as serverOptions but I couldn't figure where to put parameters such as key name, slot number and engine id etc.
In fact, OpenSSLEngineOptions has a constructor which takes JsonObject, but I couldn't find any sample for this JsonObject.
Here is a code snipped where I instantiate the Vertx ssl option
HttpServerOptions serverOptions = jerseyServerOptions.getServerOptions();
OpenSSLEngineOptions openSSLOptions = new OpenSSLEngineOptions();
serverOptions.setOpenSslEngineOptions(openSSLOptions);
serverOptions.setPort(1234);
serverOptions.setSsl(true);
String certCopy = "-----BEGIN CERTIFICATE-----
MIICMzCCAZygAwIBAgIJALiPnVsvq8dsMA0GCSqGSIb3DQEBBQUAMFMxCzAJBgNV
BAYTAlVTMQwwCgYDVQQIEwNmb28xDDAKBgNVBAcTA2ZvbzEMMAoGA1UEChMDZm9v
MQwwCgYDVQQLEwNmb28xDDAKBgNVBAMTA2ZvbzAeFw0xMzAzMTkxNTQwMTlaFw0x
ODAzMTgxNTQwMTlaMFMxCzAJBgNVBAYTAlVTMQwwCgYDVQQIEwNmb28xDDAKBgNV
BAcTA2ZvbzEMMAoGA1UEChMDZm9vMQwwCgYDVQQLEwNmb28xDDAKBgNVBAMTA2Zv
bzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAzdGfxi9CNbMf1UUcvDQh7MYB
OveIHyc0E0KIbhjK5FkCBU4CiZrbfHagaW7ZEcN0tt3EvpbOMxxc/ZQU2WN/s/wP
xph0pSfsfFsTKM4RhTWD2v4fgk+xZiKd1p0+L4hTtpwnEw0uXRVd0ki6muwV5y/P
+5FHUeldq+pgTcgzuK8CAwEAAaMPMA0wCwYDVR0PBAQDAgLkMA0GCSqGSIb3DQEB
BQUAA4GBAJiDAAtY0mQQeuxWdzLRzXmjvdSuL9GoyT3BF/jSnpxz5/58dba8pWen
v3pj4P3w5DoOso0rzkZy2jEsEitlVM2mLSbQpMM+MUVQCQoiG6W9xuCFuxSrwPIS
pAqEAuV4DNoxQKKWmhVv+J0ptMWD25Pnpxeq5sXzghfJnslJlQND
-----END CERTIFICATE-----";
PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions().setCertValue(Buffer.buffer(certValue));
serverOptions.setPemKeyCertOptions(pemKeyCertOptions);
TLDR;
How can we establish a SSL connection in Vertx where the private key stored in only HSM and could't be extracted?
Edit:
I found the parser of the jsonObject in the constructor of OpenSSLEngineOptions here. Unfortunately, it only reads the sessionCacheEnabled option.
I came up with a solution using Security Provider and Java Keystore. Here is the sample code:
/*
pkcs11.cfg example:
name=PKCS11
library=vendor provided library absolute path
slot=0
*/
String propertyPath = "/root/IdeaProjects/ssl/pkcs11.cfg;
char[] pin = "1234".toCharArray();
Provider p = new SunPKCS11(propertyPath);
Security.removeProvider("IAIK");
Security.addProvider(p);
KeyStore ks = KeyStore.getInstance("PKCS11",p);
ks.load(null,pin);
After the initialization of KeyStore, you can direct your SSLContext to KeyStore. But according to Java 8 PKCS11 Documentation, the CKA_ID attribute of the certificate and the private key should match. If pkcs11 engine matches the pair of certificate and key, it should demonstrate as alias.
//Showing aliases
Enumeration<String> aliases = ks.aliases();
for (; aliases.hasMoreElements(); ){
System.out.println(aliases.nextElement());
}
After verifying aliases, we'll use SSLContext to bind our KeyManager.
SSLContext ctx = SSLContext.getInstane("TLS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(ks,pin);
ctx.init(keyManagerFactory.getKeyManagers(), null, null);
I'm trying to make a request to a server with a client certificate authentication with this code:
try {
/*** CA Certificate ***/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.caserver);
Certificate ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
System.out.println(keyStoreType);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
/*** Client Certificate ***/
KeyStore keyStore12 = KeyStore.getInstance("PKCS12");
InputStream certInput12 = getResources().openRawResource(R.raw.p12client);
keyStore12.load(certInput12, "123456key".toCharArray());
// Create a KeyManager that uses our client cert
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keyStore12, null);
/*** SSL Connection ***/
// Create an SSLContext that uses our TrustManager and our KeyManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
URL url = new URL("https://myurl/test.json");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
System.out.println("Weeeeeeeeeee");
InputStream in = urlConnection.getInputStream(); // this throw exception
}
catch (Exception e) {
e.printStackTrace();
}
I obtain the next exception when the execution reach the last line InputStream in = urlConnection.getInputStream();.
System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I have spent lots of hours trying to fix this error but I can't find any information. When I make the same request using a web browser with the client certificate, all is ok.
Any help? Thanks in advance.
Edit
I follow this steps to generate certificates:
> openssl req -config openssl.cnf -new -x509 -extensions v3_ca -days 3650 -keyout private/caserver.key -out certs/caserver.crt
> openssl req -config openssl.cnf -new -nodes -keyout private/client.key -out client.csr -days 1095
> openssl ca -config openssl.cnf -cert certs/caserver.crt -policy policy_anything -out certs/client.crt -infiles csr/client.csr
> openssl pkcs12 -export -clcerts -in certs/client.crt -inkey private/client.key -out p12client.p12
In my code I use caserver.crt and p12client.p12.
I don't know why input stream unable to read certificate from Assets folder. I had the same problem. To overcome , i have put certificate in raw folder and access it through
InputStream caInput = getResources().openRawResource(R.raw.mycertificate);
and worked well !
You appear to be focusing on the client certificate and possible problems there, but I think the error is related to the server certificate.
You have InputStream caInput = getResources().openRawResource(R.raw.caserver); which takes as input, a CA certificate of a CA that can verify that the server certificate is valid (caserver may be a DER file, for example). As your code is saying you want to trust that CA.
So, the problem may be that this file is not a correct certificate for that CA.
Or, it may really be the certificate for that CA. But that CA might not have signed your server certificate directly. Often, there is a chain of trust, where one CA might sign, then that CA is trusted by another CA, and so on, all the way up to a root CA or other CA that you trust.
So, why does the same web site, with same server certificate, work from the browser? Your browser may have a larger set of CAs that it trusts, so is able to authenticate the server. Whereas your android app may not trust one or more intermediate CAs in the chain of trust. Therefore, "Trust anchor for certification path not found."
What can you do about it? See google's guide on what to do with cases of unknown CA or missing intermediate CA, etc.
I have a Java web service client, which consumes a web service via HTTPS.
import javax.xml.ws.Service;
#WebServiceClient(name = "ISomeService", targetNamespace = "http://tempuri.org/", wsdlLocation = "...")
public class ISomeService
extends Service
{
public ISomeService() {
super(__getWsdlLocation(), ISOMESERVICE_QNAME);
}
When I connect to the service URL (https://AAA.BBB.CCC.DDD:9443/ISomeService ), I get the exception java.security.cert.CertificateException: No subject alternative names present.
To fix it, I first ran openssl s_client -showcerts -connect AAA.BBB.CCC.DDD:9443 > certs.txt and got following content in file certs.txt:
CONNECTED(00000003)
---
Certificate chain
0 s:/CN=someSubdomain.someorganisation.com
i:/CN=someSubdomain.someorganisation.com
-----BEGIN CERTIFICATE-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-----END CERTIFICATE-----
---
Server certificate
subject=/CN=someSubdomain.someorganisation.com
issuer=/CN=someSubdomain.someorganisation.com
---
No client certificate CA names sent
---
SSL handshake has read 489 bytes and written 236 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-MD5
Server public key is 512 bit
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol : TLSv1
Cipher : RC4-MD5
Session-ID: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Session-ID-ctx:
Master-Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Key-Arg : None
Start Time: 1382521838
Timeout : 300 (sec)
Verify return code: 21 (unable to verify the first certificate)
---
AFAIK, now I need to
extract the part of certs.txt between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----,
modify it so that the certificate name is equal to AAA.BBB.CCC.DDD and
then import the result using keytool -importcert -file fileWithModifiedCertificate (where fileWithModifiedCertificate is the result of operations 1 and 2).
Is this correct?
If so, how exactly can I make the certificate from step 1 work with IP-based adddress (AAA.BBB.CCC.DDD) ?
Update 1 (23.10.2013 15:37 MSK): In an answer to a similar question, I read the following:
If you're not in control of that server, use its host name (provided
that there is at least a CN matching that host name in the existing
cert).
What exactly does "use" mean?
I fixed the problem by disabling HTTPS checks using the approach presented here:
I put following code into the the ISomeService class:
static {
disableSslVerification();
}
private static void disableSslVerification() {
try
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
Since I'm using the https://AAA.BBB.CCC.DDD:9443/ISomeService for testing purposes only, it's a good enough solution, but do not do this in production.
Note that you can also disable SSL for "one connection at a time" ex:
// don't call disableSslVerification but use its internal code:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
httpsConn.setHostnameVerifier(allHostsValid);
httpsConn.setSSLSocketFactory(sc.getSocketFactory());
}
This is an old question, yet I had the same problem when moving from JDK 1.8.0_144 to jdk 1.8.0_191
We found a hint in the changelog:
Changelog
we added the following additional system property, which helped in our case to solve this issue:
-Dcom.sun.jndi.ldap.object.disableEndpointIdentification=true
I've the same problem and solved with this code.
I put this code before the first call to my webservices.
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
return hostname.equals("localhost"); // or return true
}
});
It's simple and works fine.
Here is the original source.
The verification of the certificate identity is performed against what the client requests.
When your client uses https://xxx.xxx.xxx.xxx/something (where xxx.xxx.xxx.xxx is an IP address), the certificate identity is checked against this IP address (in theory, only using an IP SAN extension).
If your certificate has no IP SAN, but DNS SANs (or if no DNS SAN, a Common Name in the Subject DN), you can get this to work by making your client use a URL with that host name instead (or a host name for which the cert would be valid, if there are multiple possible values). For example, if you cert has a name for www.example.com, use https://www.example.com/something.
Of course, you'll need that host name to resolve to that IP address.
In addition, if there are any DNS SANs, the CN in the Subject DN will be ignored, so use a name that matches one of the DNS SANs in this case.
To import the cert:
Extract the cert from the server, e.g. openssl s_client -showcerts -connect AAA.BBB.CCC.DDD:9443 > certs.txt This will extract certs in PEM format.
Convert the cert into DER format as this is what keytool expects, e.g. openssl x509 -in certs.txt -out certs.der -outform DER
Now you want to import this cert into the system default 'cacert' file. Locate the system default 'cacerts' file for your Java installation. Take a look at How to obtain the location of cacerts of the default java installation?
Import the certs into that cacerts file: sudo keytool -importcert -file certs.der -keystore <path-to-cacerts> Default cacerts password is 'changeit'.
If the cert is issued for an FQDN and you're trying to connect by IP address in your Java code, then this should probably be fixed in your code rather than messing with certificate itself. Change your code to connect by FQDN. If FQDN is not resolvable on your dev machine, simply add it to your hosts file, or configure your machine with DNS server that can resolve this FQDN.
I fixed this issue in a right way by adding the subject alt names in certificate rather than making any changes in code or disabling SSL unlike what other answers suggest here. If you see clearly the exception says the "Subject alt names are missing" so the right way should be to add them
Please look at this link to understand step by step.
The above error means that your JKS file is missing the required domain on which you are trying to access the application.You will need to Use Open SSL and the key tool to add multiple domains
Copy the openssl.cnf into a current directory
echo '[ subject_alt_name ]' >> openssl.cnf
echo 'subjectAltName = DNS:example.mydomain1.com, DNS:example.mydomain2.com, DNS:example.mydomain3.com, DNS: localhost'>> openssl.cnf
openssl req -x509 -nodes -newkey rsa:2048 -config openssl.cnf -extensions subject_alt_name -keyout private.key -out self-signed.pem -subj '/C=gb/ST=edinburgh/L=edinburgh/O=mygroup/OU=servicing/CN=www.example.com/emailAddress=postmaster#example.com' -days 365
Export the public key (.pem) file to PKS12 format. This will prompt you for password
openssl pkcs12 -export -keypbe PBE-SHA1-3DES -certpbe PBE-SHA1-3DES -export -in
self-signed.pem -inkey private.key -name myalias -out keystore.p12
Create a.JKS from self-signed PEM (Keystore)
keytool -importkeystore -destkeystore keystore.jks -deststoretype PKCS12 -srcstoretype PKCS12 -srckeystore keystore.p12
Generate a Certificate from above Keystore or JKS file
keytool -export -keystore keystore.jks -alias myalias -file selfsigned.crt
Since the above certificate is Self Signed and is not validated by CA, it needs to be added in Truststore(Cacerts file in below location for MAC, for Windows, find out where your JDK is installed.)
sudo keytool -importcert -file selfsigned.crt -alias myalias -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts
Original answer posted on this link here.
You may not want to disable all ssl Verificatication and so you can just disable the hostName verification via this which is a bit less scary than the alternative:
HttpsURLConnection.setDefaultHostnameVerifier(
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
[EDIT]
As mentioned by conapart3 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER is now deprecated, so it may be removed in a later version, so you may be forced in the future to roll your own, although I would still say I would steer away from any solutions where all verification is turned off.
my problem with getting this error was resolved by using the full URL "qatest.ourCompany.com/webService" instead of just "qatest/webService". Reason was that our security certificate had a wildcard i.e. "*.ourCompany.com". Once I put in the full address the exception went away. Hope this helps.
As some one pointed before, I added the following code (with lambda) just before creating the RestTemplate object, and it works fine. IT is only for my internal testing class, so I will work around with a better solution for the production code.
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
(hostname, sslSession) -> true);
We faced a similar issue recently "No subject alternative DNS name matching found", it was a nightmare because we were able to reproduce it only in Production servers, were access to debug is near to zero. The rest of environments were just working fine. Our stack was JDK 1.8.x+, JBoss EAP 7+, Java Spring Boot app and Okta as identity provider (the SSL handshake was failing when recovering the well-known configuration from Okta, where okta is available in AWS Cloud - virtual servers).
Finally, we discover that (no one knows why) the JBoss EAP application server that we were using it was having an additional JVM System Property:
jsse.enableSNIExtension = false
This was preventing to establish TLS connection and we were able to reproduce the issue by adding that same system property/value in other environments. So the solution was simple to remove that undesired property and value.
As per Java Security Doc, this property is set by default to true for Java 7+ (refer to https://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#InstallationAndCustomization)
jsse.enableSNIExtension system property. Server Name Indication (SNI) is a TLS extension, defined in RFC 4366. It enables TLS connections to virtual servers, in which multiple servers for different network names are hosted at a single underlying network address.
Some very old SSL/TLS vendors may not be able handle SSL/TLS extensions. In this case, set this property to false to disable the SNI extension.
Have answered it already in https://stackoverflow.com/a/53491151/1909708.
This fails because neither the certificate common name (CN in certification Subject) nor any of the alternate names (Subject Alternative Name in the certificate) match with the target hostname or IP adress.
For e.g., from a JVM, when trying to connect to an IP address (WW.XX.YY.ZZ) and not the DNS name (https://stackoverflow.com), the HTTPS connection will fail because the certificate stored in the java truststore cacerts expects common name (or certificate alternate name like stackexchange.com or *.stackoverflow.com etc.) to match the target address.
Please check: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#HostnameVerifier
HttpsURLConnection urlConnection = (HttpsURLConnection) new URL("https://WW.XX.YY.ZZ/api/verify").openConnection();
urlConnection.setSSLSocketFactory(socketFactory());
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
});
urlConnection.getOutputStream();
Above, passed an implemented HostnameVerifier object which is always returns true:
new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
}
For Spring Boot RestTemplate:
add org.apache.httpcomponents.httpcore dependency
use NoopHostnameVerifier for SSL factory:
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(new URL("file:pathToServerKeyStore"), storePassword)
// .loadKeyMaterial(new URL("file:pathToClientKeyStore"), storePassword, storePassword)
.build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate restTemplate = new RestTemplate(factory);
This code will work like charm and use the restTemple object for rest of the code.
RestTemplate restTemplate = new RestTemplate();
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
#Override
public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
return true;
}
};
SSLContext sslContext = null;
try {
sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
.build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
restTemplate.setRequestFactory(requestFactory);
}
I also faced the same issue with a self signed certificate . By referring to few of the above solutions , i tried regenerating the certificate with the correct CN i.e the IP Address of the server .But still it didn't work for me .
Finally i tried regenerating the certificate by adding the SAN address to it via the below mentioned command
**keytool -genkey -keyalg RSA -keystore keystore.jks -keysize 2048 -alias <IP_ADDRESS> -ext san=ip:<IP_ADDRESS>**
After that i started my server and downloaded the client certificates via the below mentioned openssl command
**openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem**
Then i imported this client certificate to the java default keystore file (cacerts) of my client machine by the below mentioned command
**keytool -import -trustcacerts -keystore /home/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-1.el7.x86_64/jre/lib/security/cacerts -alias <IP_ADDRESS> -file ./mycert.pem**
I got to this question after if got this same error message. However in my case we had two URL's with different subdomains (http://example1.xxx.com/someservice and http://example2.yyy.com/someservice) which were directed to the same server. This server was having only one wildcard certificate for the *.xxx.com domain. When using the service via the second domain, the found certicate (*.xxx.com) does not match with the requested domain (*.yyy.com) and the error occurs.
In this case we should not try to fix such an errormessage by lowering SSL security, but should check the server and certificates on it.
I was going through 2 way SSL in springboot. I have made all correct configuration service tomcat server and service caller RestTemplate. but I was getting error as "java.security.cert.CertificateException: No subject alternative names present"
After going through solutions, I found, JVM needs this certificate otherwise it gives handshaking error.
Now, how to add this to JVM.
go to jre/lib/security/cacerts file. we need to add our server certificate file to this cacerts file of jvm.
Command to add server cert to cacerts file via command line in windows.
C:\Program Files\Java\jdk1.8.0_191\jre\lib\security>keytool -import -noprompt -trustcacerts -alias sslserver -file E:\spring_cloud_sachin\ssl_keys\sslserver.cer -keystore cacerts -storepass changeit
Check server cert is installed or not:
C:\Program Files\Java\jdk1.8.0_191\jre\lib\security>keytool -list -keystore cacerts
you can see list of certificates installed:
for more details: https://sachin4java.blogspot.com/2019/08/javasecuritycertcertificateexception-no.html
add the host entry with the ip corresponding to the CN in the certificate
CN=someSubdomain.someorganisation.com
now update the ip with the CN name where you are trying to access the url.
It worked for me.
When you have a certificate with both CN and Subject Alternative Names (SAN), if you make your request based on the CN content, then that particular content must also be present under SAN, otherwise it will fail with the error in question.
In my case CN had something, SAN had something else. I had to use SAN URL, and then it worked just fine.
I have resolved the said
MqttException (0) - javax.net.ssl.SSLHandshakeException: No
subjectAltNames on the certificate match
error by adding one (can add multiple) alternative subject name in the server certificate (having CN=example.com) which after prints the part of certificate as below:
Subject Alternative Name:
DNS: example.com
I used KeyExplorer on windows for generating my server certificate.
You can follow this link for adding alternative subject names (follow the only part for adding it).
I was referred to animo3991's answer and tweaked it to make my Bitbucket Backup Client 3.6.0 work for backing up my Bitbucket Server when before it was also hitting No subject alternative names present error.
The first command however must use alias tomcat, otherwise Bitbucket Server would not start up properly:
keytool -genkey -keyalg RSA -sigalg SHA256withRSA -keystore keystore.jks -keysize 2048 -alias tomcat -ext san=ip:<IP_ADDRESS>
openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem
keytool -import -trustcacerts -keystore /etc/pki/ca-trust/extracted/java/cacerts -alias <IP_ADDRESS> -file ./myCert.pem
public class RESTfulClientSSL {
static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}};
public class NullHostNameVerifier implements HostnameVerifier {
/*
* (non-Javadoc)
*
* #see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
* javax.net.ssl.SSLSession)
*/
#Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
}
public static void main(String[] args) {
HttpURLConnection connection = null;
try {
HttpsURLConnection.setDefaultHostnameVerifier(new RESTfulwalkthroughCer().new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
String uriString = "https://172.20.20.12:9443/rest/hr/exposed/service";
URL url = new URL(uriString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//connection.setRequestMethod("POST");
BASE64Encoder encoder = new BASE64Encoder();
String username = "admin";
String password = "admin";
String encodedCredential = encoder.encode((username + ":" + password).getBytes());
connection.setRequestProperty("Authorization", "Basic " + encodedCredential);
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
String content = stringBuffer.toString();
System.out.println(content);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Add your IP address in the hosts file.which is in the folder of C:\Windows\System32\drivers\etc.
Also add IP and Domain Name of the IP address.
example:
aaa.bbb.ccc.ddd abc#def.com