Unable to connect to MySQL database with SunCertPathBuilderException - java

I'm trying to connect to MySQL database:
static final String URL="jdbc:mysql://localhost:3306/demo_hotels?useSSL=true&autoReconnect=true&serverTimezone=UTC";
static final String USERNAME="demo";
static final String PASSWORD="demo";
public static void main(String[] args) {
try {
DriverManager.registerDriver(new FabricMySQLDriver());
connection=DriverManager.getConnection(URL, USERNAME, PASSWORD);
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new
JdbcConnection(connection));
Liquibase liquibase = new liquibase.Liquibase("db/db.changelog.xml",
new ClassLoaderResourceAccessor(), database);
liquibase.update(new Contexts(), new LabelExpression());
database.close();
} catch (SQLException | LiquibaseException e) {
e.printStackTrace();
}
This was working. But now I'm trying to execute this code on another machine and it doesn't work:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
at com.pazukdev.auxiliary_services.DBService.main(DBService.java:69)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
Why did it stop to work?
Old machine: java version 1.8.0_112, Windows 7, MySQL Server 5.7.21
New machine: java version 1.8.0_172, Windows 10, MySQL Server 8.0.11
I found some information about such kind of exceptions. It look like I have some triobles with SSL certificate: Accept server's self-signed ssl certificate in Java client
But Option 2 with TrustManager not works - I have the same Exception.
I tried to type in cmd:
<JAVA_HOME>\bin\keytool -import -v -trustcacerts
-alias server-alias -file server.cer
-keystore cacerts.jks -keypass changeit
-storepass changeit
But I have no eny effect from this Option 1 too.
Maybe I'm doing something wrong..

I'm not Java developer, but I have some doubts and questions here.
Do you actually need for ?useSSL=true if you're using local db?
What are the results of your cmd execution? Did you have correctly exported server.cer file corresponds to your local host? With necessary keypass and storepass?

I had a global problem with database and connection to it. It was caused by that now I installed all the MySQL stuff in its lastest versions. And on my old machine I have the older versions of that software. So, I even had some exceptions trying to execute some of my old MySQL queries in new software.
I installed the same versions of MySQL Server and Connector/ODBC as I have on old machine (5.7.21 and 5.3.10 respectively) and got connection working properly as before.

Related

The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed:

I'm new to SQL(Microsoft SQL Server Management) and I am trying to connect it with IntelliJ
I am getting the following error:
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target".
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MyJDBC {
public static void main(String[] args) {
String connectionURL = "jdbc:sqlserver://localhost:10020;databaseName=mydatabase;user=me;password=random_password";
try {
System.out.print("Connecting to the server......");
try (Connection connection = DriverManager.getConnection(connectionURL)) {
System.out.println("Connected to the Server.");
}
}catch (Exception e){
System.out.println("I am not connected to the Server");
e.printStackTrace();
}
}
}
I have this on my lib
LIB
Any help is appreciated it!
Add encrypt=true and trustServerCertificate=true to connection url.
String connectionURL = "jdbc:sqlserver://localhost:10020;databaseName=mydatabase;user=me;password=random_password;encrypt=true;trustServerCertificate=true";
Microsoft Blog Reference - link
Find below excerpt from it -
This is an issue in Java Certificate Store. As a quick workaround, if
you enable TrustServerCertificate=True in the connection string, the
connection from JDBC succeeds. When TrustServerCertificate is set to
true, the transport layer will use SSL to encrypt the channel and
bypass walking the certificate chain to validate trust. If
TrustServerCertificate is set to true and encryption is turned on, the
encryption level specified on the server will be used even if Encrypt
is set to false. The connection will fail otherwise. However, for
security considerations, it is not recommended to bypass the
certificate validation. Hence, to address the issue, follow the steps
below to change the connection string and import the required
certificates.
Change the connection string to point to the Java certificate path
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;" +
"encrypt=true; trustServerCertificate=false;" +
"trustStore= C:\Program Files\Java\jdk-14.0.2\lib\cacert;trustStorePassword=changeit";
Import all the certificates mentioned in this document.
Note: To import above certificates into the keystore cacerts, please
use below command and please note you must mention truststore and
truststore password in the connection string to successfully connect.
Steps to import missing certificates in Java Certificate Store
Download all the certs from here, store them in a location on client
host and then use keytool utility to import these certificates into
the truststore. Please follow the below steps:
Save all the certificates from the above MS doc. Keytool utility is in
the bin folder of your default Java location (C:\Program
Files\Java\jdk-14.0.2\bin). You need to use command prompt to navigate
to that location. Then you can use the keytool command to import the
certificate previously saved. When prompted for password insert the
key in the password as “changeit”
Example of commands:
keytool -importcert -trustcacerts -alias TLS1 -file
"C:\Users\Documents\Microsoft RSA TLS CA 01.crt" -keystore "C:\Program
Files\Java\jdk-14.0.2\lib\security\cacerts"
keytool -importcert -trustcacerts -alias TLS2 -file
"C:\Users\Documents\Microsoft RSA TLS CA 02.crt" -keystore "C:\Program
Files\Java\jdk-14.0.2\lib\security\cacerts"
Below worked for me:
jdbc:sqlserver://Host;trustServerCertificate=true;integratedSecurity=true;authenticationScheme=NTLM

WildFly 11 - Use certificate to make https requests

I'm a bit lost of how I can use certificate in WidlFly 11. I re the doccumentation and found a lot of terms like JSSE, OpenSSL, Elytron, ApplicationRealm.
The problem occurs when I execute the code
final URL url = new URL("https://someUrl");
HttpsURLConnection httpURLConnection = (HttpsURLConnection)url.openConnection();
This exception is thrown sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
So, what exactly need to configure? I tried the section "Enable One-way SSL/TLS for Applications" in Elytron Doccumentation but didn't works.
ps: I'm using java 9.01
ps2: I'm using standalone-full.xml
let me know if you need more informations
This is unrelated to WildFly - you need to configure certificates trusted by java URL connections - you need to create and configure truststore:
create keystore containing certificate of server (if it is self-signed certificate), or better, certificate of its CA:
keytool -import -file myCA.cert -alias myCA -storepass mypassword -noprompt -keystore my.truststore
start using created keystore file as truststore in WildFly by setting javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword system properties:
bin/jboss-cli.sh -c
/system-property=javax.net.ssl.trustStore:add(value="/path/to/my.truststore")
/system-property=javax.net.ssl.trustStorePassword:add(value="mypassword")
Elytron documentation you mention is related only to server side - but this is client side configuration, which is not currently handled by it.
The certificate is not trusted, iirc there is a self-signed certificate in WildFly 11 so yo need to trust it or install a real certificate.
Accept server's self-signed ssl certificate in Java client

issues in connecting to AD server over SSL?

I had to enable SSL over Active Directory server, to do that I followed each and every steps mentioned here: http://www.linuxmail.info/enable-ldap-ssl-active-directory/
Now I am not sure if SSL is really enabled properly?
On server itself if I run ldp, I think I can connect on 636 port. However on my system I don't see SSL option on ldp client?
I've two other LDAP clients (Softerra LDAP Browser and Apache Directory Studio) but I am not able to connect using ldaps (on 636 port). I guess I'll need to import certificate used in AD server so these tools can trust that self sign certificate which I used on AD server.
Using Java code, I've added certificate into cacerts (got certificate using steps mentioned here: http://www.linuxmail.info/export-ssl-certificate-windows-2003/), however I still can't connect to AD using SSL.
I tried SSL as well as TSL:
TLS:
// got LdapContext using ldap (not with ldaps)
StartTlsResponse tls = (StartTlsResponse)ctx.extendedOperation(new StartTlsRequest());
It gives following exception:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
SSL:
String ldapURL = "ldaps://<domain-name>:636";
String keystore = "C:/Oracle/Middleware/jdk160_24/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore",keystore);
env.put(Context.SECURITY_PROTOCOL,"ssl");
// other properties are set in env
LdapContext ctx = new InitialLdapContext(env, null);
It gives following exception:
javax.naming.CommunicationException: <domain-name>:636 [Root exception is java.net.ConnectException: Connection timed out: connect]
Can anyone please suggest where I am wrong?
Thanks.
This one was fixed.
I was using wrong (rather incomplete) command to import certificate.
I was using:
keytool -import -alias mycert -keystore cacerts -file d:\mycert.cer
When I used follwing:
keytool -import -noprompt -trustcacerts -alias mycert -file c:/mycert.cer -keystore C:/Oracle/Middleware/jdk160_24/jre/lib/security/cacerts -storepass changeit
And it started working.
If you can't get TLS to work, it is unlikely that SSL will work. Are you sure that you got the right certificate and configured the keystore correctly? Based on the SSLHandshakeException when trying to use TLS, it would seem that may not be set up correctly.
Check out this SO answer for some tips on how to verify that your keystore is correctly set up: https://stackoverflow.com/a/9619478/1792088

com.iplanet.services.comm.client.SendRequestException: sun.security.validator.ValidatorException: PKIX path building failed:

I did with following steps but its throwing exception:
1.I have installed openam 10.0.0 on windows server 2003.
2.Configured tomcat with ssl on the same windows server machine.
3.It is configured correctly and openam url is accessible with https.
4.Installed openam client sdk on another machine which is ubuntu machine and from that ubuntu machin i am trying to login to openam server using
AuthContext lc = new AuthContext("/","https://server.ensarm.com:8443/openam/namingservice");
AuthContext.IndexType indexType = AuthContext.IndexType.MODULE_INSTANCE;
lc.login(indexType, "DataStore");
return lc;
But i am getting following exception:
ERROR: Naming service connection failed for https://server.ensarm.com:8443/openam/namingservice
com.iplanet.services.comm.client.SendRequestException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I didn't understand what could be the problem.Is it due to to my java keystore (needed for ssl configuration) is on windows server machine and i have no keystore on ubuntu machine,
OR
need to import keystore into ubuntu machine.?? Please can anyone help me to get out of this.
“javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:”
It means the server does not have a valid certificate from an Authorized CA.
You are facing this exception because you are try to connect through SSL (https). You would need to import the server certificate into the JRE KeyStore.
Perform the following steps to resolve it:
Getting the certificate: Type the URL (e.g. https://server.ensarm.com:8443/openam/namingservice) in your browser.
You will now probably see a dialog box warning you about the certificate. Now click on the 'View Certificate' and install the certificate. Ignore any warning messages.
Next step would be to install export the certificate and installing it in the jre keystore. Use keytool certificate management utility to perform thishttp://download.oracle.com/javase/1.3/docs/tooldocs/win32/keytool.html .
Exporting certificate: Go to Tools->'Internet Options' ->Content->Certificates. Once you open the certificates, locate the one you just installed under 'Trusted Root Certification Authorities". Select the right one and click on 'export'. You can now save it (DER encoded binary) as e.g. mycert.cer.
Go to JRE\BIN and use the keytool -import command to import the file into your cacerts keystore.
E.g. keytool --import -alias MYCA -keystore ..\lib\security\cacerts -file c:\mycert.cer.
Enter keystore password: (by default it will be “changeit”).Input “yes” to the prompts.
Run command keytool -list -keystore ..\lib\security\cacerts . You will now see a list of all the certificates including the one you just added.

SSL Connection from Java client

I'm creating a Java client program that will be sending sensitive information to a Tomcat server. So I need to use SSL Connection so information will be encrypted.
I need to use self-signed untrusted certificate but having problems making connection from java client.
I have successfully setup Tomcat 5.5 to use SSL and tested it through Firefox, which displays warning of self-signed certificate.
I followed the Tomcat 5.5 SSL setup and they mentioned to create a keystore:
keytool -genkey -alias tomcat -keyalg RSA
Then I did an export of the above:
keytool -export -keystore .keystore -alias tomcat -file localhost.cer
Then I did an import of the above certificate into client machine:
keytool -import -alias tomcat -file localhost.cer -keystore "C:\Program Files"\Java\jdk1.6.0_17\jre\lib\security\cacerts"
But when running client I get:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This is the client code:
URL url = new URL("https://localhost:8443");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslsocketfactory);
InputStream inputstream = conn.getInputStream();
Now I just started playing with these certificates today and I'm new to keystores, so please be patient.
Can someone please explain how to export and import the certificate created in Tomcat to client machine?
Thank you.
Atlassian has good instructions on how to fix this.
http://confluence.atlassian.com/display/JIRA/Connecting+to+SSL+services
Another approach is to install less unforgiving certificate validators, but that should only be done as a last resort.
Use Apache HTTP Cleint jar and follow this SSL Guide.
EasySSLProtocolSocketFactory can be used to create SSL connections that allow the target server to authenticate with a self-signed certificate.
I think you should input password using "changeit".

Categories