Embedded Tomcat enable SSL - java

I'm trying to setup SSL for embedded Tomcat. Both connectors starts but I only get response on http. On https I get in chrome a "No data received message" when I try http://localhost:9000/
The port is open:
I've tried telnet
telnet localhost 9000
and I have a connection.
I've also tried
openssl s_client -connect localhost:9000
and GET / method
and my servlet prints me the expected result in console. I do not understand why I get this error in browsers(chrome and Firefox)
My OS is Ubuntu 14.04 and I've tried with both Java 7 and Java 8 having the same result. Tomcat version is 8.0.23 from Maven repo
The code is:
public class Main {
public static void main(String[] args) throws Exception {
Tomcat tomcat = new Tomcat();
Service service = tomcat.getService();
service.addConnector(getSslConnector());
File base = new File(System.getProperty("java.io.tmpdir"));
Context rootCtx = tomcat.addContext("/", base.getAbsolutePath());
Tomcat.addServlet(rootCtx, "emptyServlet", new EmptyServlet());
rootCtx.addServletMapping("/*", "emptyServlet");
tomcat.start();
tomcat.getServer().await();
}
private static Connector getSslConnector() {
Connector connector = new Connector();
connector.setPort(9000);
connector.setSecure(true);
connector.setScheme("https");
connector.setAttribute("keyAlias", "tomcat");
connector.setAttribute("keystorePass", "password");
connector.setAttribute("keystoreType", "JKS");
connector.setAttribute("keystoreFile",
"keystore.jks");
connector.setAttribute("clientAuth", "false");
connector.setAttribute("protocol", "HTTP/1.1");
connector.setAttribute("sslProtocol", "TLS");
connector.setAttribute("maxThreads", "200");
connector.setAttribute("protocol", "org.apache.coyote.http11.Http11AprProtocol");
connector.setAttribute("SSLEnabled", true);
return connector;
}
}
The keystore you can find it on github
I've already tried different keystores but with the same result. Also the keystore looks good: keytool -list -keystore keystore.jks seems to be as expected.
Thanks in advance

It turned out to be my fault. The service was up and running but I kept on trying on http://localhost:9000 not https://locahost:9000 in my browser

Related

Java Rconnection hangs when Rserve has TLS enabled

I have an Ubuntu VM with R and Rserve installed for remote calls. I start Rserve in debug mode from the terminal with:
R CMD Rserve.dbg
And this is the output:
Rserve 1.8-6 () (C)Copyright 2002-2013 Simon Urbanek
Loading config file /etc/Rserv.conf
conf> command="remote", parameter="enable"
conf> command="plaintext", parameter="disable"
conf> command="encoding", parameter="utf8"
conf> command="pwdfile", parameter="/etc/RserveAuth.txt"
conf> command="auth", parameter="required"
conf> command="qap", parameter="disable"
conf> command="qap.tls.port", parameter="6311"
conf> command="tls.key", parameter="server.key"
conf> command="tls.cert", parameter="server.crt"
conf> command="tls.ca", parameter="rootCA.crt"
Loaded config file /etc/Rserv.conf
R version 3.5.3 (2019-03-11) -- "Great Truth"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
- create_server(port = 6311, socket = <NULL>, mode = 0, flags = 0x800)
INFO: adding server 0x5618de18b9d0 (total 1 servers)
Rserve: Ok, ready to answer queries.
I generated the key and self-signed certificates with OPENSSL.
Now on the client side, I have a Java application just requesting the version of R that Rserve is sitting on top of as a test of functionality:
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.Rserve.RConnection;
public class RJava {
public static void main(String[] args) throws Exception{
//Run R code on remote R installation via Rserve.
String remoteIP="10.16.24.63"; //Ubuntu VM Box
int port=6311;
String user="TEST";
String pass="12345";
//Connect to the remote server.
RConnection connection = new RConnection(remoteIP,port);//Remote server
connection.login(user, pass);
//Run a command.
REXP x = connection.eval("R.version.string");
System.out.println(x.asString());
//Disconnect.
connection.close();
}
}
The problem is the client code hangs on the call to the RConnection constructor. I've let it go for ten minutes and nothing changes until I kill the server. On the server side I just see:
INFO: accepted connection for server 0x5618de18b9d0, calling connected
connection accepted.
I can't find any documentation to help at this point. Is this possibly a client configuration problem?
Also, if I remove all the TLS configuration items from Rserv.conf, Rserve will work as expected no problem with this client code, so I know it is set up correctly.
I figured this out on my own. It was in fact a client configuration problem. I needed to create the RConnection with an SSLSocket and also import the server certificate to the java truststore.
Relevant client code changed to this:
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(remoteIP, port);
//Connect to the remote server.
RConnection connection = new RConnection(sslsocket);
N.B. the constructor RConnection(Socket s) is apparently not in the REngine jar, so I grabbed the source itself and put that in my project because it is included there.
Running at this point threw a javax.net.ssl.SSLHandshakeException because the cert wasn't in the truststore. So I withdrew the cert from the server using OPENSSL like this:
echo "" | openssl s_client -connect 10.16.24.63:6311 | openssl x509 -out server.crt
Then I moved that cert file to %JAVA_HOME%\jre\lib\security and ran this to import the certificate:
keytool -import -alias myAlias -file server.crt -keystore cacerts -storepass changeit
And it works! Wireshark confirms all the packets are now encrypted.
Resources:
https://stats-rosuda-devel.listserv.uni-augsburg.narkive.com/g5VM1afB/encryption-with-rserve-1-8-1
https://www.baeldung.com/java-ssl
Digital Certificate: How to import .cer file in to .truststore file using?

Unable to connect to MySQL database with SunCertPathBuilderException

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.

grails application gmail smtp not working on ubuntu

My gmail smtp in my grails application is working fine on windows but not working when it comes to ubuntu machine with same configuration.
Configuration used by me are:
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "*******#gmail.com"
password = "*********"
props = ["mail.smtp.auth":"false", "mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false" ]
}
Install and configure Sendmail on Ubuntu
This should help you get Sendmail installed with basic configuration on Ubuntu.
If sendmail isn't installed,
install it:
sudo apt-get install sendmail
Configure /etc/hosts file:
nano /etc/hosts
3.Make sure the line looks like this:
127.0.0.1 localhost yourhostname
4.Run Sendmail's config and answer 'Y' to everything:
sudo sendmailconfig
Restart apache:
sudo service apache2 restart.
To check the status send of sendmail service
1: For start:
service sendmail start.
For restart:
service sendmail restart
3.Check the status :
service sendmail status
The correct configuration is the following, I have used it without any instalations, on Ubuntu, MacOS and Windows:
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "your#email.es"
password = "yourpassword"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}

MySQL is not connecting over SSL in java REST applications

I generated Keystore in Java home path. Set up the Connector in tomcat server.xml for the port 8443.
MySQL is not getting connected.
Added the following logic in java mysql connection class
String url = "jdbc:mysql://127.0.0.1:3306/xxxx"
"?verifyServerCertificate=false"+
"&useSSL=true"+
"&requireSSL=true";
System.setProperty("javax.net.ssl.keyStore", "path");
System.setProperty("javax.net.ssl.keyStorePassword", "pwd");
I think your key store config have some problem. Please check this link. Also, please attach error report.

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