Add support for PolarSSL 1.3.x
[umurmur.git] / src / ssl.c
index dc2245352b6fff895948f665ceca3087c5861c4a..925795c0b8de6857dacb34d173f162ff8b5dfa64 100644 (file)
--- a/src/ssl.c
+++ b/src/ssl.c
@@ -1,5 +1,5 @@
-/* Copyright (C) 2009-2010, Martin Johansson <martin@fatbob.nu>
-   Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com>
+/* Copyright (C) 2009-2013, Martin Johansson <martin@fatbob.nu>
+   Copyright (C) 2005-2013, Thorvald Natvig <thorvald@natvig.com>
 
    All rights reserved.
 
@@ -30,6 +30,7 @@
 */
 #include <string.h>
 #include <stdlib.h>
+#include <fcntl.h>
 
 #include "conf.h"
 #include "log.h"
  * PolarSSL interface
  */
 
+#include <polarssl/config.h>
 #include <polarssl/havege.h>
 #include <polarssl/certs.h>
 #include <polarssl/x509.h>
 #include <polarssl/ssl.h>
 #include <polarssl/net.h>
 
-#define CA_CRT_FILENAME "ca.crt"
-
+#ifdef POLARSSL_API_V1_2_ABOVE
+int ciphers[] =
+{
+    TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
+    TLS_RSA_WITH_AES_256_CBC_SHA,
+    TLS_RSA_WITH_AES_128_CBC_SHA,
+    0
+};
+#else
 int ciphers[] =
 {
     SSL_EDH_RSA_AES_256_SHA,
-    SSL_EDH_RSA_CAMELLIA_256_SHA,
-    SSL_EDH_RSA_DES_168_SHA,
     SSL_RSA_AES_256_SHA,
-    SSL_RSA_CAMELLIA_256_SHA,
     SSL_RSA_AES_128_SHA,
-    SSL_RSA_CAMELLIA_128_SHA,
-    SSL_RSA_DES_168_SHA,
-    SSL_RSA_RC4_128_SHA,
-    SSL_RSA_RC4_128_MD5,
     0
 };
+#endif
+
+#ifdef POLARSSL_API_V1_3_ABOVE
+static x509_crt certificate;
+static inline int x509parse_keyfile(rsa_context *rsa, const char *path,
+                                    const char *pwd)
+{
+    int ret;
+    pk_context pk;
+    
+    pk_init(&pk);
+    ret = pk_parse_keyfile(&pk, path, pwd);
+    if (ret == 0 && !pk_can_do( &pk, POLARSSL_PK_RSA))
+        ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
+    if (ret == 0)
+        rsa_copy(rsa, pk_rsa(pk));
+    else
+        rsa_free(rsa);
+    pk_free(&pk);
+    return ret;
+}
+#else
 static x509_cert certificate;
+#endif
+
 static rsa_context key;
-havege_state hs; /* exported to crypt.c */
+bool_t builtInTestCertificate;
+
+#ifdef USE_POLARSSL_HAVEGE
+havege_state hs;
+#else
+int urandom_fd;
+#endif
 
 /* DH prime */
 char *my_dhm_P =
@@ -77,37 +109,65 @@ char *my_dhm_P =
        "DEF409C08E8AC24D1732A6128D2220DC53";
 char *my_dhm_G = "4";
 
+#ifdef USE_POLARSSL_TESTCERT
+static void initTestCert()
+{
+       int rc;
+       builtInTestCertificate = true;
+#ifdef POLARSSL_API_V1_3_ABOVE
+       rc = x509_crt_parse_rsa(&certificate, (unsigned char *)test_srv_crt,
+               strlen(test_srv_crt));
+#else
+       rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
+               strlen(test_srv_crt));
+#endif
+       if (rc != 0)
+               Log_fatal("Could not parse built-in test certificate");
+}
+
+static void initTestKey()
+{
+       int rc;
+       
+       rc = x509parse_key_rsa(&key, (unsigned char *)test_srv_key,
+                              strlen(test_srv_key), NULL, 0);
+       if (rc != 0)
+               Log_fatal("Could not parse built-in test RSA key");
+}
+#endif
+
+/*
+ * How to generate a self-signed cert with openssl:
+ * openssl genrsa 1024 > host.key
+ * openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert
+ */
 static void initCert()
 {
        int rc;
        char *crtfile = (char *)getStrConf(CERTIFICATE);
-       char *ca_file, *p;
        
-       if (crtfile == NULL)
-               Log_fatal("No certificate file specified"); 
+       if (crtfile == NULL) {
+#ifdef USE_POLARSSL_TESTCERT
+               Log_warn("No certificate file specified. Falling back to test certificate.");
+               initTestCert();
+#else
+               Log_fatal("No certificate file specified");
+#endif
+               return;
+       }
+#ifdef POLARSSL_API_V1_3_ABOVE
+       rc = x509_crt_parse_file(&certificate, crtfile);
+#else
        rc = x509parse_crtfile(&certificate, crtfile);
-       if (rc != 0)
-               Log_fatal("Could not read certificate file %s", crtfile);
-       
-       /* Look for CA certificate file in same dir */
-       ca_file = malloc(strlen(crtfile) + strlen(CA_CRT_FILENAME) + 1);
-       strcpy(ca_file, crtfile);
-       p = strrchr(ca_file, '/');
-       if (p != NULL)
-               strcpy(p + 1, CA_CRT_FILENAME);
-       else
-               strcpy(ca_file, CA_CRT_FILENAME);
-       
-       rc = x509parse_crtfile(&certificate, ca_file);
-       if (rc != 0) { /* No CA certifiacte found. Assume self-signed. */
-               Log_info("CA certificate file %s not found. Assuming self-signed certificate.", ca_file);
-               /*
-                * Apparently PolarSSL needs to read something more into certificate chain.
-                * Doesn't seem to matter what. Read own certificate again.
-                */
-               rc = x509parse_crtfile(&certificate, crtfile);
-               if (rc != 0)
-                       Log_fatal("Could not read certificate file %s", crtfile);
+#endif
+       if (rc != 0) {
+#ifdef USE_POLARSSL_TESTCERT
+               Log_warn("Could not read certificate file '%s'. Falling back to test certificate.", crtfile);
+               initTestCert();
+#else
+               Log_fatal("Could not read certificate file '%s'", crtfile);
+#endif
+               return;
        }
 }
 
@@ -115,7 +175,7 @@ static void initKey()
 {
        int rc;
        char *keyfile = (char *)getStrConf(KEY);
-       
+
        if (keyfile == NULL)
                Log_fatal("No key file specified"); 
        rc = x509parse_keyfile(&key, keyfile, NULL);
@@ -123,27 +183,88 @@ static void initKey()
                Log_fatal("Could not read RSA key file %s", keyfile);
 }
 
+#ifndef USE_POLARSSL_HAVEGE
+int urandom_bytes(void *ctx, unsigned char *dest, size_t len)
+{
+       int cur;
+       
+       while (len) {
+               cur = read(urandom_fd, dest, len);
+               if (cur < 0)
+                       continue;
+               len -= cur;
+       }
+       return 0;
+}
+#endif
+
 #define DEBUG_LEVEL 0
-static void pssl_debug(void *ctx, int level, char *str)
+static void pssl_debug(void *ctx, int level, const char *str)
 {
     if (level <= DEBUG_LEVEL)
-               Log_debug("PolarSSL [level %d]: %s", level, str);
+               Log_info("PolarSSL [level %d]: %s", level, str);
 }
 
 void SSLi_init(void)
 {
+       char verstring[12];
+       
        initCert();
+#ifdef USE_POLARSSL_TESTCERT
+       if (builtInTestCertificate) {
+               Log_warn("*** Using built-in test certificate and RSA key ***");
+               Log_warn("*** This is not secure! Please use a CA-signed certificate or create a key and self-signed certificate ***");
+               initTestKey();
+       }
+       else
+               initKey();
+#else
        initKey();
+#endif
+
+       /* Initialize random number generator */
+#ifdef USE_POLARSSL_HAVEGE
     havege_init(&hs);
-       Log_info("PolarSSL library initialized");
+#else
+    urandom_fd = open("/dev/urandom", O_RDONLY);
+    if (urandom_fd < 0)
+           Log_fatal("Cannot open /dev/urandom");
+#endif
+    
+    version_get_string(verstring);
+    Log_info("PolarSSL library version %s initialized", verstring);
 }
 
 void SSLi_deinit(void)
 {
+#ifdef POLARSSL_API_V1_3_ABOVE
+       x509_crt_free(&certificate);
+#else  
        x509_free(&certificate);
+#endif
        rsa_free(&key);
 }
 
+/* Create SHA1 of last certificate in the peer's chain. */
+bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
+{
+#ifdef POLARSSL_API_V1_3_ABOVE
+       x509_crt const *cert;
+#else
+       x509_cert const *cert;
+#endif
+#ifdef POLARSSL_API_V1_2_ABOVE
+       cert = ssl_get_peer_cert(ssl);
+#else
+       cert = ssl->peer_cert;
+#endif
+       if (!cert) {
+               return false;
+       }       
+       sha1(cert->raw.p, cert->raw.len, hash);
+       return true;
+}
+       
 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
 {
        ssl_context *ssl;
@@ -159,21 +280,35 @@ SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
        
        rc = ssl_init(ssl);
        if (rc != 0 )
-               Log_fatal("Failed to initalize: %d", rc);
+               Log_fatal("Failed to initialize: %d", rc);
        
        ssl_set_endpoint(ssl, SSL_IS_SERVER);   
-    ssl_set_authmode(ssl, SSL_VERIFY_OPTIONAL);
+       ssl_set_authmode(ssl, SSL_VERIFY_OPTIONAL);
+       
+#ifdef USE_POLARSSL_HAVEGE
+       ssl_set_rng(ssl, HAVEGE_RAND, &hs);
+#else
+       ssl_set_rng(ssl, urandom_bytes, NULL);
+#endif
+       
+       ssl_set_dbg(ssl, pssl_debug, NULL);
+       ssl_set_bio(ssl, net_recv, fd, net_send, fd);
 
-    ssl_set_rng(ssl, havege_rand, &hs);
-    ssl_set_dbg(ssl, pssl_debug, NULL);
-    ssl_set_bio(ssl, net_recv, fd, net_send, fd);
+       ssl_set_ciphersuites(ssl, ciphers);
 
-    ssl_set_ciphers(ssl, ciphers);
+#ifdef POLARSSL_API_V1_2_ABOVE
+    ssl_set_session(ssl, ssn);
+#else
     ssl_set_session(ssl, 0, 0, ssn);
-
-    ssl_set_ca_chain(ssl, certificate.next, NULL, NULL);
-    ssl_set_own_cert(ssl, &certificate, &key);
-    ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
+#endif
+    
+    ssl_set_ca_chain(ssl, &certificate, NULL, NULL);
+#ifdef POLARSSL_API_V1_3_ABOVE
+       ssl_set_own_cert_rsa(ssl, &certificate, &key);
+#else
+       ssl_set_own_cert(ssl, &certificate, &key);
+#endif
+       ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
 
        return ssl;
 }
@@ -184,8 +319,10 @@ int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
        
        rc = ssl_handshake(ssl);
        if (rc != 0) {
-               if (rc == POLARSSL_ERR_NET_TRY_AGAIN) {
+               if (rc == POLARSSL_ERR_NET_WANT_READ || rc == POLARSSL_ERR_NET_WANT_WRITE) {
                        return 0;
+               } else if (rc == POLARSSL_ERR_X509_CERT_VERIFY_FAILED) { /* Allow this (selfsigned etc) */
+                       return 0;                       
                } else {
                        Log_warn("SSL handshake failed: %d", rc);
                        return -1;
@@ -198,8 +335,9 @@ int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
 {
        int rc;
+
        rc = ssl_read(ssl, buf, len);
-       if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
+       if (rc == POLARSSL_ERR_NET_WANT_READ)
                return SSLI_ERROR_WANT_READ;
        return rc;
 }
@@ -207,8 +345,9 @@ int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
 {
        int rc;
+       
        rc = ssl_write(ssl, buf, len);
-       if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
+       if (rc == POLARSSL_ERR_NET_WANT_WRITE)
                return SSLI_ERROR_WANT_WRITE;
        return rc;
 }
@@ -230,7 +369,12 @@ void SSLi_shutdown(SSL_handle_t *ssl)
 
 void SSLi_free(SSL_handle_t *ssl)
 {
-       free(ssl->session);
+       Log_debug("SSLi_free");
+#if (POLARSSL_VERSION_MINOR <= 2 && POLARSSL_VERSION_PATCH < 6)
+       free(ssl->session); /* Workaround for memory leak in PolarSSL < 1.2.6 */
+       ssl->session = NULL;
+#endif
+       ssl_free(ssl);
        free(ssl);
 }
 
@@ -247,6 +391,8 @@ static X509 *x509;
 static RSA *rsa;
 static SSL_CTX *context;
 static EVP_PKEY *pkey;
+static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx);
 
 static int SSL_add_ext(X509 * crt, int nid, char *value) {
        X509_EXTENSION *ex;
@@ -320,23 +466,15 @@ static RSA *SSL_readprivatekey(char *keyfile)
 static void SSL_writecert(char *certfile, X509 *x509)
 {
        FILE *fp;
-       BIO *err_output;
-       
-       /* prepare a BIO for outputting error messages */
-       
-       err_output = BIO_new_fp(stderr,BIO_NOCLOSE);
-       
+               
        /* open the private key file */
        fp = fopen(certfile, "w");
        if (fp == NULL) {
-               BIO_printf(err_output, "Unable to open the X509 file for writing.\n");
-               BIO_free(err_output);
+               Log_warn("Unable to open the X509 file %s for writing", certfile);
                return;
-       }
-               
+       }               
        if (PEM_write_X509(fp, x509) == 0) {
-               BIO_printf(err_output, "Error trying to write X509 info.\n");
-               ERR_print_errors(err_output);
+               Log_warn("Error trying to write X509 info.");
        }
        fclose(fp);
 }
@@ -344,22 +482,16 @@ static void SSL_writecert(char *certfile, X509 *x509)
 static void SSL_writekey(char *keyfile, RSA *rsa)
 {
        FILE *fp;
-       BIO *err_output;
-       /* prepare a BIO for outputing error messages */        
-       err_output = BIO_new_fp(stderr, BIO_NOCLOSE);
        
        /* open the private key file for reading */
        fp = fopen(keyfile, "w");
        if (fp == NULL) {
-               BIO_printf(err_output, "Unable to open the private key file %s for writing.\n", keyfile);
-               BIO_free(err_output);
+               Log_warn("Unable to open the private key file %s for writing.", keyfile);
                return;
        }
        
        if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
-               /* error reading the key - check the error stack */
-               BIO_printf(err_output, "Error trying to write private key\n");
-               ERR_print_errors(err_output);
+               Log_warn("Error trying to write private key");
        }
        fclose(fp);
 }
@@ -410,14 +542,11 @@ static void SSL_initializeCert() {
 #endif
        
        if (!rsa || !x509) {
-               logthis("Generating new server certificate.");
+               Log_info("Generating new server certificate.");
 
-               BIO *bio_err;
                
                CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
-               
-               bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
-               
+                               
                x509 = X509_new();
                pkey = EVP_PKEY_new();
                rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
@@ -450,10 +579,10 @@ void SSLi_init(void)
 {
        const SSL_METHOD *method;
        SSL *ssl;
-       int i, offset = 0;
+       int i, offset = 0, cipherstringlen = 0;
        STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
        SSL_CIPHER *cipher;
-       char cipherstring[1024];
+       char *cipherstring, tempstring[128];
                
        SSL_library_init();
     OpenSSL_add_all_algorithms();              /* load & register all cryptos, etc. */
@@ -486,11 +615,16 @@ void SSLi_init(void)
        }
        Log_debug("List of ciphers:");
        if (cipherlist_new) {
-               for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
+               for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
                        Log_debug("%s", SSL_CIPHER_get_name(cipher));
-                       offset += snprintf(cipherstring + offset, 1024 - offset, "%s:", SSL_CIPHER_get_name(cipher));
+                       cipherstringlen += strlen(SSL_CIPHER_get_name(cipher)) + 1;
+               }
+               cipherstring = malloc(cipherstringlen + 1);
+               if (cipherstring == NULL)
+                       Log_fatal("Out of memory");
+               for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
+                       offset += sprintf(cipherstring + offset, "%s:", SSL_CIPHER_get_name(cipher));
                }
-               cipherstring[offset - 1] = '\0';
        }
        
        if (cipherlist_new)
@@ -501,7 +635,11 @@ void SSLi_init(void)
        
        if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
                Log_fatal("Failed to set cipher list!");
-               
+
+       free(cipherstring);
+       
+       SSL_CTX_set_verify(context, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
+                          verify_callback);            
        
        SSL_free(ssl);
        Log_info("OpenSSL library initialized");
@@ -546,6 +684,32 @@ SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
        return ssl;
 }
 
+/* Create SHA1 of last certificate in the peer's chain. */
+bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
+{
+       X509 *x509;
+       uint8_t *buf, *p;
+       int len;
+       
+       x509 = SSL_get_peer_certificate(ssl);
+       if (!x509) {
+               return false;
+       }       
+       
+       len = i2d_X509(x509, NULL);
+       buf = malloc(len);
+       if (buf == NULL) {
+               Log_fatal("malloc");
+       }
+
+       p = buf;
+       i2d_X509(x509, &p);     
+       
+       SHA1(buf, len, hash);
+       free(buf);
+       return true;
+}
 void SSLi_closeconnection(SSL_handle_t *ssl)
 {
        SSL_free(ssl);
@@ -581,4 +745,38 @@ void SSLi_free(SSL_handle_t *ssl)
        SSL_free(ssl);
 }
 
+static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
+{
+       char    buf[256];
+       X509   *err_cert;
+       int     err, depth;
+       SSL    *ssl;
+    
+    err_cert = X509_STORE_CTX_get_current_cert(ctx);
+    err = X509_STORE_CTX_get_error(ctx);
+    depth = X509_STORE_CTX_get_error_depth(ctx);
+    
+    ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
+    X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
+        
+    if (depth > 5) {
+        preverify_ok = 0;
+        err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
+        X509_STORE_CTX_set_error(ctx, err);
+    }
+    if (!preverify_ok) {
+           Log_warn("SSL: verify error:num=%d:%s:depth=%d:%s\n", err,
+                    X509_verify_cert_error_string(err), depth, buf);
+    }
+    /*
+     * At this point, err contains the last verification error. We can use
+     * it for something special
+     */
+    if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
+           X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
+           Log_warn("issuer= %s", buf);
+    }
+    return 1;
+}
 #endif