Skip to content

Update config API for TLS to match DIP. #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,35 +27,34 @@
import javax.net.ssl.TrustManagerFactory;

import org.neo4j.driver.v1.Config;
import org.neo4j.driver.v1.exceptions.ClientException;
import org.neo4j.driver.internal.spi.Logger;

import static org.neo4j.driver.internal.util.CertificateTool.loadX509Cert;

class SSLContextFactory
{

private final String host;
private final int port;
private final Config.TlsAuthenticationConfig authConfig;
private final Config.TrustStrategy authConfig;
private final Logger logger;

SSLContextFactory( String host, int port, Config.TlsAuthenticationConfig authConfig )
SSLContextFactory( String host, int port, Config.TrustStrategy authConfig, Logger logger )
{
this.host = host;
this.port = port;
this.authConfig = authConfig;
this.logger = logger;
}

public SSLContext create()
throws GeneralSecurityException, IOException
{
SSLContext sslContext = SSLContext.getInstance( "TLS" );
TrustManager[] trustManagers;

// TODO Do we also want the server to verify the client's cert, a.k.a mutual authentication?
// Ref: http://logicoy.com/blogs/ssl-keystore-truststore-and-mutual-authentication/
KeyManager[] keyManagers = new KeyManager[0];
TrustManager[] trustManagers = null;

if ( authConfig.isFullAuthEnabled() )
{
switch ( authConfig.strategy() ) {
case TRUST_SIGNED_CERTIFICATES:
// A certificate file is specified so we will load the certificates in the file
// Init a in memory TrustedKeyStore
KeyStore trustedKeyStore = KeyStore.getInstance( "JKS" );
Expand All @@ -68,13 +67,15 @@ public SSLContext create()
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( "SunX509" );
trustManagerFactory.init( trustedKeyStore );
trustManagers = trustManagerFactory.getTrustManagers();
}
else
{
trustManagers = new TrustManager[]{new TrustOnFirstUseTrustManager( host, port, authConfig.certFile() )};
break;
case TRUST_ON_FIRST_USE:
trustManagers = new TrustManager[]{new TrustOnFirstUseTrustManager( host, port, authConfig.certFile(), logger )};
break;
default:
throw new ClientException( "Unknown TLS authentication strategy: " + authConfig.strategy().name() );
}

sslContext.init( keyManagers, trustManagers, null );
sslContext.init( new KeyManager[0], trustManagers, null );
return sslContext;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,22 @@ public static ByteChannel create( String host, int port, Config config, Logger l
soChannel.setOption( StandardSocketOptions.SO_KEEPALIVE, true );
soChannel.connect( new InetSocketAddress( host, port ) );

ByteChannel channel = null;
ByteChannel channel;

if( config.isTlsEnabled() )
switch ( config.encryptionLevel() )
{
channel = new SSLSocketChannel( host, port, soChannel, logger, config.tlsAuthConfig() );
case REQUIRED:
{
channel = new TLSSocketChannel( host, port, soChannel, logger, config.trustStrategy() );
break;
}
else
case REJECTED:
{
channel = new AllOrNothingChannel( soChannel );
break;
}
default:
throw new ClientException( "Unknown TLS Level: " + config.encryptionLevel() );
}

if( logger.isTraceEnabled() )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,19 @@

public class SocketConnector implements Connector
{
public static final String SCHEME = "bolt";
public static final int DEFAULT_PORT = 7687;

@Override
public boolean supports( String scheme )
{
return scheme.equals( Config.SCHEME );
return scheme.equals( SCHEME );
}

@Override
public Connection connect( URI sessionURI, Config config ) throws ClientException
{
int port = sessionURI.getPort() == -1 ? Config.DEFAULT_PORT : sessionURI.getPort();
int port = sessionURI.getPort() == -1 ? DEFAULT_PORT : sessionURI.getPort();
SocketConnection conn = new SocketConnection( sessionURI.getHost(), port, config );
conn.init( "bolt-java-driver/" + Version.driverVersion() );
return conn;
Expand All @@ -48,6 +51,6 @@ public Connection connect( URI sessionURI, Config config ) throws ClientExceptio
@Override
public Collection<String> supportedSchemes()
{
return Collections.singletonList( Config.SCHEME );
return Collections.singletonList( SCHEME );
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@

import org.neo4j.driver.internal.spi.Logger;
import org.neo4j.driver.internal.util.BytePrinter;
import org.neo4j.driver.v1.Config.TlsAuthenticationConfig;
import org.neo4j.driver.v1.Config.TrustStrategy;
import org.neo4j.driver.v1.exceptions.ClientException;

import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;

/**
* A blocking SSL socket channel.
* A blocking TLS socket channel.
*
* When debugging, we could enable JSSE system debugging by setting system property:
* {@code -Djavax.net.debug=all} to value more information about handshake messages and other operations underway.
Expand All @@ -49,7 +49,7 @@
* http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#SSLENG
* http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLEngine.html
*/
public class SSLSocketChannel implements ByteChannel
public class TLSSocketChannel implements ByteChannel
{
private final SocketChannel channel; // The real channel the data is sent to and read from
private final Logger logger;
Expand All @@ -64,25 +64,25 @@ public class SSLSocketChannel implements ByteChannel
private ByteBuffer plainIn;
private ByteBuffer plainOut;

public SSLSocketChannel( String host, int port, SocketChannel channel, Logger logger,
TlsAuthenticationConfig authConfig )
public TLSSocketChannel( String host, int port, SocketChannel channel, Logger logger,
TrustStrategy trustStrategy )
throws GeneralSecurityException, IOException
{
logger.debug( "TLS connection enabled" );
this.logger = logger;
this.channel = channel;
this.channel.configureBlocking( true );

sslContext = new SSLContextFactory( host, port, authConfig ).create();
sslContext = new SSLContextFactory( host, port, trustStrategy, logger ).create();
createSSLEngine( host, port );
createBuffers();
runSSLHandShake();
runHandshake();
logger.debug( "TLS connection established" );
}

/** Used in internal tests only */
SSLSocketChannel( SocketChannel channel, Logger logger, SSLEngine sslEngine,
ByteBuffer plainIn, ByteBuffer cipherIn, ByteBuffer plainOut, ByteBuffer cipherOut )
TLSSocketChannel( SocketChannel channel, Logger logger, SSLEngine sslEngine,
ByteBuffer plainIn, ByteBuffer cipherIn, ByteBuffer plainOut, ByteBuffer cipherOut )
throws GeneralSecurityException, IOException
{
logger.debug( "Testing TLS buffers" );
Expand All @@ -109,7 +109,7 @@ public SSLSocketChannel( String host, int port, SocketChannel channel, Logger lo
*
* @throws IOException
*/
private void runSSLHandShake() throws IOException
private void runHandshake() throws IOException
{
sslEngine.beginHandshake();
HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,26 @@
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;

import org.neo4j.driver.internal.spi.Logger;
import org.neo4j.driver.internal.util.BytePrinter;

import static org.neo4j.driver.internal.util.CertificateTool.X509CertToString;

/**
* References:
* http://stackoverflow.com/questions/6802421/how-to-compare-distinct-implementations-of-java-security-cert-x509certificate?answertab=votes#tab-top
*/

class TrustOnFirstUseTrustManager implements X509TrustManager
{
/**
* A list of pairs (known_server, certificate) are stored in this file.
* When establishing a SSL connection to a new server, we will save the server's ip:port and its certificate in this
* A list of pairs (known_server certificate) are stored in this file.
* When establishing a SSL connection to a new server, we will save the server's host:port and its certificate in this
* file.
* Then when we try to connect to a known server again, we will authenticate the server by checking if it provides
* the same certificate as the one saved in this file.
Expand All @@ -50,15 +52,15 @@ class TrustOnFirstUseTrustManager implements X509TrustManager

/** The server ip:port (in digits) of the server that we are currently connected to */
private final String serverId;
private final Logger logger;

/** The known certificate we've registered for this server */
private String cert;
private String fingerprint;

TrustOnFirstUseTrustManager( String host, int port, File knownCerts ) throws IOException
TrustOnFirstUseTrustManager( String host, int port, File knownCerts, Logger logger ) throws IOException
{
String ip = InetAddress.getByName( host ).getHostAddress(); // localhost -> 127.0.0.1
this.serverId = ip + ":" + port;

this.logger = logger;
this.serverId = host + ":" + port;
this.knownCerts = knownCerts;
load();
}
Expand All @@ -76,16 +78,16 @@ private void load() throws IOException
}

BufferedReader reader = new BufferedReader( new FileReader( knownCerts ) );
String line = null;
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) && line.contains( "," ) )
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( "," );
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
cert = strings[1].trim();
fingerprint = strings[1].trim();
return;
}
}
Expand All @@ -96,16 +98,17 @@ private void load() throws IOException
/**
* Save a new (server_ip, cert) pair into knownCerts file
*
* @param cert
* @param fingerprint the SHA-512 fingerprint of the host certificate
*/
private void save( String cert ) throws IOException
private void saveTrustedHost( String fingerprint ) throws IOException
{
this.cert = cert;
this.fingerprint = fingerprint;

logger.warn( "Adding %s as known and trusted certificate for %s.", fingerprint, serverId );
createKnownCertFileIfNotExists();

BufferedWriter writer = new BufferedWriter( new FileWriter( knownCerts, true ) );
writer.write( serverId + "," + this.cert );
writer.write( serverId + " " + this.fingerprint );
writer.newLine();
writer.close();
}
Expand All @@ -126,15 +129,14 @@ public void checkServerTrusted( X509Certificate[] chain, String authType )
throws CertificateException
{
X509Certificate certificate = chain[0];
byte[] encoded = certificate.getEncoded();

String cert = DatatypeConverter.printBase64Binary( encoded );
String cert = fingerprint( certificate );

if ( this.cert == null )
if ( this.fingerprint == null )
{
try
{
save( cert );
saveTrustedHost( cert );
}
catch ( IOException e )
{
Expand All @@ -146,7 +148,7 @@ public void checkServerTrusted( X509Certificate[] chain, String authType )
}
else
{
if ( !this.cert.equals( cert ) )
if ( !this.fingerprint.equals( cert ) )
{
throw new CertificateException( String.format(
"Unable to connect to neo4j at `%s`, because the certificate the server uses has changed. " +
Expand All @@ -156,21 +158,47 @@ public void checkServerTrusted( X509Certificate[] chain, String authType )
"in the file `%s`.\n" +
"The old certificate saved in file is:\n%sThe New certificate received is:\n%s",
serverId, serverId, knownCerts.getAbsolutePath(),
X509CertToString( this.cert ), X509CertToString( cert ) ) );
X509CertToString( this.fingerprint ), X509CertToString( cert ) ) );
}
}
}

/**
* Calculate the certificate fingerprint - simply the SHA-512 hash of the DER-encoded certificate.
*/
public static String fingerprint( X509Certificate cert ) throws CertificateException
{
try
{
MessageDigest md = MessageDigest.getInstance( "SHA-512" );
md.update( cert.getEncoded() );
return BytePrinter.compactHex( md.digest() );
}
catch( NoSuchAlgorithmException e )
{
// SHA-1 not available
throw new CertificateException( "Cannot use TLS on this platform, because SHA-512 message digest algorithm is not available: " + e.getMessage(), e );
}
}

private File createKnownCertFileIfNotExists() throws IOException
{
if ( !knownCerts.exists() )
{
File parentDir = knownCerts.getParentFile();
if( parentDir != null && !parentDir.exists() )
{
parentDir.mkdirs();
if(!parentDir.mkdirs()) {
throw new IOException( "Failed to create directories for the known hosts file in " + knownCerts.getAbsolutePath() + ". This is usually " +
"because you do not have write permissions to the directory. Try configuring the Neo4j driver to use a file " +
"system location you do have write permissions to." );
}
}
if(!knownCerts.createNewFile()) {
throw new IOException( "Failed to create a known hosts file at " + knownCerts.getAbsolutePath() + ". This is usually " +
"because you do not have write permissions to the directory. Try configuring the Neo4j driver to use a file " +
"system location you do have write permissions to." );
}
knownCerts.createNewFile();
BufferedWriter writer = new BufferedWriter( new FileWriter( knownCerts ) );
writer.write( "# This file contains trusted certificates for Neo4j servers, it's created by Neo4j drivers." );
writer.newLine();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public void info( String message, Object... params )

}

@Override
public void warn( String message, Object... params )
{

}

@Override
public void debug( String message, Object... params )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public void info( String format, Object... params )
delegate.log( Level.INFO, String.format( format, params ) );
}

@Override
public void warn( String format, Object... params )
{
delegate.log( Level.WARNING, String.format( format, params ) );
}

@Override
public void debug( String format, Object... params )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public interface Logger

void info( String message, Object... params );

void warn( String message, Object... params );

void debug( String message, Object... params );

void trace( String message, Object... params );
Expand Down
Loading