pg.ddx.io  pgsql-jdbc@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Marc-André Laverdière <marc-andre@atc.tcs.com>
To: Craig Ringer <craig@postnewspapers.com.au>
Cc: Kris Jurka <books@ejurka.com>
Cc: pgsql-jdbc@postgresql.org
Subject: Re: Support for cert auth in JDBC
Date: Thu, 19 May 2011 11:44:13 +0530
Message-ID: <4DD4B535.1050707@atc.tcs.com> (raw)
In-Reply-To: <4DD4AED1.2080008@postnewspapers.com.au>
References: <4DD34FE5.3020609@atc.tcs.com>
	<4DD35BEA.3020902@postnewspapers.com.au>
	<4DD361CA.3070907@atc.tcs.com>
	<4DD36EFC.6070707@postnewspapers.com.au>
	<4DD379C5.1030703@atc.tcs.com>
	<4DD3C751.5080908@postnewspapers.com.au>
	<alpine.BSO.2.00.1105181130380.13086@leary.csoft.net>
	<4DD4AED1.2080008@postnewspapers.com.au>

Hi guys,

Here are some improvements based on the comments I saw so far.
I'm also adding a small cheapo tester. Definitely not JUnit-ready :)

Marc-André Laverdière
Software Security Scientist
Innovation Labs, Tata Consultancy Services
Hyderabad, India

On Thursday 19 May 2011 11:16 AM, Craig Ringer wrote:
> On 05/18/2011 11:32 PM, Kris Jurka wrote:
>>
>>
>> On Wed, 18 May 2011, Craig Ringer wrote:
>>
>>> Alas the SSLSocketFactory interface doesn't offer any really nice
>>> options like a way to pass a Properties instance to the ctor,
>>
>> That'd be an easy thing to fix, just add another case to
>> org.postgresql.ssl.MakeSSL#convert to pass through the provided
>> Properties object. I've thought about that in the past, but with no real
>> use case, I wasn't in a big rush to do so.
> 
> OK, good to know.
> 
> It wasn't a big issue for me in the end, as I landed up fetching my
> configuration using the String argument form as a key to an
> application-specific configuration provider. It's much easier to pass a
> String argument through various layers one often has over the JDBC
> driver, like an ORM or the like.
> 
> -- 
> Craig Ringer

Attachments:

PostgreSQLCertConnTester.java (text/x-java, 1.6K) download /*------------------------------------------------------------------------- * * Copyright (c) 2011, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.ssl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * * Quick and dirty tester for the cert auth factory * @author Marc-Andre Laverdiere * */ public class PostgreSQLCertConnTester { public static void main(String[] args) throws ClassNotFoundException, SQLException{ // ========== TODO TODO TODO Set those values as needed for your test final String userId = ""; //Set the properties System.setProperty(CertAuthFactory.CONFIG_KEYSTORE_PATH, ""); System.setProperty(CertAuthFactory.CONFIG_KEYSTORE_PWD, ""); System.setProperty(CertAuthFactory.CONFIG_TRUSTSTORE_PATH, ""); System.setProperty(CertAuthFactory.CONFIG_TRUSTSTORE_PWD, ""); // ============== End TODO section final String connUrl = "jdbc:postgresql://127.0.0.1:5432/postgres?ssl=true&sslfactory=org.postgresql.ssl.CertAuthFactory"; final String query = "select * from pg_largeobject"; Class.forName("org.postgresql.Driver"); Properties props = new Properties(); props.setProperty("user",userId);//it somehow picks my logged-in user here Connection conn = DriverManager.getConnection(connUrl,props); PreparedStatement stmt = conn.prepareStatement(query); stmt.execute(); ResultSet rs = stmt.getResultSet(); while(rs.next()){ System.out.println("Reading row #" + rs.getRow()); } } }
CertAuthFactory.java (text/x-java, 8.5K) download /*------------------------------------------------------------------------- * * Copyright (c) 2011, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.ssl; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.Properties; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; /** * Provide an implementation of SSLSocketFactory that allows client authentication * @author Marc-André Laverdière (marc-andre@atc.tcs.com / marcandre.laverdiere@tcs.com) */ public class CertAuthFactory extends SSLSocketFactory { // ---------------------------- Constants used internally public final static String CONFIG_KEYSTORE_PATH = "org.postgresql.jdbc.keystore.path"; public final static String CONFIG_KEYSTORE_PWD = "org.postgresql.jdbc.keystore.password"; public final static String CONFIG_TRUSTSTORE_PATH = "org.postgresql.jdbc.truststore.path"; public final static String CONFIG_TRUSTSTORE_PWD = "org.postgresql.jdbc.truststore.password"; public final static String SSL_PROTOCOL_NAME = "SSL"; public final static String TLS_PROTOCOL_NAME = "TLS"; public final static String SECURE_RANDOM_NAME = "SHA1PRNG"; public final static String KEYSTORE_TYPE_PKCS12 = "PKCS12"; public final static String KEYSTORE_TYPE_JKS = "JKS"; //------------------------------- Actual instance data protected final SSLSocketFactory _internalFactory; protected final boolean isUsingCertificateAuth; //------------------------------ Constructors public CertAuthFactory() throws IOException, GeneralSecurityException { this(System.getProperties()); } public CertAuthFactory(String ignored) throws IOException, GeneralSecurityException { this(System.getProperties()); } /** * Builds an SSLContext with the specified trust store and key store. * The parameters read are as follows: * <ul> * <li> (optional) <code>org.postgresql.jdbc.keystore.path</code> : the path to the keystore containing the client certificate * <li> (mandatory if previous is set) <code>org.postgresql.jdbc.keystore.password</code> : password for loading the keystore containing the client certificate * <li> (optional) <code>org.postgresql.jdbc.truststore.path</code> : keystore containing the CA certificate(s) that are trusted. * This should normally be the same CA as the one that signed the certificate of the server you would connect to. * <li> (mandatory if previous is set) <code>org.postgresql.jdbc.truststore.password</code> : the password to open the keystore containing the CA certificate(s) * </ul> * @param props the properties to load the configuration from. Must be non-null. * @return an SSLContext initialized based on those properties. * @throws IOException on any error loading the keystores * @throws GeneralSecurityException on keystore errors or crypto set-up errors */ public CertAuthFactory(Properties props) throws IOException, GeneralSecurityException { if (props == null) throw new IllegalArgumentException("Properties is null"); FileInputStream fInKeyStore = null; FileInputStream fInTrustStore = null; try{ //Load configuration String trustPath = props.getProperty(CONFIG_TRUSTSTORE_PATH); String trustPwd = props.getProperty(CONFIG_TRUSTSTORE_PWD); String keyPath = props.getProperty(CONFIG_KEYSTORE_PATH); String keyPwd = props.getProperty(CONFIG_KEYSTORE_PWD); KeyManagerFactory managerFactory = null; TrustManagerFactory trustFactory = null; if (keyPath != null && !"".equals(keyPath)){ if (keyPwd == null) throw new IllegalArgumentException("Keystore password must be specified"); //Load the Key Managers KeyStore ks = loadKeyStore(keyPath, keyPwd); managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); managerFactory.init(ks, keyPwd.toCharArray()); isUsingCertificateAuth = true; } else isUsingCertificateAuth = false; if (trustPath != null && !"".equals(trustPath)){ if (trustPwd == null) throw new IllegalArgumentException("Trust store password must be specified"); // Load the trust store KeyStore trustKs = loadKeyStore(trustPath, trustPwd); trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustKs); } //Create + Initialize TLS context SSLContext context = SSLContext.getInstance(SSL_PROTOCOL_NAME); //can be TLS too context.init(managerFactory.getKeyManagers(), trustFactory.getTrustManagers(), SecureRandom.getInstance(SECURE_RANDOM_NAME)); _internalFactory = context.getSocketFactory(); } finally{ try{ if (fInKeyStore != null) fInKeyStore.close(); if (fInTrustStore != null) fInTrustStore.close(); } catch (IOException e){ //ignore it } } } //------------------------- SSLSocketFactory API implementation @Override public Socket createSocket() throws IOException { SSLSocket sock = (SSLSocket) _internalFactory.createSocket(); return enableClientAuth(sock); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localhost, int localPort) throws IOException { SSLSocket sock = (SSLSocket) _internalFactory.createSocket(address, port, localhost, localPort); return enableClientAuth(sock); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { SSLSocket sock = (SSLSocket) _internalFactory.createSocket(host, port); return enableClientAuth(sock); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { SSLSocket sock = (SSLSocket) _internalFactory.createSocket(s, host, port, autoClose); return enableClientAuth(sock); } @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { SSLSocket sock = (SSLSocket) _internalFactory.createSocket(host, port); return enableClientAuth(sock); } @Override public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException { SSLSocket sock = (SSLSocket) _internalFactory.createSocket(host, port, localAddress, localPort); return enableClientAuth(sock); } @Override public String[] getDefaultCipherSuites() { return _internalFactory.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return _internalFactory.getSupportedCipherSuites(); } // -------------------------------------- Internal Helper Methods /** * Load a keystore at the path specified. It will try both JKS and PKCS12 keystores * @param path the path to the keystore * @param password the keystore password * */ protected static KeyStore loadKeyStore(String path, String password) throws IOException, GeneralSecurityException{ if (path == null || "".equals(path)) throw new IllegalArgumentException("Path is empty or null"); if (password == null) throw new IllegalArgumentException("Password is null"); //first try with JKS try{ return loadKeyStore(path, password, KEYSTORE_TYPE_JKS); } catch (IOException e){ //docs say that this is what is loaded if the file format is wrong //try loading PKCS instead return loadKeyStore(path, password, KEYSTORE_TYPE_PKCS12); } } /** * Tries to open a keystore of the given type * @param path the path to the keystore * @param password the keystore password * @param type the keystore type * @return a valid keystore * @throws IOException If there is any error loading the keystore * @throws GeneralSecurityException if the certificates cannot be loaded or the type specified is invalid */ protected static KeyStore loadKeyStore(String path, String password, String type) throws IOException, GeneralSecurityException{ FileInputStream fIn = null; try{ KeyStore ks = KeyStore.getInstance(type); fIn = new FileInputStream(path); ks.load(fIn, password.toCharArray()); return ks; } finally{ if (fIn != null) fIn.close(); } } /** * Enables the client mode and the client authentication (if a certificate was loaded) * on the socket * */ protected SSLSocket enableClientAuth(SSLSocket sock){ sock.setNeedClientAuth(isUsingCertificateAuth); sock.setUseClientMode(true); return sock; } }

view thread (28+ messages)  latest in thread

Message-ID: <4DD4B535.1050707@atc.tcs.com>
Permalink:  ../4DD4B535.1050707@atc.tcs.com/
Also on:    postgresql.org/message-id/4DD4B535.1050707@atc.tcs.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-jdbc@postgresql.org
  Cc: marc-andre@atc.tcs.com, craig@postnewspapers.com.au, books@ejurka.com
  Subject: Re: Support for cert auth in JDBC
  In-Reply-To: <4DD4B535.1050707@atc.tcs.com>
  References: <4DD34FE5.3020609@atc.tcs.com> <4DD35BEA.3020902@postnewspapers.com.au> <4DD361CA.3070907@atc.tcs.com> <4DD36EFC.6070707@postnewspapers.com.au> <4DD379C5.1030703@atc.tcs.com> <4DD3C751.5080908@postnewspapers.com.au> <alpine.BSO.2.00.1105181130380.13086@leary.csoft.net> <4DD4AED1.2080008@postnewspapers.com.au> <4DD4B535.1050707@atc.tcs.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox