From: Bodor Andras <bodri.mh3@gmail.com>
To: pgsql-jdbc@postgresql.org
Subject: Re: JDBC SSL hostname verification
Date: Tue, 16 Aug 2011 23:03:38 +0200
Message-ID: <4E4ADB2A.5040902@gmail.com> (raw)
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
Attachments:MakeSSL.patch (text/x-diff, 4.3K) download
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);
> }
> }
LazyKeyManager.java (text/x-java, 7.2K) download
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"};
}
}
LibPQFactory.java (text/x-java, 10.8K) download
/*-------------------------------------------------------------------------
*
* 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<certs.length; i++)
{
ks.setCertificateEntry("cert"+i, certs[i]);
}
tmf.init(ks);
}
catch (IOException ioex)
{
throw new PSQLException(GT.tr("Could not read SSL root certificate file {0}.", new Object[]{sslrootcertfile}), PSQLState.CONNECTION_FAILURE, ioex);
} catch (GeneralSecurityException gsex)
{
throw new PSQLException(GT.tr("Loading the SSL root certificate {0} into a TrustManager failed.", new Object[]{sslrootcertfile}), PSQLState.CONNECTION_FAILURE, gsex);
}
tm = tmf.getTrustManagers();
} else { //server validation is not required
tm = new TrustManager[] { new NonValidatingTM() };
}
//finally we can initialize the context
try
{
ctx.init(new KeyManager[]{km}, tm, null);
} catch (KeyManagementException ex)
{
throw new PSQLException(GT.tr("Could not initialize SSL context.", null), PSQLState.CONNECTION_FAILURE, ex);
}
_factory = ctx.getSocketFactory();
}
catch(NoSuchAlgorithmException ex)
{
throw new PSQLException(GT.tr("Could not find a java cryptographic algorithm: {0}.", new Object[]{ex.getMessage()}), PSQLState.CONNECTION_FAILURE, ex);
}
}
/**
* Propagates any exception from LazyKeyManager
* @throws PSQLException
*/
public void throwKeyManagerException() throws PSQLException
{
if (km!=null) km.throwKeyManagerException();
}
/**
* A CallbackHandler that reads the password from the console
* or returns the password given to it's constructor.
*
*/
class ConsoleCallbackHandler implements CallbackHandler {
private char[] password = null;
public ConsoleCallbackHandler(String password)
{
if (password != null) this.password = password.toCharArray();
}
/**
* Handles the callbacks.
* @param callbacks The callbacks to handle
* @throws UnsupportedCallbackException If the console is not available
* or other than PasswordCallback is supplied
*/
@Override
public void handle(Callback[] callbacks) throws IOException,
UnsupportedCallbackException {
Console cons = System.console();
if (cons==null && password==null) {throw new UnsupportedCallbackException(callbacks[0], "Console is not available");}
for (int i=0; i<callbacks.length; i++)
{
if (callbacks[i] instanceof PasswordCallback)
{
if (password==null)
{
//It is used instead of cons.readPassword(prompt), because the prompt may contain '%' characters
((PasswordCallback)callbacks[i]).setPassword(cons.readPassword("%s", ((PasswordCallback)callbacks[i]).getPrompt()));
} else {
((PasswordCallback)callbacks[i]).setPassword(password);
}
} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}
}
@Override
/**
* Verifies the server certificate according to the libpq rules.
* The cn attribute of the certificate is matched against the hostname.
* If the cn attribute starts with an asterisk (*), it will be treated as a wildcard,
* and will match all characters except a dot (.). This means the certificate
* will not match subdomains. If the connection is made using an IP address instead of a
* hostname, the IP address will be matched (without doing any DNS lookups).
* @param hostname Hostname or IP address of the server.
* @param session The SSL session.
* @returns true if the certificate belongs to the server, false otherwise.
*/
public boolean verify(String hostname, SSLSession session) {
X509Certificate[] peerCerts;
try
{
peerCerts = (X509Certificate[])session.getPeerCertificates();
} catch (SSLPeerUnverifiedException e)
{
return false;
}
if (peerCerts == null || peerCerts.length == 0) {
return false;
}
//Extract the common name
X509Certificate serverCert = peerCerts[0];
LdapName DN;
try
{
DN = new LdapName(serverCert.getSubjectX500Principal().getName(X500Principal.RFC2253));
} catch (InvalidNameException e)
{
return false;
}
String CN = null;
for(Rdn rdn : DN.getRdns())
{
if ("CN".equals(rdn.getType())) //Multiple AVAs are not treated
{
CN = (String)rdn.getValue();
break;
}
}
if (CN == null)
{
return false;
} else if (CN.startsWith("*"))
{ //We have a wildcard
if (hostname.endsWith(CN.substring(1)))
{ //Avoid IndexOutOfBoundsException because hostname already ends with CN
return !(hostname.substring(0, hostname.length()-CN.length()+1).contains("."));
} else {
return false;
}
} else {
return CN.equals(hostname);
}
}
}
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: bodri.mh3@gmail.com
Subject: Re: JDBC SSL hostname verification
In-Reply-To: <4E4ADB2A.5040902@gmail.com>
References: <4E4ADB2A.5040902@gmail.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