This corrects the reference count handling in SSL_get_session.
Previously, the returned SSL_SESSION didn't have its reference count
incremented so the SSL_SESSION could be freed at any time causing
seg-faults if the pointer was subsequently used. Code that uses
SSL_get_session must now make a corresponding SSL_SESSION_free() call when
it is done to avoid memory leaks (or blocked up session caches).

Submitted By: Geoff Thorpe <geoff@eu.c2.net>
diff --git a/CHANGES b/CHANGES
index c4b95c8..f37645a 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,6 +4,10 @@
 
  Changes between 0.9.4 and 0.9.5  [xx XXX 1999]
 
+  *) Correctly increment the reference count in the SSL_SESSION pointer 
+     returned from SSL_get_session().
+     [Geoff Thorpe <geoff@eu.c2.net>]
+
   *) Fix for 'req': it was adding a null to request attributes.
      Also change the X509_LOOKUP and X509_INFO code to handle
      certificate auxiliary information.
diff --git a/ssl/ssl_sess.c b/ssl/ssl_sess.c
index 681499f..4dddf62 100644
--- a/ssl/ssl_sess.c
+++ b/ssl/ssl_sess.c
@@ -69,7 +69,16 @@
 
 SSL_SESSION *SSL_get_session(SSL *ssl)
 	{
-	return(ssl->session);
+	SSL_SESSION *sess;
+	/* Need to lock this all up rather than just use CRYPTO_add so that
+	 * somebody doesn't free ssl->session between when we check it's
+	 * non-null and when we up the reference count. */
+	CRYPTO_r_lock(CRYPTO_LOCK_SSL_SESSION);
+	sess = ssl->session;
+	if(sess)
+		sess->references++;
+	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_SESSION);
+	return(sess);
 	}
 
 int SSL_SESSION_get_ex_new_index(long argl, char *argp, int (*new_func)(),