Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 124B1B5DBD4 for ; Thu, 19 May 2011 03:16:34 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 51221-03 for ; Thu, 19 May 2011 06:16:19 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from atcmail.atc.tcs.com (atcmail.atc.tcs.co.in [203.200.212.145]) by mail.postgresql.org (Postfix) with ESMTP id 64F70B5DBDC for ; Thu, 19 May 2011 03:16:17 -0300 (ADT) Received: from [172.25.149.79] (marc.atc.tcs.com [172.25.149.79]) by atcmail.atc.tcs.com (8.13.8/8.13.8) with ESMTP id p4J6G8aB030848; Thu, 19 May 2011 11:46:08 +0530 Message-ID: <4DD4B535.1050707@atc.tcs.com> Date: Thu, 19 May 2011 11:44:13 +0530 From: =?ISO-8859-1?Q?Marc-Andr=E9_Laverdi=E8re?= User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110424 Thunderbird/3.1.10 MIME-Version: 1.0 To: Craig Ringer CC: Kris Jurka , pgsql-jdbc@postgresql.org Subject: Re: Support for cert auth in JDBC 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> <4DD4AED1.2080008@postnewspapers.com.au> In-Reply-To: <4DD4AED1.2080008@postnewspapers.com.au> Content-Type: multipart/mixed; boundary="------------010606090600030508090407" X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.9 tagged_above=-10 required=5 tests=BAYES_00=-1.9 X-Spam-Level: X-Archive-Number: 201105/56 X-Sequence-Number: 21886 This is a multi-part message in MIME format. --------------010606090600030508090407 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit 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 --------------010606090600030508090407 Content-Type: text/x-java; name="PostgreSQLCertConnTester.java" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="PostgreSQLCertConnTester.java" /*------------------------------------------------------------------------- * * 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()); } } } --------------010606090600030508090407 Content-Type: text/x-java; name="CertAuthFactory.java" Content-Transfer-Encoding: 8bit Content-Disposition: attachment; filename="CertAuthFactory.java" /*------------------------------------------------------------------------- * * 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: *
    *
  • (optional) org.postgresql.jdbc.keystore.path : the path to the keystore containing the client certificate *
  • (mandatory if previous is set) org.postgresql.jdbc.keystore.password : password for loading the keystore containing the client certificate *
  • (optional) org.postgresql.jdbc.truststore.path : 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. *
  • (mandatory if previous is set) org.postgresql.jdbc.truststore.password : the password to open the keystore containing the CA certificate(s) *
* @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; } } --------------010606090600030508090407--