Creating Encrypted connection for Amazon Aurora DB with public key - java

I am using Maria JDBC driver for creating a connection to Amazon Aurora DB
I wanted to create a secured connection so I read here
To connect to a DB cluster with SSL using the MySQL utility
Download the public key for the Amazon RDS signing certificate from
https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem.
Note that this will download a file named rds-combined-ca-bundle.pem.
First Question: How exactly is it secured - anyone can download this pem file from Amazon AWS?
I did some research How should i connect into Aurora DB with public key
and i found these 2 links First, Second
So my Code is quite Simple:
Class.forName("org.mariadb.jdbc.Driver");
Properties prop = new Properties();
prop.setProperty("javax.net.ssl.trustStore","C:\\temp\\rds-combined-ca-bundle.pem");
prop.setProperty("user",jdbcDetails.username);
prop.setProperty("password",jdbcDetails.getSensitiveData());
java.sql.Connection conne = DriverManager.getConnection(jdbcDetails.connectionString, prop);
try (Statement stmt1 = conne.createStatement()) {
// Execute all but the rest
ResultSet rs = stmt1.executeQuery("Select 98765 from dual limit 2");
while(rs.next()) {
rs.getLong(1);
}
}
conne.close();
Second Question: How is having the public key file relate to Encryption?
The above information doesn't get along with Oracle Java information that says:
If the client wants to authenticate the server, then the client's trust store must contain the server's certificate
Third Question: From what I understand if the client trust the server it doesn't require him to use this file
Forth Question: I was checking the connection creation with Wireshark
both cases with and without this public key file i was able to create a connection and both cases in Wireshark appeared Encrypted
Something that looks like that:
Encrypted Application Data:
eb:62:45:fb:10:50:f7:8c............:b9:0a:52:e7:97:1d:34

Base on this answer I understand about public key usage:
First,
It appears that Amazon AWS Azure documentation is misleading a bit - it is only relevant for connection with specific tool called MySQL utility
An answer for First & Second & third Question:
"Java can definitely establish an SSL connection without a client
validating the certificate chain of the server."
the key exchange is made to ensure that the server that it's connected to is indeed the one it was expecting (i.e non-suspicious server)
This means that it's still the same SSL connection made, but with verifyServerCertificate=false it does not verify that it is the intended server
Answer Forth Question:
Currect, The code is in Java - and passing the SSL parameter make it encrypted.
So using these parameter gives what requires
?trustServerCertificate=true&useSSL=true&requireSSL=true&verifyServerCertificate=false

Related

Code showing username and password for connecting to server

I'm writing a method that make it possible for my Java program to create a database connection that will eventually make me able to access it from other classes/methods.
public class DatabaseConnection
{
private Connection databaseLink;
public Connection getConnection()
{
String url = "jdbc:mysql://localhost/DBname";
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
databaseLink = DriverManager.getConnection(url, "fakeUsr", "fakePsw"); //these are not the real username/password
}
catch (Exception e)
{
e.printStackTrace();
}
return databaseLink;
}
}
I've got a couple of issues:
1)people not using my computer will not be able to get into my server since I wrote "localhost":
String url = "jdbc:mysql://localhost/DBname";
2)I've typed the real username and password instead of "fakeUsr" and "fakePsw".
The thing is: I'm quite sure that the average user of my program should NOT be able to access that information. Is there any other way to permit access to a DB without making username and password readable by virtually anyone getting access to my source code?
For issue n. 1: I tried to type my IP address instead of "localhost" here:
String url = "jdbc:mysql://localhost/DBname"; //changed localhost to my IP address
but then I get "Communications link failure".
For issue n. 2: I have literally no idea how to solve this. I've never coded a program that needs access to a DB so I had to improvise a bit for that.
About Issue #2:
There is no secure way of storing the password inside the code itself. You can of course try to encrypt the password, but then your code has to decrypt it when the connection is established and therefore the encryption key is visible virtually "to all that have access to your source code". With this key, it is possible to get to the real password, just a little bit more complicated.
The only secure way is to have the user enter the login credentials by his own. Either low level (program arguments when starting your application) or by some form of "login dialog", if the application has a GUI.
A third option would be to create a technical user with restricted DB access, depending on the application you are working on. But this usually causes security issues.
You could create your application such that it sends an https request and authenticate itself against a webserver. What you use to authenticate is up to you: Client IP, username, password, client certificates, ...
Once authenticated, your webserver could transfer a one-time username/password that the client uses to login into your database.
The advantage here is that you can still control whether the user gets full or restricted access, or gets no password any more for whatever reason. And there is no security hole in your application.
1⁠) Most Internet providers don’t allow ordinary users to accept incoming socket connections, both for security reasons and because the network traffic can quickly overwhelm consumer grade networks. You will have to either purchase a commercial Internet connection which allows incoming connections, or look for a server you can lease or borrow. I’m afraid I don’t know what options are available.
2⁠) As MrFreeze correctly pointed out, there is no way to safely embed credentials in an application. No matter what you do to obscure your database login credentials, someone can always decompile your program and figure out how you are decrypting those credentials. The only truly safe solution is to tell users you trust what the credentials are, then write your application so the user must enter them.
Side note: Class.forName("com.mysql.cj.jdbc.Driver"); has not been needed for many years. You can remove that line.

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Lotus Notes Java replication of remote database

I have a lot of Lotus Notes / Domino (version 7) database to migrate to a new software.
On my workstation (with Lotus Notes installed), I'm using a standalone Java application to connect to a local replica an extract data.
However the replication of the distant database is still a manual process. I'd like to automatise it.
My java code basically looks like this :
Session localSession = NotesFactory.createSession(); // With Notes thread initialized
Session remoteSession = NotesFactory.createSession(SERVER, USER, PASSWORD);
Database localDb = localSession.getDbDirectory(null).openDatabase("local_name", true);
Database remoteDb = remoteSession.getDbDirectory(null).openDatabaseByReplicaID(REPLICA);
// ***EDITED CALLING INSTANCE BELOW***
remoteDb.createReplica(null, "local_name"); // Error thrown here
However the last line throws an exception (from memroy, but something like)
CN=****/***** does not have the right to create database on a server
How is it possible that I don't have the right to create database on my local computer ?
Is there any other way to programmaticly create a local replica from a distant database ?
Edit: changed calling instance of create replica to match my code causing the issue
My guess is that it's just giving you the wrong error message. One thing that's definitely wrong is that he first argument for createReplica should be an empty string, not a null pointer. I.e., try this:
localDb.createReplica("", "local_name");
Ok it looks like I found the answer.
AFAIU I had to open the database on the target server, using my local session, and run the createReplica() from here. This way, the createReplica is executed on my local Lotus Notes server, and the replica is created locally.
Session localSession = NotesFactory.createSession((String)null, (String)null, PASSWORD);
DbDirectory remoteDbDirectory = localSession.getDbDirectory(remoteSession.getServerName());
Database localSessionRemoteDatabase = remoteDbDirectory.openDatabaseByReplicaID(REMOTE_REPLICA_ID);
localSessionRemoteDatabase.createReplica("", LOCAL_FILE_NAME);
#Richard Schwartz Can you confirm this is ok ?
The only weird thing, is that it opens a prompt (like when it's expecting password) but the replica is created.
The process is executed within Eclipse.

Remove output message when connecting to MySQL via Java

I have a question regarding connecting my Java program to my Mysql database.
I watched a video which creates a method that can connect to my database and has the form:
enter code here
public static Connection getConnection() throws Exception{
try{
String driver = "....";
String url = "....";
String username ="....";
String password = "....";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
}
catch(Exception e){System.out.println("Connection failed ");}
return null;
When executing this method in each function (such as deleting an entry or adding), I always receive the message: "Sat Nov 05 12:04:49 CET 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification."
How can I stop this error message and fix the above problem? Even though this message is shown, I can still work with the database, however, I want to get rid of the message because it harms the User interface (looks ugly and always gets repeated each time I connect to the database).
I know little about eclipse and MySQL. As a result, I don't know the terms use above.
Could anyone aid me on what to do in order to hide or remove the above message?
Thanks :)
This problem comes when you are trying to make SSL connection with the databse and you can avoid this warning by using the connection url:
jdbc:mysql://yourhost:port/dbname?useSSL=false
You can refer here for mysql jdbc connection properties.

How to connect to a database that requires password without exposing the password?

I am creating an application and I need to connect to a database. The database requires login/password so the application can do operations like select and insert.
In the application I need to connect to the database using login and password, so the application is free to do some tasks on the database. My question is: how do I store and use a password to connect to the database without exposing the password?
I can't simply use a hash or encryption to store the password because the database must recognize the password (I think most or all databases must receive password as plain text).
.
.
Note: The connection is made by the application. No human input to do the connection.
(Edit)More info about the application: it is a web application using servlets/jsp. The database is on the same server of the application. The user for the application is a default user without complete admin powers, but it may insert/delete rows and do most things that involve queries and data modification in tables.
The usual way this is done is to externalize the username/password to a property/config file which is read at runtime (whether or not you use native JDBC/JNDI/CDI/J2EE datasource/etc).
The file is protected via the O/S security by the sysadmins.
The O/S has better tools for protection than app code.
You can use jasypt for the encryption.And store the username and password to datasource.properties file.
public Connection getConnection() throws IOException{
try{
BasicTextEncryptor encryptor = new BasicTextEncryptor();
encryptor.setPassword("jasypt");
Properties props = new EncryptableProperties(encryptor);
props.load( this.getClass().getResourceAsStream("datasource.properties") );
String driver = props.getProperty("datasource.driver");
String url = props.getProperty("datasource.url");
String userName = props.getProperty("datasource.userName");
String password = props.getProperty("datasource.password");
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userName, password);
conn.setAutoCommit(false);
return conn;
} catch(ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch(SQLException e) {
e.printStackTrace();
return null;
}
}
You should use a config file for this. use spring with JDBC to make your life easier!
http://www.youtube.com/watch?v=f-k823MZ02Q
Checkout the above awesome tutorial on the Spring framework and using JDBC. Watch all of his JDBC and spring tutorials.
BTW, he covers how to store passwords in config files and wire beans etc.. Hope this helps.
If it's a web app, deploy it on a Java EE app server and connect using a JNDI resource. Only the admin who set up the JNDI data resource needs to know about the credentials needed to connect. Users and developers don't even have to know them; just the JNDI lookup name.
It's not possible to completely eliminate the need for someone besides the database owner to know the username and password, but it is possible to restrict that knowledge to the app server owner.
You are also well advised to create separate credentials just for that application and GRANT it the minimum access and permissions needed to accomplish its tasks. There should be no knowledge of system tables or any other resources outside the province of the application. IF DELETE permission isn't necessary, don't grant it. If access should only be read only, that's what you should GRANT to that credential.

Categories