Fix memory leaks when using PolarSSL. Valgrind says it's 100% leak free now :)
[umurmur.git] / src / ssl.c
1 /* Copyright (C) 2009-2010, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com>
3
4    All rights reserved.
5
6    Redistribution and use in source and binary forms, with or without
7    modification, are permitted provided that the following conditions
8    are met:
9
10    - Redistributions of source code must retain the above copyright notice,
11      this list of conditions and the following disclaimer.
12    - Redistributions in binary form must reproduce the above copyright notice,
13      this list of conditions and the following disclaimer in the documentation
14      and/or other materials provided with the distribution.
15    - Neither the name of the Developers nor the names of its contributors may
16      be used to endorse or promote products derived from this software without
17      specific prior written permission.
18
19    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22    A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "conf.h"
35 #include "log.h"
36 #include "ssl.h"
37
38 #ifdef USE_POLARSSL
39 /*
40  * PolarSSL interface
41  */
42
43 #include <polarssl/havege.h>
44 #include <polarssl/certs.h>
45 #include <polarssl/x509.h>
46 #include <polarssl/ssl.h>
47 #include <polarssl/net.h>
48
49 #define CA_CRT_FILENAME "ca.crt"
50
51 int ciphers[] =
52 {
53     SSL_EDH_RSA_AES_256_SHA,
54     SSL_EDH_RSA_CAMELLIA_256_SHA,
55     SSL_EDH_RSA_DES_168_SHA,
56     SSL_RSA_AES_256_SHA,
57     SSL_RSA_CAMELLIA_256_SHA,
58     SSL_RSA_AES_128_SHA,
59     SSL_RSA_CAMELLIA_128_SHA,
60     SSL_RSA_DES_168_SHA,
61     SSL_RSA_RC4_128_SHA,
62     SSL_RSA_RC4_128_MD5,
63     0
64 };
65 static x509_cert certificate;
66 static rsa_context key;
67 havege_state hs; /* exported to crypt.c */
68
69 /* DH prime */
70 char *my_dhm_P =
71         "9CE85640903BF123906947FEDE767261" \
72         "D9B4A973EB8F7D984A8C656E2BCC161C" \
73         "183D4CA471BA78225F940F16D1D99CA3" \
74         "E66152CC68EDCE1311A390F307741835" \
75         "44FF6AB553EC7073AD0CB608F2A3B480" \
76         "19E6C02BCED40BD30E91BB2469089670" \
77         "DEF409C08E8AC24D1732A6128D2220DC53";
78 char *my_dhm_G = "4";
79
80 static void initCert()
81 {
82         int rc;
83         char *crtfile = (char *)getStrConf(CERTIFICATE);
84         char *ca_file, *p;
85         
86         if (crtfile == NULL)
87                 Log_fatal("No certificate file specified"); 
88         rc = x509parse_crtfile(&certificate, crtfile);
89         if (rc != 0)
90                 Log_fatal("Could not read certificate file %s", crtfile);
91         
92         /* Look for CA certificate file in same dir */
93         ca_file = malloc(strlen(crtfile) + strlen(CA_CRT_FILENAME) + 1);
94         strcpy(ca_file, crtfile);
95         p = strrchr(ca_file, '/');
96         if (p != NULL)
97                 strcpy(p + 1, CA_CRT_FILENAME);
98         else
99                 strcpy(ca_file, CA_CRT_FILENAME);
100         
101         rc = x509parse_crtfile(&certificate, ca_file);
102         if (rc != 0) { /* No CA certifiacte found. Assume self-signed. */
103                 Log_info("CA certificate file %s not found. Assuming self-signed certificate.", ca_file);
104                 /*
105                  * Apparently PolarSSL needs to read something more into certificate chain.
106                  * Doesn't seem to matter what. Read own certificate again.
107                  */
108                 rc = x509parse_crtfile(&certificate, crtfile);
109                 if (rc != 0)
110                         Log_fatal("Could not read certificate file %s", crtfile);
111         }
112         free(ca_file);
113 }
114
115 static void initKey()
116 {
117         int rc;
118         char *keyfile = (char *)getStrConf(KEY);
119         
120         if (keyfile == NULL)
121                 Log_fatal("No key file specified"); 
122         rc = x509parse_keyfile(&key, keyfile, NULL);
123         if (rc != 0)
124                 Log_fatal("Could not read RSA key file %s", keyfile);
125 }
126
127 #define DEBUG_LEVEL 0
128 static void pssl_debug(void *ctx, int level, char *str)
129 {
130     if (level <= DEBUG_LEVEL)
131                 Log_debug("PolarSSL [level %d]: %s", level, str);
132 }
133
134 void SSLi_init(void)
135 {
136         initCert();
137         initKey();
138     havege_init(&hs);
139         Log_info("PolarSSL library initialized");
140 }
141
142 void SSLi_deinit(void)
143 {
144         x509_free(&certificate);
145         rsa_free(&key);
146 }
147
148 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
149 {
150         ssl_context *ssl;
151         ssl_session *ssn;
152         int rc;
153         
154         ssl = malloc(sizeof(ssl_context));
155         ssn = malloc(sizeof(ssl_session));
156         if (!ssl || !ssn)
157                 Log_fatal("Out of memory");
158         memset(ssl, 0, sizeof(ssl_context));
159         memset(ssn, 0, sizeof(ssl_session));
160         
161         rc = ssl_init(ssl);
162         if (rc != 0 )
163                 Log_fatal("Failed to initalize: %d", rc);
164         
165         ssl_set_endpoint(ssl, SSL_IS_SERVER);   
166     ssl_set_authmode(ssl, SSL_VERIFY_OPTIONAL);
167
168     ssl_set_rng(ssl, havege_rand, &hs);
169     ssl_set_dbg(ssl, pssl_debug, NULL);
170     ssl_set_bio(ssl, net_recv, fd, net_send, fd);
171
172     ssl_set_ciphers(ssl, ciphers);
173     ssl_set_session(ssl, 0, 0, ssn);
174
175     ssl_set_ca_chain(ssl, certificate.next, NULL, NULL);
176     ssl_set_own_cert(ssl, &certificate, &key);
177     ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
178
179         return ssl;
180 }
181
182 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
183 {
184         int rc;
185         
186         rc = ssl_handshake(ssl);
187         if (rc != 0) {
188                 if (rc == POLARSSL_ERR_NET_TRY_AGAIN) {
189                         return 0;
190                 } else {
191                         Log_warn("SSL handshake failed: %d", rc);
192                         return -1;
193                 }
194         }
195         *SSLready = true;
196         return 0;
197 }
198
199 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
200 {
201         int rc;
202         rc = ssl_read(ssl, buf, len);
203         if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
204                 return SSLI_ERROR_WANT_READ;
205         return rc;
206 }
207
208 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
209 {
210         int rc;
211         rc = ssl_write(ssl, buf, len);
212         if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
213                 return SSLI_ERROR_WANT_WRITE;
214         return rc;
215 }
216
217 int SSLi_get_error(SSL_handle_t *ssl, int code)
218 {
219         return code;
220 }
221
222 bool_t SSLi_data_pending(SSL_handle_t *ssl)
223 {
224         return ssl_get_bytes_avail(ssl) > 0;
225 }
226
227 void SSLi_shutdown(SSL_handle_t *ssl)
228 {
229         ssl_close_notify(ssl);
230 }
231
232 void SSLi_free(SSL_handle_t *ssl)
233 {
234         Log_debug("SSLi_free");
235         free(ssl->session); /* XXX - Hmmm. */
236         ssl_free(ssl);
237         free(ssl);
238 }
239
240 #else
241 /*
242  * OpenSSL interface
243  */
244
245 #include <openssl/x509v3.h>
246 #include <openssl/ssl.h>
247 #include <openssl/err.h>
248 #include <openssl/safestack.h>
249 static X509 *x509;
250 static RSA *rsa;
251 static SSL_CTX *context;
252 static EVP_PKEY *pkey;
253
254 static int SSL_add_ext(X509 * crt, int nid, char *value) {
255         X509_EXTENSION *ex;
256         X509V3_CTX ctx;
257         X509V3_set_ctx_nodb(&ctx);
258         X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
259         ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
260         if (!ex)
261                 return 0;
262
263         X509_add_ext(crt, ex, -1);
264         X509_EXTENSION_free(ex);
265         return 1;
266 }
267
268 static X509 *SSL_readcert(char *certfile)
269 {
270         FILE *fp;
271         X509 *x509;
272                         
273         /* open the private key file */
274         fp = fopen(certfile, "r");
275         if (fp == NULL) {
276                 Log_warn("Unable to open the X509 file %s for reading.", certfile);
277                 return NULL;
278         }
279         
280         /* allocate memory for the cert structure */    
281         x509 = X509_new();
282         
283         if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
284                 /* error reading the x509 information - check the error stack */
285                 Log_warn("Error trying to read X509 info.");
286                 fclose(fp);
287                 X509_free(x509);
288                 return NULL;
289         }
290         fclose(fp);
291         return x509;
292 }
293
294 static RSA *SSL_readprivatekey(char *keyfile)
295 {
296         FILE *fp;
297         RSA *rsa;
298
299 /* open the private key file for reading */
300         fp = fopen(keyfile, "r");
301         if (fp == NULL) {
302                 Log_warn("Unable to open the private key file %s for reading.", keyfile);
303                 return NULL;
304         }
305         
306 /* allocate memory for the RSA structure */
307         rsa = RSA_new();
308         
309         /* assign a callback function for the password */
310         
311         /* read a private key from file */      
312         if (PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL) <= 0) {
313                 /* error reading the key - check the error stack */
314                 Log_warn("Error trying to read private key.");
315                 RSA_free(rsa);
316                 fclose(fp);
317                 return NULL;
318         }
319         fclose(fp);
320         return rsa;
321 }
322
323 static void SSL_writecert(char *certfile, X509 *x509)
324 {
325         FILE *fp;
326         BIO *err_output;
327         
328         /* prepare a BIO for outputting error messages */
329         
330         err_output = BIO_new_fp(stderr,BIO_NOCLOSE);
331         
332         /* open the private key file */
333         fp = fopen(certfile, "w");
334         if (fp == NULL) {
335                 BIO_printf(err_output, "Unable to open the X509 file for writing.\n");
336                 BIO_free(err_output);
337                 return;
338         }
339                 
340         if (PEM_write_X509(fp, x509) == 0) {
341                 BIO_printf(err_output, "Error trying to write X509 info.\n");
342                 ERR_print_errors(err_output);
343         }
344         fclose(fp);
345 }
346
347 static void SSL_writekey(char *keyfile, RSA *rsa)
348 {
349         FILE *fp;
350         BIO *err_output;
351         /* prepare a BIO for outputing error messages */        
352         err_output = BIO_new_fp(stderr, BIO_NOCLOSE);
353         
354         /* open the private key file for reading */
355         fp = fopen(keyfile, "w");
356         if (fp == NULL) {
357                 BIO_printf(err_output, "Unable to open the private key file %s for writing.\n", keyfile);
358                 BIO_free(err_output);
359                 return;
360         }
361         
362         if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
363                 /* error reading the key - check the error stack */
364                 BIO_printf(err_output, "Error trying to write private key\n");
365                 ERR_print_errors(err_output);
366         }
367         fclose(fp);
368 }
369
370 static void SSL_initializeCert() {
371         char *crt, *key, *pass;
372         
373         crt = (char *)getStrConf(CERTIFICATE);
374         key = (char *)getStrConf(KEY);
375         pass = (char *)getStrConf(PASSPHRASE);
376
377         x509 = SSL_readcert(crt);
378         rsa = SSL_readprivatekey(key);
379         if (rsa != NULL) {
380                 pkey = EVP_PKEY_new();
381                 EVP_PKEY_assign_RSA(pkey, rsa);
382         }               
383         
384 #if 0
385         /* Later ... */
386         if (key && !x509) {             
387                 qscCert = QSslCertificate(key);
388                 if (! qscCert.isNull()) {
389                         logthis("Using certificate from key.");
390                 }
391         }
392
393         if (! qscCert.isNull()) {
394                 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
395                 /* Fetch algorith from cert */
396                 if (! key.isEmpty()) {
397                         /* get key */
398                         qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
399                         if (qskKey.isNull()) {
400                                 logthis("Failed to parse key.");
401                         }
402                 }
403
404                 if (! crt.isEmpty() && qskKey.isNull()) {
405                         /* get key from certificate */
406                         qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
407                         if (! qskKey.isNull()) {
408                                 logthis("Using key from certificate.");
409                         }
410                 }
411
412         }
413 #endif
414         
415         if (!rsa || !x509) {
416                 logthis("Generating new server certificate.");
417
418                 BIO *bio_err;
419                 
420                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
421                 
422                 bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
423                 
424                 x509 = X509_new();
425                 pkey = EVP_PKEY_new();
426                 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
427                 EVP_PKEY_assign_RSA(pkey, rsa);
428                 
429                 X509_set_version(x509, 2);
430                 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
431                 X509_gmtime_adj(X509_get_notBefore(x509),0);
432                 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
433                 X509_set_pubkey(x509, pkey);
434                 
435                 X509_NAME *name=X509_get_subject_name(x509);
436                 
437                 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
438                 X509_set_issuer_name(x509, name);
439                 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
440                 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
441                 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
442                 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
443                 
444                 X509_sign(x509, pkey, EVP_md5());
445                 
446                 SSL_writecert(crt, x509);
447                 SSL_writekey(key, rsa);
448         }
449
450 }
451
452 void SSLi_init(void)
453 {
454         const SSL_METHOD *method;
455         SSL *ssl;
456         int i, offset = 0;
457         STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
458         SSL_CIPHER *cipher;
459         char cipherstring[1024];
460                 
461         SSL_library_init();
462     OpenSSL_add_all_algorithms();               /* load & register all cryptos, etc. */
463     SSL_load_error_strings();                   /* load all error messages */
464     ERR_load_crypto_strings();                  /* load all error messages */
465     method = SSLv23_server_method();            /* create new server-method instance */
466     context = SSL_CTX_new(method);                      /* create new context from method */
467     if (context == NULL)
468     {
469         ERR_print_errors_fp(stderr);
470         abort();
471     }
472         SSL_initializeCert();
473         if (SSL_CTX_use_certificate(context, x509) <= 0)
474                 Log_fatal("Failed to initialize cert");
475         if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
476                 ERR_print_errors_fp(stderr);
477                 Log_fatal("Failed to initialize private key");
478         }
479
480         /* Set cipher list */
481         ssl = SSL_new(context); 
482         cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
483         cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
484         
485         for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
486                 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
487                         sk_SSL_CIPHER_push(cipherlist_new, cipher);
488                 }
489         }
490         Log_debug("List of ciphers:");
491         if (cipherlist_new) {
492                 for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
493                         Log_debug("%s", SSL_CIPHER_get_name(cipher));
494                         offset += snprintf(cipherstring + offset, 1024 - offset, "%s:", SSL_CIPHER_get_name(cipher));
495                 }
496                 cipherstring[offset - 1] = '\0';
497         }
498         
499         if (cipherlist_new)
500                 sk_SSL_CIPHER_free(cipherlist_new);
501         
502         if (strlen(cipherstring) == 0)
503                 Log_fatal("No suitable ciphers found!");
504         
505         if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
506                 Log_fatal("Failed to set cipher list!");
507                 
508         
509         SSL_free(ssl);
510         Log_info("OpenSSL library initialized");
511
512 }
513
514 void SSLi_deinit(void)
515 {
516         SSL_CTX_free(context);
517         EVP_cleanup();
518 }
519
520 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
521 {
522         int rc;
523         rc = SSL_accept(ssl);
524         if (rc < 0) {
525                 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
526                         SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
527                         Log_debug("SSL not ready");
528                         return 0;
529                 } else {
530                         Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
531                         return -1;
532                 }
533         }
534         *SSLready = true;
535         return 0;
536 }
537
538 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
539 {
540         SSL *ssl;
541         
542         *SSLready = false;
543         ssl = SSL_new(context);
544         SSL_set_fd(ssl, *fd);
545         if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
546                 SSL_free(ssl);
547                 return NULL;
548         }
549         return ssl;
550 }
551
552 void SSLi_closeconnection(SSL_handle_t *ssl)
553 {
554         SSL_free(ssl);
555 }
556
557 void SSLi_shutdown(SSL_handle_t *ssl)
558 {
559         SSL_shutdown(ssl);
560 }
561
562 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
563 {
564         return SSL_read(ssl, buf, len);
565 }
566
567 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
568 {
569         return SSL_write(ssl, buf, len);
570 }
571
572 int SSLi_get_error(SSL_handle_t *ssl, int code)
573 {
574         return SSL_get_error(ssl, code);
575 }
576
577 bool_t SSLi_data_pending(SSL_handle_t *ssl)
578 {
579         return SSL_pending(ssl);
580 }
581
582 void SSLi_free(SSL_handle_t *ssl)
583 {
584         SSL_free(ssl);
585 }
586
587 #endif