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: pgsql-jdbc@postgresql.org
Subject: Re: Support for cert auth in JDBC
Date: Thu, 19 May 2011 12:11:09 +0530
Message-ID: <4DD4BB85.4070300@atc.tcs.com> (raw)
In-Reply-To: <4DD4B187.6080002@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>
	<4DD4B187.6080002@postnewspapers.com.au>

Hello,

Thanks for the changes. It is a good step forward in terms of
extensibility. That being said, I think we could just put a lot of the
loading code in AbstractCertAuthFactory, so that it is more reusable.

There was a tiny bug in SysPropCertAuthFactory whereas a path was sent
instead of a password. I'm attaching the fix.

I also added the code that allows to load both PKCS12 and JKS blindly. I
think that we can remove the property for specifying the type. I  doubt
we have to worry about other types of keystores than those two.

I'm also adding the slightly modified tester which uses the right class.

Regards,

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

On Thursday 19 May 2011 11:28 AM, Craig Ringer wrote:
> On 05/18/2011 03:48 PM, Marc-André Laverdière wrote:
>> It is true that anyone who knows the right Java APIs can put that
>> factory together with little pain. I just think that the average user
>> shouldn't have to bother about it.
>>
>> Also, some use cases do not allow to use the default keystore and trust
>> store for everything.
> 
> I agree, and I think you're right that the PgJDBC  code should have a
> re-usable class to provide support for these use cases without everyone
> having to code their own.
> 
> I've taken your code and re-worked it a bit to:
> 
> - Use the PgJDBC WrappedFactory rather than re-implementing an
>   effectively identical one;
> 
> - Separate the basic construction process of the SSLSocketFactory
>   from its configuration, providing an abstract superclass that does
>   the construction via a few simple method calls, so someone who needs
>   different configuration sources/methods can re-use the code;
> 
> - Provided a concrete subclass of the above that gets its configuration
>   from system properties and uses the superclass methods to construct
>   the factory. This class has the same functionality as what you posted
>   originally plus a few additional configuration options for additional
>   use cases like non-default KeyStore types (pkcs12 etc); and
> 
> - Added more extensive JavaDoc
> 
> It's also possible to pass your own KeyStore and/or TrustStore instances
> directly if your app has to do something funky like manage an in-memory
> KeyStore.
> 
> What I haven't done yet is tested it! This is a preview so you can
> comment on it and tell me if you think I've gone completely off the
> rails or not.
> 
> The simplest uses of the code remain as simple as they were with your
> original version. You just set some system properties and specify
> SysPropCertAuthFactory as the sslsocketfactory class. More complex use
> cases become possible without having to re-implement the whole lot - in
> particular, if you can't fetch your configuration from system properties
> you can provide alternative mechanisms to look it up without having to
> re-write all the JSSE crap.
> 
> So: thanks VERY much for posting this code. My original demos weren't
> flexible enough to be included in PgJDBC, and by posting this you really
> helped motivate me to try to turn your code and my original demoes into
> something that _was_.
> 
> What do you think? Note that you'll need PgJDBC on your classpath to
> complile this now, because it uses org.postgresql.ssl.WrappedFactory  .
> 
> -- 
> Craig Ringer

Attachments:

PostgreSQLCertConnTester.java (text/x-java, 1.7K) 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(SysPropCertAuthFactory.CONFIG_KEYSTORE_PATH, ""); System.setProperty(SysPropCertAuthFactory.CONFIG_KEYSTORE_PWD, ""); System.setProperty(SysPropCertAuthFactory.CONFIG_TRUSTSTORE_PATH, ""); System.setProperty(SysPropCertAuthFactory.CONFIG_TRUSTSTORE_PWD, ""); // ============== End TODO section final String connUrl = "jdbc:postgresql://127.0.0.1:5432/postgres?ssl=true&sslfactory=org.postgresql.ssl.SysPropCertAuthFactory"; 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()); } } }
SysPropCertAuthFactory.java (text/x-java, 5.6K) download /*------------------------------------------------------------------------- * * Copyright (c) 2011, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.ssl; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.SecureRandom; import javax.net.ssl.KeyManager; import javax.net.ssl.TrustManager; /** * A CertAuthFactory that's configured using system properties, much like * (but independent from) the stock javax.net.ssl SSLSocketFactory implementation. */ public class SysPropCertAuthFactory extends AbstractCertAuthFactory { /** * File-system path to the keystore file to load, or null for system default keystore. * * May be the set to the same path as CONFIG_TRUSTSTORE_PATH if trust and key material are * in the same store. */ public final static String CONFIG_KEYSTORE_PATH = "org.postgresql.jdbc.keystore.path"; /** * Password to use to decode keystore. Ignored if CONFIG_KEYSTORE_PATH unset. */ public final static String CONFIG_KEYSTORE_PWD = "org.postgresql.jdbc.keystore.password"; /** * Password to use to decode keys within keystore. If unset, CONFIG_KEYSTORE_PWD used. * In most cases the KeyStore password is the same as the key password, so this may be * left unset. */ public final static String CONFIG_KEYSTORE_KEYPWD = "org.postgresql.jdbc.keystore.keypassword"; /** * KeyStore type, a JSSE KeyStore type name like JKS, JECKS, pkcs12, etc. Ignored if CONFIG_KEYSTORE_PATH unset. * * JECKS is the usual format used to store private keys with keytool, etc. */ public final static String CONFIG_KEYSTORE_TYPE = "org.postgresql.jdbc.keystore.type"; /** * File system path to the trust store file to load, or null for the system default trust store. * * May be the same path as CONFIG_KEYSTORE_PATH if trust and key material are * in the same store. * * The default Sun JDK trustStore is a JKS format store with password "changeme". * If you wish to use the system-default list of trusted signers, rather than * specifying the location, type, and password of the system default truststore * you should leave CONFIG_TRUSTSTORE_PATH unset so the system default truststore * is automatically loaded for you. */ public final static String CONFIG_TRUSTSTORE_PATH = "org.postgresql.jdbc.truststore.path"; /** * Password used to decode the truststore. Ignored if CONFIG_TRUSTSTORE_PATH unset. */ public final static String CONFIG_TRUSTSTORE_PWD = "org.postgresql.jdbc.truststore.password"; /** * TrustStore type. Just like CONFIG_KEYSTORE_TYPE, but for the TrustStore. * * If the TrustStore is not the same store as the KeyStore, it is common * to use the JKS format for it rather than the JECKS format usually used * for KeyStores and for combined TrustStore/KeyStores. */ public final static String CONFIG_TRUSTSTORE_TYPE = "org.postgresql.jdbc.truststore.type"; /** * The secure random algorithm to use. It is unlikely that you will need to change * this, but support for doing so is provided for completeness. */ public final static String CONFIG_SECURERANDOM = "org.postgresql.jdbc.securerandom"; public SysPropCertAuthFactory() throws IOException, GeneralSecurityException { super(); // Load configuration. First, configure and create the key manager: KeyManager[] keyManagers = null; String keyStorePath = System.getProperty(CONFIG_KEYSTORE_PATH); if (keyStorePath != null && !keyStorePath.isEmpty()) { // If only a keystore passphrase is specified but no // key passphrase is given, use the keystore passphrase for both the keystore // and the key. char[] keyStorePass = null, keyPass = null; String ksp = System.getProperty(CONFIG_KEYSTORE_PWD, null); if (ksp != null) { keyStorePass = ksp.toCharArray(); keyPass = keyStorePass; } String kp = System.getProperty(CONFIG_KEYSTORE_KEYPWD, null); if (kp != null) { keyPass = kp.toCharArray(); } keyManagers = createKeyManagers( keyStorePath, keyStorePass, keyPass, System.getProperty(CONFIG_KEYSTORE_TYPE, null)); } // then create the trust manager TrustManager[] trustManagers = null; String trustStorePath = System.getProperty(CONFIG_TRUSTSTORE_PATH); if (trustStorePath != null && !trustStorePath.isEmpty()) { char[] trustStorePass = null; String tsp = System.getProperty(CONFIG_TRUSTSTORE_PWD, null); if (tsp != null) { trustStorePass = tsp.toCharArray(); } trustManagers = createTrustManagers( trustStorePath, trustStorePass, System.getProperty(CONFIG_TRUSTSTORE_TYPE)); } // and SecureRandom instance if configured SecureRandom secureRandom = null; String secureRandomAlgo = System.getProperty(CONFIG_SECURERANDOM); if (secureRandomAlgo != null) { secureRandom = SecureRandom.getInstance(secureRandomAlgo); } // Finally, configure the factory. buildSSLSocketFactory(keyManagers, trustManagers, secureRandom); } public SysPropCertAuthFactory(String ignored) throws IOException, GeneralSecurityException { this(); } }
AbstractCertAuthFactory.java (text/x-java, 8.3K) download /*------------------------------------------------------------------------- * * Copyright (c) 2011, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.ssl; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; /** * Provide an implementation of SSLSocketFactory that allows client authentication. * * This code creates and wraps a SSLSocketFactory using the paths and passwords * obtained from calls to abstract methods that must be defined by a subclass. * You cannot use this class as-is. See SysPropCertAuthFactory for one you can * use unmodified. * * Subclasses <b>must</b> call buildSSLSocketFactory() at the end of their * constructors, and <b>must</b> call the superclass constructors at the beginning * of their constructors. Subclasses must also implement the abstract methods * so that appropriate configuration details are returned. * * @author Marc-André Laverdière (marc-andre@atc.tcs.com / marcandre.laverdiere@tcs.com) */ //// //// TODO: Delegate trust checks to system trustmanager if //// no match in our own trustmanager? //// //// TODO: way to override keymanager/trustmanager supply without //// haivng to override those abstracts? public abstract class AbstractCertAuthFactory extends WrappedFactory { protected final static String DEFAULT_SSL_PROTOCOL_NAME = "SSL"; public final static String KEYSTORE_TYPE_PKCS12 = "PKCS12"; public final static String KEYSTORE_TYPE_JKS = "JKS"; protected AbstractCertAuthFactory() { } protected AbstractCertAuthFactory(String ignored) { } /** * Builds an SSLContext with a trust store and key store constructed * using the parameters provided by the subclass's implementation of * AbstractCertAuthFactory's abstract methods. * * If a null value is passed for any argument, the system default will * be used. For example, a null keyManagers array will cause * the SSLSocketFactory to use an SSLContext with a system-default KeyStore. * On the Sun JRE, this is created using the JSSE javax.net.ssl system * properties. Similar rules apply for the TrustStore and SecureRandom instance. * * See http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html . * * @param keyManagers KeyManager(s) to obtain key material from, or null for JSSE default keystore * @param trustManagers TrustManager(s) to obtain trust material from, or null for JSSE default truststore * @param secureRandom Secure random generator. Unless you know you need to do otherwise, leave this null to use the default. * */ protected void buildSSLSocketFactory(KeyManager[] keyManagers, TrustManager[] trustManagers, SecureRandom secureRandom) throws IOException, GeneralSecurityException{ if (_factory != null) { throw new IllegalStateException("buildSSLSocketFactory() already called!"); } //Create + Initialize TLS context SSLContext context = SSLContext.getInstance(getSSLProtocolName()); context.init(keyManagers, trustManagers, secureRandom); _factory = context.getSocketFactory(); } /** * Create and return KeyManager(s) using the passed information. * * If keyStoreType is null, the default keystore type for the system default * JSSE provider will be used. If the keyPass is null, the keyStorePass will * also be used to decode the key. No other arguments may be null. * * @param keyStorePath Location of keystore on file system. Non-null. * @param keyStorePass Password/passphrase to decrypt keystore with. Non-null. * @param keyPass Password/passphrase to decrypt key(s) of interest within KeyStore with. If null, keyStorePass used. * @param keyStoreType JSSE keystore type. If null, JSSE provider default is used. * @return KeyStore(s) created * @throws IOException if the KeyStore could not be read * @throws GeneralSecurityException (subtypes of) for most crypto errors, passphrase errors, etc. */ protected KeyManager[] createKeyManagers(String keyStorePath, char[] keyStorePass, char[] keyPass, String keyStoreType) throws IOException, GeneralSecurityException { //Load the Key Managers if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } if (keyPass == null) { keyPass = keyStorePass; } KeyStore ks = loadKeyStore(keyStorePath, keyStorePass); KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); managerFactory.init(ks, keyPass); return managerFactory.getKeyManagers(); } /** * Create and return TrustManager(s) using the passed information. * * If trustStoreType is null, the JSSE default keystore type is used. * No other arguments may be null. * * If you want to use the Java default truststore, do not call this method * at all. Just pass a null TrustManager[] as the trustManagers argument to * buildSSLSocketFactory(...). * * @param trustStorePath Location of trust store on file system. Non-null. * @param trustStorePass Password to decrypt truststore. * @param trustStoreType JSSE TrustStore type. If null, default JSSE keystore type is used. * @return TrustStore(s) created * @throws IOException If the TrustStore cannot be read * @throws GeneralSecurityException (subtypes of) for most crypto errors, password errors, etc. */ protected TrustManager[] createTrustManagers(String trustStorePath, char[] trustStorePass, String trustStoreType) throws IOException, GeneralSecurityException { // Load the trust store if (trustStoreType == null) { trustStoreType = KeyStore.getDefaultType(); } KeyStore trustKs = loadKeyStore(trustStorePath, trustStorePass); TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustKs); return trustFactory.getTrustManagers(); } /** * If you wish to override SSL protocol selection, you may do so by * overriding this method. The defualt simply returns * AbstractCertAuthFactory.DEFAULT_SSL_PROTOCOL_NAME . * . * @return JSSE ssl/tls protocol name AbstractCertAuthFactory.DEFAULT_SSL_PROTOCOL_NAME */ protected String getSSLProtocolName() { return DEFAULT_SSL_PROTOCOL_NAME; } // -------------------------------------- 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, char[] 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, char[] password, String type) throws IOException, GeneralSecurityException{ FileInputStream fIn = null; try{ KeyStore ks = KeyStore.getInstance(type); fIn = new FileInputStream(path); ks.load(fIn, password); return ks; } finally{ if (fIn != null) fIn.close(); } } }

view thread (28+ messages)  latest in thread

Message-ID: <4DD4BB85.4070300@atc.tcs.com>
Permalink:  ../4DD4BB85.4070300@atc.tcs.com/
Also on:    postgresql.org/message-id/4DD4BB85.4070300@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
  Subject: Re: Support for cert auth in JDBC
  In-Reply-To: <4DD4BB85.4070300@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> <4DD4B187.6080002@postnewspapers.com.au> <4DD4BB85.4070300@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