Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id BB325B5DBEA for ; Thu, 19 May 2011 04:28:15 -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 58130-08 for ; Thu, 19 May 2011 07:28:07 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from www.postnewspapers.com.au (www.postnewspapers.com.au [173.230.139.50]) by mail.postgresql.org (Postfix) with ESMTP id A04E1B5DBC1 for ; Thu, 19 May 2011 04:28:07 -0300 (ADT) Received: from localhost (localhost [127.0.0.1]) by www.postnewspapers.com.au (Postfix) with ESMTP id 2B5134B9; Thu, 19 May 2011 03:28:07 -0400 (EDT) X-Virus-Scanned: amavisd-new at postnewspapers.com.au.com Received: from www.postnewspapers.com.au ([127.0.0.1]) by localhost (www.postnewspapers.com.au [127.0.0.1]) (amavisd-new, port 10024) with LMTP id HP-nc11T1JUg; Thu, 19 May 2011 03:28:05 -0400 (EDT) Received: from mail.postnewspapers.com.au (ppp171-128.static.internode.on.net [150.101.171.128]) by www.postnewspapers.com.au (Postfix) with ESMTP id 47B2927; Thu, 19 May 2011 03:28:05 -0400 (EDT) Received: from localhost (localhost [127.0.0.1]) by mail.postnewspapers.com.au (Postfix) with ESMTP id 41D94AE505; Thu, 19 May 2011 15:28:04 +0800 (WST) X-Virus-Scanned: Debian amavisd-new at postnewspapers.com.au Received: from mail.postnewspapers.com.au ([127.0.0.1]) by localhost (mail.postnewspapers.com.au [127.0.0.1]) (amavisd-new, port 10024) with LMTP id T7FTUxHZ33uT; Thu, 19 May 2011 15:27:57 +0800 (WST) Received: from [10.1.1.5] (124-169-254-58.dyn.iinet.net.au [124.169.254.58]) (using TLSv1 with cipher DHE-RSA-AES256-SHA (256/256 bits)) (Client CN "Craig Ringer", Issuer "POST Certificate Authority" (verified OK)) by mail.postnewspapers.com.au (Postfix) with ESMTPSA id B8070AE886; Thu, 19 May 2011 15:27:56 +0800 (WST) Message-ID: <4DD4C67B.5070809@postnewspapers.com.au> Date: Thu, 19 May 2011 15:27:55 +0800 From: Craig Ringer User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.17) Gecko/20110428 Fedora/3.1.10-1.fc14 Thunderbird/3.1.10 MIME-Version: 1.0 To: =?windows-1252?Q?Marc-Andr=E9_Laverdi=E8re?= CC: 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> <4DD4B187.6080002@postnewspapers.com.au> <4DD4BB85.4070300@atc.tcs.com> In-Reply-To: <4DD4BB85.4070300@atc.tcs.com> Content-Type: multipart/mixed; boundary="------------010307010702070702090509" X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201105/58 X-Sequence-Number: 21888 This is a multi-part message in MIME format. --------------010307010702070702090509 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 8bit Thanks for those changes. Comments follow. I'm attaching a further-tweaked version of the code you just sent. I only had to change AbstractCertAuthFactory, so the other files remain unaltered. Changes are: - Only attempt to autodetect keystore type when null keystore type was passed, instead of always accepting but ignoring the keystore type argument. - Make string constants private so nobody lands up relying on them so they can't be changed without breaking backward compat. - Make "internal helper only" methods private. If they're protected, they're API not internal helpers. Reasonable? See further comments inline below: On 05/19/2011 02:41 PM, Marc-André Laverdière wrote: > There was a tiny bug in SysPropCertAuthFactory whereas a path was sent > instead of a password. I'm attaching the fix. Whoops. Thanks. > 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. I thought it was, as much as already possible. What more would you move into AbstractCertAuthFactory ? Or do you want to create a single helper method that takes something like: initFactory( String ksPath, char[] ksPass, char[] keyPass, String tsPath, char[] tsPass) to reduce verbosity, one that uses the existing buildSSLSocketFactory(), createKeyManagers() and createTrustManagers() behind the scenes? To me, it seems a pretty small thing to have to call createKeyManagers and createTrustManagers and pass the args to buildSSLSocketFactory(...). I did intentionally move the checks for null/empty keystore path and truststore path out of AbstractCertAuthFactory and into SysPropCertAuthFactory. It's already possible to say "use system default" by passing null to buildSSLSocketFactory(...), so I don't think createKeyManagers(..) or createTrustManagers() should be making that decision implicitly for the caller. In security, it might be quite undesirable to have the app fail silently back to the system truststore - you might have good reasons to have specified your own. I can see that it's necessary to treat a missing key as "use default" when using system properties as a configuration mechanism, but don't think that should be an assumption that AbstractCertAuthFactory makes for all users of that code. > 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. JECKS is also common. I don't love this part - it's making assumptions that may not prove true in the long run, and IOException is a very broad exception to rely on to detect a very specific thing like wrong keystore format. It could potentially result in confusing error messages, too. For example, a corrupt or damaged JKS keystore might fail to load with an error reporting that a "pkcs12 keystore could not be read", causing the user to wonder why the S@#$@ the code was trying to read it as PKCS#12 and not identify the real problem, that it tried JKS first and failed because the keystore was damaged. It seems OK to me to attempt to auto-detect the keystore type when no keystore type is given. The code you posted _ignores_ the keystore type argument. If a non-null keystore type is passed it should be honoured, but if a null keystore type is passed then I think it's fine to try to detect it rather than blindly assuming KeyStore.getDefaultType() . -- Craig Ringer --------------010307010702070702090509 Content-Type: text/plain; name="AbstractCertAuthFactory.java" Content-Transfer-Encoding: 8bit Content-Disposition: attachment; filename="AbstractCertAuthFactory.java" /*------------------------------------------------------------------------- * * 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 must call buildSSLSocketFactory() at the end of their * constructors, and must 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"; private final static String KEYSTORE_TYPE_PKCS12 = "PKCS12"; private 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, auto-detection of store type is attempted. * @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 (keyPass == null) { keyPass = keyStorePass; } KeyStore ks = loadKeyStore(keyStorePath, keyPass, keyStoreType); 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, auto-detection of store type is attempted. * @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 KeyStore trustKs = loadKeyStore(trustStorePath, trustStorePass, trustStoreType); 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; } // Load a keystore at the path specified, trying to detect the keystore // type. JKS will be tried first, and PKCS12 if that fails. private static KeyStore loadKeyStore(String path, char[] password) throws IOException, GeneralSecurityException{ //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); } } // Load a keystore at the path specified, Attempting to auto-detect the type // if null is passed for type. private static KeyStore loadKeyStore(String path, char[] password, String type) throws IOException, GeneralSecurityException{ if (type == null) { return loadKeyStore(path, password); } else { return loadKeyStoreOfType(path, password, type); } } // // Helper used by loadKeyStore(...) to do the actual keystore loading work. // private static KeyStore loadKeyStoreOfType(String path, char[] password, String type) throws IOException, GeneralSecurityException{ // Load the keystore with the specified keystore type. if (path == null || "".equals(path)) throw new IllegalArgumentException("Path is empty or null"); if (password == null) throw new IllegalArgumentException("Password is null"); if (type == null) throw new IllegalArgumentException("KeyStore type must be non-null"); 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(); } } } } --------------010307010702070702090509--