Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 37580B5DBD8 for ; Tue, 16 Aug 2011 18:03:58 -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 90867-03 for ; Tue, 16 Aug 2011 21:03:49 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from mail-fx0-f46.google.com (mail-fx0-f46.google.com [209.85.161.46]) by mail.postgresql.org (Postfix) with ESMTP id 526F9B5DBEE for ; Tue, 16 Aug 2011 18:03:47 -0300 (ADT) Received: by fxh19 with SMTP id 19so241705fxh.19 for ; Tue, 16 Aug 2011 14:03:47 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=message-id:date:from:user-agent:mime-version:to:subject :content-type; bh=jwQk35q+5kS8NU0xzKS8JlV/sSz+AVDyvqsW50aw4qI=; b=mTdUz04RRz9b8bwEUHgay0hS2hISbKI6i6Rt5ulixec0Qv/O8t3Pl+Wji0zMvSPLn+ 9Ubxsnh7gXxZTiSNApaVVAvn2+69Y2pJuHTnRQ8TQ5IPL34OnLBuleaAbLKNjvw1kuaS BDhRhDp6DCbJKq7F9tHChWTNiqI85bEWtihLM= Received: by 10.223.74.10 with SMTP id s10mr225817faj.73.1313528627088; Tue, 16 Aug 2011 14:03:47 -0700 (PDT) Received: from [188.143.43.107] (188-143-43-107.pool.digikabel.hu [188.143.43.107]) by mx.google.com with ESMTPS id j23sm338945faa.22.2011.08.16.14.03.44 (version=SSLv3 cipher=OTHER); Tue, 16 Aug 2011 14:03:45 -0700 (PDT) Message-ID: <4E4ADB2A.5040902@gmail.com> Date: Tue, 16 Aug 2011 23:03:38 +0200 From: Bodor Andras User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.16) Gecko/20101123 SeaMonkey/2.0.11 MIME-Version: 1.0 To: pgsql-jdbc@postgresql.org Subject: Re: JDBC SSL hostname verification Content-Type: multipart/mixed; boundary="------------010003020903030608070807" X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.789 tagged_above=-10 required=5 tests=BAYES_00=-1.9, FREEMAIL_ENVFROM_END_DIGIT=0.1, FREEMAIL_FROM=0.001, T_TO_NO_BRKTS_FREEMAIL=0.01 X-Spam-Level: X-Archive-Number: 201108/40 X-Sequence-Number: 22072 This is a multi-part message in MIME format. --------------010003020903030608070807 Content-Type: text/plain; charset=ISO-8859-2; format=flowed Content-Transfer-Encoding: 7bit Dear Jdbc developers! Recently Bruno Harbulot sent in a patch, that handles hostname verification for ssl connection. Let me send a tentative patch, that may treat the ssl connections close to that implemeted in libpg. A few more connection properties are introduced these are: -sslmode: similar to the libpg parameter, the allowed values are disable, allow, prefer, require, verify-ca, verify-full The parameter ssl should be made deprecated, as sslmode can cover all the possibilities. In my patch ssl=true is still necessary, to start ssl, then only require, verify-ca and verify-full behave correctly. (In case of verify-full, the Common name must match the hostname, or a leading * can match anything except a dot.) -sslcert,sslkey,sslrootcert: these are the locations of the client certificate, client key, and server certificate. (CRLs ar not implemeted yet.) Surprisingly, java can read openssl certificates without any modification, but the key must be converted to pkcs8 format: openssl pkcs8 -topk8 -in client.key -out client.pk8 -outform DER -v1 PBE-MD5-DES the ciphers, recognized by java are PBE-MD5-DES, PBE-SHA1-3DES, PBE-SHA1-RC2-40, or with the -nocrypt switch, it can be unencrypted. If any of these parameters is missing, the default locations are looked up (in $HOME/.postgresql). -sslpassword: the password for the ssl key (different from the database password) -sslpasswordcallback: a class, implementing javax.security.auth.callback.CallbackHandler that can handle PassworCallback for the ssl password. If set, sslpassword is ignored. The supplied class must have either a constructor with a Properties argument where the connection info properties are given, or a zero argument constructor If neither sslpassword nor sslpasswordcallback is set, and the key is protected, the user is prompted at the console for a password -sslhostnameverifier: a class, implementing javax.net.ssl.HostnameVerifier that can verify the server. The supplied class must have either a constructor with a Properties argument where the connection info properties are given, or a zero argument constructor. If set the server hostname is verified irrespective of the value of sslmode. (This behaivor is to be discussed.) -sslfactory: this parameter is modified slightly. The supplied class can also have a constructor with a Properties argument. In this case sslfactoryarg is ignored. If set, then the supplied factory class is wholly responsible for the SSL connection, but the hostname verification is still handled by the sslhostnameverifier class if supplied. Attached are the patch to MakeSSL.java, and two new classes, org.postgresql.ssl.LazyKeyManager and org.postgresql.ssl.LibPQFactory. Sincerely Yours Andras --------------010003020903030608070807 Content-Type: text/x-diff; name="MakeSSL.patch" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="MakeSSL.patch" 12d11 < import java.util.Properties; 14d12 < import java.net.Socket; 15a14,19 > import java.lang.reflect.InvocationTargetException; > import java.util.Properties; > > import javax.net.ssl.HostnameVerifier; > import javax.net.ssl.SSLPeerUnverifiedException; > import javax.net.ssl.SSLSocket; 18d21 < import org.postgresql.core.PGStream; 19a23 > import org.postgresql.core.PGStream; 21d24 < import org.postgresql.util.PSQLState; 22a26 > import org.postgresql.util.PSQLState; 24a29,64 > > public static Object instantiate(String classname, Properties info, boolean tryString, String stringarg) > throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, > InstantiationException, IllegalAccessException, InvocationTargetException > { > Object[] args = {info}; > Constructor ctor = null; > Class cls; > cls = Class.forName(classname); > try > { > ctor = cls.getConstructor(new Class[]{Properties.class}); > } > catch (NoSuchMethodException nsme) > { > if (tryString) > { > try > { > ctor = cls.getConstructor(new Class[]{String.class}); > args = new String[]{stringarg}; > } > catch (NoSuchMethodException nsme2) > { > tryString = false; > } > } > if (!tryString) > { > ctor = cls.getConstructor((Class[])null); > args = null; > } > } > return ctor.newInstance(args); > } > 29a70 > String sslmode = info.getProperty("sslmode"); 31c72 < // --- > // unless sslmode is set 34a76,82 > //If sslmode is set, use the libpg compatible factory > if (sslmode!=null) > { > factory = new LibPQFactory(info); > } > else > { 35a84 > } 39,42d87 < Object[] args = {info.getProperty("sslfactoryarg")}; < Constructor ctor; < Class factoryClass; < 45,55c90 < factoryClass = Class.forName(classname); < try < { < ctor = factoryClass.getConstructor(new Class[]{String.class}); < } < catch (NoSuchMethodException nsme) < { < ctor = factoryClass.getConstructor((Class[])null); < args = null; < } < factory = (SSLSocketFactory)ctor.newInstance(args); --- > factory = (SSLSocketFactory)instantiate(classname, info, true, info.getProperty("sslfactoryarg")); 63c98,130 < Socket newConnection = factory.createSocket(stream.getSocket(), stream.getHost(), stream.getPort(), true); --- > SSLSocket newConnection = (SSLSocket)factory.createSocket(stream.getSocket(), stream.getHost(), stream.getPort(), true); > if (!newConnection.getSession().isValid()) > { //The connection is not valid, throw any KeyManager exception. > if (factory instanceof LibPQFactory) > { > ((LibPQFactory)factory).throwKeyManagerException(); > } > } > > String sslhostnameverifier = info.getProperty("sslhostnameverifier"); > if (sslhostnameverifier!=null) > { > HostnameVerifier hvn; > try > { > hvn = (HostnameVerifier)instantiate(sslhostnameverifier, info, false, null); > } > catch (Exception e) > { > throw new PSQLException(GT.tr("The HostnameVerifier class provided {0} could not be instantiated.", sslhostnameverifier), PSQLState.CONNECTION_FAILURE, e); > } > if (!hvn.verify(stream.getHost(), newConnection.getSession())) > { > throw new PSQLException(GT.tr("The hostname {0} could not be verified by hostnameverifier {1}.", new Object[]{stream.getHost(), sslhostnameverifier}), PSQLState.CONNECTION_FAILURE); > } > } > else if ("verify-full".equals(sslmode)) > { > if (!((LibPQFactory)factory).verify(stream.getHost(), newConnection.getSession())) > { > throw new PSQLException(GT.tr("The hostname {0} could not be verified.", stream.getHost()), PSQLState.CONNECTION_FAILURE); > } > } --------------010003020903030608070807 Content-Type: text/x-java; name="LazyKeyManager.java" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="LazyKeyManager.java" package org.postgresql.ssl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.Socket; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Collection; import javax.crypto.Cipher; import javax.crypto.EncryptedPrivateKeyInfo; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.net.ssl.X509KeyManager; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; /** * A Key manager that only loads the keys, if necessary. * @author bodri * */ public class LazyKeyManager implements X509KeyManager { private X509Certificate[] cert = null; private PrivateKey key = null; private String certfile; private String keyfile; private CallbackHandler cbh; private PSQLException error = null; public LazyKeyManager(String certfile, String keyfile, CallbackHandler cbh) { this.certfile = certfile; this.keyfile = keyfile; this.cbh = cbh; } /** * getCertificateChain and getPrivateKey cannot throw exeptions, * therefore any exception is stored in this.error and can be raised * by this method * @throws PSQLException */ public void throwKeyManagerException() throws PSQLException { if (error!=null) throw error; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return "user"; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return "server"; } @Override public X509Certificate[] getCertificateChain(String alias) { if (cert==null) { //The certificate must be loaded CertificateFactory cf; try { cf = CertificateFactory.getInstance("X.509"); } catch (CertificateException ex) { //For some strange reason it throws CertificateException instead of NoSuchAlgorithmException... error = new PSQLException(GT.tr("Could not find a java cryptographic algorithm: X.509 CertificateFactory not available.", null), PSQLState.CONNECTION_FAILURE, ex); return null; } Collection certs; try { certs = cf.generateCertificates(new FileInputStream(certfile)); } catch (FileNotFoundException ioex) { error = new PSQLException(GT.tr("Could not open SSL certificate file {0}.", new Object[]{certfile}), PSQLState.CONNECTION_FAILURE, ioex); return null; }catch (CertificateException gsex) { error = new PSQLException(GT.tr("Loading the SSL certificate {0} into a KeyManager failed.", new Object[]{certfile}), PSQLState.CONNECTION_FAILURE, gsex); return null; } cert = (X509Certificate[]) certs.toArray(new X509Certificate[certs.size()]); } return cert; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { return new String[]{"user"}; } @Override public PrivateKey getPrivateKey(String alias) { try { if (key==null) { //The private key must be loaded if (cert==null) { //We need the certificate for the algorithm getCertificateChain("user"); } File keyf = new File(keyfile); FileInputStream fl = new FileInputStream(keyfile); byte[] keydata = new byte[(int)keyf.length()]; fl.read ( keydata, 0, (int)keyf.length() ); fl.close(); KeyFactory kf = KeyFactory.getInstance(cert[0].getPublicKey().getAlgorithm()); try { KeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec (keydata); key = kf.generatePrivate (pkcs8KeySpec); } catch (InvalidKeySpecException ex) //The key might be password protected { EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(keydata); Cipher cipher; try { cipher = Cipher.getInstance(ePKInfo.getAlgName()); } catch (NoSuchPaddingException npex) { //Why is it not a subclass of NoSuchAlgorithmException? throw new NoSuchAlgorithmException(npex.getMessage(),npex); } //We call back for the password PasswordCallback pwdcb = new PasswordCallback(GT.tr("Enter SSL password: "), false); try { cbh.handle(new Callback[]{pwdcb}); } catch (UnsupportedCallbackException ucex) { if ((cbh instanceof LibPQFactory.ConsoleCallbackHandler) && ("Console is not available".equals(ucex.getMessage()))) { error = new PSQLException(GT.tr("Could not read password for SSL key file, console is not available.", null), PSQLState.CONNECTION_FAILURE, ucex); } else { error = new PSQLException(GT.tr("Could not read password for SSL key file by callbackhandler {0}.", new Object[]{cbh.getClass().getName()}), PSQLState.CONNECTION_FAILURE, ucex); } return null; } try { PBEKeySpec pbeKeySpec = new PBEKeySpec(pwdcb.getPassword()); // Now create the Key from the PBEKeySpec SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo.getAlgName()); Key pbeKey = skFac.generateSecret(pbeKeySpec); // Extract the iteration count and the salt AlgorithmParameters algParams = ePKInfo.getAlgParameters(); cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams); // Decrypt the encryped private key into a PKCS8EncodedKeySpec KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher); key = kf.generatePrivate (pkcs8KeySpec); } catch (GeneralSecurityException ikex) { error = new PSQLException(GT.tr("Could not decrypt SSL key file {0}.", new Object[]{keyfile}), PSQLState.CONNECTION_FAILURE, ikex); return null; } } } } catch (IOException ioex) { error = new PSQLException(GT.tr("Could not read SSL key file {0}.", new Object[]{keyfile}), PSQLState.CONNECTION_FAILURE, ioex); return null; } catch(NoSuchAlgorithmException ex) { error = new PSQLException(GT.tr("Could not find a java cryptographic algorithm: {0}.", new Object[]{ex.getMessage()}), PSQLState.CONNECTION_FAILURE, ex); return null; } return key; } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { return new String[]{"server"}; } } --------------010003020903030608070807 Content-Type: text/x-java; name="LibPQFactory.java" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="LibPQFactory.java" /*------------------------------------------------------------------------- * * Copyright (c) 2004-2008, PostgreSQL Global Development Group * * IDENTIFICATION * $PostgreSQL: pgjdbc/org/postgresql/ssl/NonValidatingFactory.java,v 1.8 2008/01/08 06:56:30 jurka Exp $ * *------------------------------------------------------------------------- */ package org.postgresql.ssl; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Collection; import java.util.Properties; import javax.crypto.Cipher; import javax.crypto.EncryptedPrivateKeyInfo; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.x500.X500Principal; import org.postgresql.ssl.NonValidatingFactory.NonValidatingTM; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; /** * Provide an SSLSocketFactory that is compatible with the libpq * behaviour. */ public class LibPQFactory extends WrappedFactory implements HostnameVerifier { LazyKeyManager km = null; /** * * @param info the connection parameters * The following parameters are used: * sslmode,sslcert,sslkey,sslrootcert,sslhostnameverifier,sslpasswordcallback,sslpassword * @throws GeneralSecurityException * @throws IOException * @throws UnsupportedCallbackException */ public LibPQFactory(Properties info) throws PSQLException { try { SSLContext ctx = SSLContext.getInstance("TLS"); // or "SSL" ? //Determinig the default file location String pathsep = System.getProperty("path.separator"); String defaultdir; if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) { //It is Windows defaultdir = System.getenv("APPDATA")+pathsep+"postgresql"+pathsep; } else { defaultdir = System.getProperty("user.home")+pathsep+".postgresql"+pathsep; } //Load the client's certificate and key String sslcertfile = info.getProperty("sslcert"); if (sslcertfile == null) { //Fall back to default sslcertfile = defaultdir + "postgresql.crt"; } String sslkeyfile = info.getProperty("sslkey"); if (sslkeyfile == null) { //Fall back to default sslkeyfile = defaultdir + "postgresql.key"; } //Determine the callback handler CallbackHandler cbh; String sslpasswordcallback = info.getProperty("sslpasswordcallback"); if (sslpasswordcallback != null) { try { cbh = (CallbackHandler)MakeSSL.instantiate(sslpasswordcallback, info, false, null); } catch (Exception e) { throw new PSQLException(GT.tr("The password callback class provided {0} could not be instantiated.", sslpasswordcallback), PSQLState.CONNECTION_FAILURE, e); } } else { cbh = new ConsoleCallbackHandler(info.getProperty("sslpassword")); } km = new LazyKeyManager(sslcertfile, sslkeyfile, cbh); TrustManager[] tm; String sslmode = info.getProperty("sslmode"); if("verify-ca".equals(sslmode) || "verify-full".equals(sslmode)) { //Load the server certificate TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); KeyStore ks; try { ks = KeyStore.getInstance("jks"); } catch (KeyStoreException e) { throw new NoSuchAlgorithmException("jks KeyStore not available"); //this should never happen } String sslrootcertfile = info.getProperty("sslrootcert"); if (sslrootcertfile == null) { //Fall back to default sslrootcertfile = defaultdir + "root.crt"; } FileInputStream fis; try { fis = new FileInputStream(sslrootcertfile); } catch (FileNotFoundException ex) { throw new PSQLException(GT.tr("Could not open SSL root certificate file {0}.", new Object[]{sslrootcertfile}), PSQLState.CONNECTION_FAILURE, ex); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate[] certs = cf.generateCertificates(fis).toArray(new Certificate[]{}); fis.close(); ks.load(null, null); for(int i=0; i