Remove pointless CA cert handling with PolarSSL. Did not work anyway. Use VERIFY_NONE...
[umurmur.git] / src / ssl.c
1 /* Copyright (C) 2009-2011, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2011, 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 #include <polarssl/version.h>
49
50 int ciphers[] =
51 {
52     SSL_EDH_RSA_AES_256_SHA,
53     SSL_EDH_RSA_CAMELLIA_256_SHA,
54     SSL_EDH_RSA_DES_168_SHA,
55     SSL_RSA_AES_256_SHA,
56     SSL_RSA_CAMELLIA_256_SHA,
57     SSL_RSA_AES_128_SHA,
58     SSL_RSA_CAMELLIA_128_SHA,
59     SSL_RSA_DES_168_SHA,
60     SSL_RSA_RC4_128_SHA,
61     SSL_RSA_RC4_128_MD5,
62     0
63 };
64 static x509_cert certificate;
65 static rsa_context key;
66 bool_t builtInTestCertificate;
67
68 havege_state hs; /* exported to crypt.c */
69
70 /* DH prime */
71 char *my_dhm_P =
72         "9CE85640903BF123906947FEDE767261" \
73         "D9B4A973EB8F7D984A8C656E2BCC161C" \
74         "183D4CA471BA78225F940F16D1D99CA3" \
75         "E66152CC68EDCE1311A390F307741835" \
76         "44FF6AB553EC7073AD0CB608F2A3B480" \
77         "19E6C02BCED40BD30E91BB2469089670" \
78         "DEF409C08E8AC24D1732A6128D2220DC53";
79 char *my_dhm_G = "4";
80
81 static void initTestCert()
82 {
83         int rc;
84         builtInTestCertificate = true;
85         rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
86                                            strlen(test_srv_crt));       
87         if (rc != 0)
88                 Log_fatal("Could not parse built-in test certificate");
89 }
90
91 static void initTestKey()
92 {
93         int rc;
94         
95         rc = x509parse_key(&key, (unsigned char *)test_srv_key,
96                                            strlen(test_srv_key), NULL, 0);
97         if (rc != 0)
98                 Log_fatal("Could not parse built-in test RSA key");
99 }
100
101 /*
102  * How to generate a self-signed cert with openssl:
103  * openssl genrsa 1024 > host.key
104  * openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert
105  */
106 static void initCert()
107 {
108         int rc;
109         char *crtfile = (char *)getStrConf(CERTIFICATE);
110         
111         if (crtfile == NULL) {
112                 Log_warn("No certificate file specified");
113                 initTestCert();
114                 return;
115         }
116         rc = x509parse_crtfile(&certificate, crtfile);
117         if (rc != 0) {
118                 Log_warn("Could not read certificate file %s", crtfile);
119                 initTestCert();
120                 return;
121         }
122 }
123
124 static void initKey()
125 {
126         int rc;
127         char *keyfile = (char *)getStrConf(KEY);
128
129         if (keyfile == NULL)
130                 Log_fatal("No key file specified"); 
131         rc = x509parse_keyfile(&key, keyfile, NULL);
132         if (rc != 0)
133                 Log_fatal("Could not read RSA key file %s", keyfile);
134 }
135
136 #define DEBUG_LEVEL 0
137 static void pssl_debug(void *ctx, int level, const char *str)
138 {
139     if (level <= DEBUG_LEVEL)
140                 Log_debug("PolarSSL [level %d]: %s", level, str);
141 }
142
143 void SSLi_init(void)
144 {
145         initCert();
146         if (builtInTestCertificate) {
147                 Log_warn("*** Using built-in test certificate and RSA key ***");
148                 Log_warn("*** This is not secure! Please use a CA-signed certificate or create a self-signed certificate ***");
149                 initTestKey();
150         }
151         else
152                 initKey();
153     havege_init(&hs);
154         Log_info("PolarSSL library initialized");
155 }
156
157 void SSLi_deinit(void)
158 {
159         x509_free(&certificate);
160         rsa_free(&key);
161 }
162
163 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
164 {
165         ssl_context *ssl;
166         ssl_session *ssn;
167         int rc;
168         
169         ssl = malloc(sizeof(ssl_context));
170         ssn = malloc(sizeof(ssl_session));
171         if (!ssl || !ssn)
172                 Log_fatal("Out of memory");
173         memset(ssl, 0, sizeof(ssl_context));
174         memset(ssn, 0, sizeof(ssl_session));
175         
176         rc = ssl_init(ssl);
177         if (rc != 0 )
178                 Log_fatal("Failed to initalize: %d", rc);
179         
180         ssl_set_endpoint(ssl, SSL_IS_SERVER);   
181         ssl_set_authmode(ssl, SSL_VERIFY_NONE);
182
183         ssl_set_rng(ssl, havege_rand, &hs);
184         ssl_set_dbg(ssl, pssl_debug, NULL);
185         ssl_set_bio(ssl, net_recv, fd, net_send, fd);
186
187         ssl_set_ciphers(ssl, ciphers);
188         ssl_set_session(ssl, 0, 0, ssn);
189
190         ssl_set_own_cert(ssl, &certificate, &key);
191         ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
192
193         return ssl;
194 }
195
196 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
197 {
198         int rc;
199         
200         rc = ssl_handshake(ssl);
201         if (rc != 0) {
202                 if (rc == POLARSSL_ERR_NET_TRY_AGAIN) {
203                         return 0;
204                 } else {
205                         Log_warn("SSL handshake failed: %d", rc);
206                         return -1;
207                 }
208         }
209         *SSLready = true;
210         return 0;
211 }
212
213 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
214 {
215         int rc;
216         rc = ssl_read(ssl, buf, len);
217         if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
218                 return SSLI_ERROR_WANT_READ;
219         return rc;
220 }
221
222 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
223 {
224         int rc;
225         rc = ssl_write(ssl, buf, len);
226         if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
227                 return SSLI_ERROR_WANT_WRITE;
228         return rc;
229 }
230
231 int SSLi_get_error(SSL_handle_t *ssl, int code)
232 {
233         return code;
234 }
235
236 bool_t SSLi_data_pending(SSL_handle_t *ssl)
237 {
238         return ssl_get_bytes_avail(ssl) > 0;
239 }
240
241 void SSLi_shutdown(SSL_handle_t *ssl)
242 {
243         ssl_close_notify(ssl);
244 }
245
246 void SSLi_free(SSL_handle_t *ssl)
247 {
248         Log_debug("SSLi_free");
249         free(ssl->session); /* XXX - Hmmm. */
250         ssl_free(ssl);
251         free(ssl);
252 }
253
254 #else
255 /*
256  * OpenSSL interface
257  */
258
259 #include <openssl/x509v3.h>
260 #include <openssl/ssl.h>
261 #include <openssl/err.h>
262 #include <openssl/safestack.h>
263 static X509 *x509;
264 static RSA *rsa;
265 static SSL_CTX *context;
266 static EVP_PKEY *pkey;
267
268 static int SSL_add_ext(X509 * crt, int nid, char *value) {
269         X509_EXTENSION *ex;
270         X509V3_CTX ctx;
271         X509V3_set_ctx_nodb(&ctx);
272         X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
273         ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
274         if (!ex)
275                 return 0;
276
277         X509_add_ext(crt, ex, -1);
278         X509_EXTENSION_free(ex);
279         return 1;
280 }
281
282 static X509 *SSL_readcert(char *certfile)
283 {
284         FILE *fp;
285         X509 *x509;
286                         
287         /* open the private key file */
288         fp = fopen(certfile, "r");
289         if (fp == NULL) {
290                 Log_warn("Unable to open the X509 file %s for reading.", certfile);
291                 return NULL;
292         }
293         
294         /* allocate memory for the cert structure */    
295         x509 = X509_new();
296         
297         if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
298                 /* error reading the x509 information - check the error stack */
299                 Log_warn("Error trying to read X509 info.");
300                 fclose(fp);
301                 X509_free(x509);
302                 return NULL;
303         }
304         fclose(fp);
305         return x509;
306 }
307
308 static RSA *SSL_readprivatekey(char *keyfile)
309 {
310         FILE *fp;
311         RSA *rsa;
312
313 /* open the private key file for reading */
314         fp = fopen(keyfile, "r");
315         if (fp == NULL) {
316                 Log_warn("Unable to open the private key file %s for reading.", keyfile);
317                 return NULL;
318         }
319         
320 /* allocate memory for the RSA structure */
321         rsa = RSA_new();
322         
323         /* assign a callback function for the password */
324         
325         /* read a private key from file */      
326         if (PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL) <= 0) {
327                 /* error reading the key - check the error stack */
328                 Log_warn("Error trying to read private key.");
329                 RSA_free(rsa);
330                 fclose(fp);
331                 return NULL;
332         }
333         fclose(fp);
334         return rsa;
335 }
336
337 static void SSL_writecert(char *certfile, X509 *x509)
338 {
339         FILE *fp;
340         BIO *err_output;
341         
342         /* prepare a BIO for outputting error messages */
343         
344         err_output = BIO_new_fp(stderr,BIO_NOCLOSE);
345         
346         /* open the private key file */
347         fp = fopen(certfile, "w");
348         if (fp == NULL) {
349                 BIO_printf(err_output, "Unable to open the X509 file for writing.\n");
350                 BIO_free(err_output);
351                 return;
352         }
353                 
354         if (PEM_write_X509(fp, x509) == 0) {
355                 BIO_printf(err_output, "Error trying to write X509 info.\n");
356                 ERR_print_errors(err_output);
357         }
358         fclose(fp);
359 }
360
361 static void SSL_writekey(char *keyfile, RSA *rsa)
362 {
363         FILE *fp;
364         BIO *err_output;
365         /* prepare a BIO for outputing error messages */        
366         err_output = BIO_new_fp(stderr, BIO_NOCLOSE);
367         
368         /* open the private key file for reading */
369         fp = fopen(keyfile, "w");
370         if (fp == NULL) {
371                 BIO_printf(err_output, "Unable to open the private key file %s for writing.\n", keyfile);
372                 BIO_free(err_output);
373                 return;
374         }
375         
376         if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
377                 /* error reading the key - check the error stack */
378                 BIO_printf(err_output, "Error trying to write private key\n");
379                 ERR_print_errors(err_output);
380         }
381         fclose(fp);
382 }
383
384 static void SSL_initializeCert() {
385         char *crt, *key, *pass;
386         
387         crt = (char *)getStrConf(CERTIFICATE);
388         key = (char *)getStrConf(KEY);
389         pass = (char *)getStrConf(PASSPHRASE);
390
391         x509 = SSL_readcert(crt);
392         rsa = SSL_readprivatekey(key);
393         if (rsa != NULL) {
394                 pkey = EVP_PKEY_new();
395                 EVP_PKEY_assign_RSA(pkey, rsa);
396         }               
397         
398 #if 0
399         /* Later ... */
400         if (key && !x509) {             
401                 qscCert = QSslCertificate(key);
402                 if (! qscCert.isNull()) {
403                         logthis("Using certificate from key.");
404                 }
405         }
406
407         if (! qscCert.isNull()) {
408                 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
409                 /* Fetch algorith from cert */
410                 if (! key.isEmpty()) {
411                         /* get key */
412                         qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
413                         if (qskKey.isNull()) {
414                                 logthis("Failed to parse key.");
415                         }
416                 }
417
418                 if (! crt.isEmpty() && qskKey.isNull()) {
419                         /* get key from certificate */
420                         qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
421                         if (! qskKey.isNull()) {
422                                 logthis("Using key from certificate.");
423                         }
424                 }
425
426         }
427 #endif
428         
429         if (!rsa || !x509) {
430                 logthis("Generating new server certificate.");
431
432                 BIO *bio_err;
433                 
434                 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
435                 
436                 bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
437                 
438                 x509 = X509_new();
439                 pkey = EVP_PKEY_new();
440                 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
441                 EVP_PKEY_assign_RSA(pkey, rsa);
442                 
443                 X509_set_version(x509, 2);
444                 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
445                 X509_gmtime_adj(X509_get_notBefore(x509),0);
446                 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
447                 X509_set_pubkey(x509, pkey);
448                 
449                 X509_NAME *name=X509_get_subject_name(x509);
450                 
451                 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
452                 X509_set_issuer_name(x509, name);
453                 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
454                 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
455                 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
456                 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
457                 
458                 X509_sign(x509, pkey, EVP_md5());
459                 
460                 SSL_writecert(crt, x509);
461                 SSL_writekey(key, rsa);
462         }
463
464 }
465
466 void SSLi_init(void)
467 {
468         const SSL_METHOD *method;
469         SSL *ssl;
470         int i, offset = 0;
471         STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
472         SSL_CIPHER *cipher;
473         char cipherstring[1024];
474                 
475         SSL_library_init();
476     OpenSSL_add_all_algorithms();               /* load & register all cryptos, etc. */
477     SSL_load_error_strings();                   /* load all error messages */
478     ERR_load_crypto_strings();                  /* load all error messages */
479     method = SSLv23_server_method();            /* create new server-method instance */
480     context = SSL_CTX_new(method);                      /* create new context from method */
481     if (context == NULL)
482     {
483         ERR_print_errors_fp(stderr);
484         abort();
485     }
486         SSL_initializeCert();
487         if (SSL_CTX_use_certificate(context, x509) <= 0)
488                 Log_fatal("Failed to initialize cert");
489         if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
490                 ERR_print_errors_fp(stderr);
491                 Log_fatal("Failed to initialize private key");
492         }
493
494         /* Set cipher list */
495         ssl = SSL_new(context); 
496         cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
497         cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
498         
499         for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
500                 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
501                         sk_SSL_CIPHER_push(cipherlist_new, cipher);
502                 }
503         }
504         Log_debug("List of ciphers:");
505         if (cipherlist_new) {
506                 for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
507                         Log_debug("%s", SSL_CIPHER_get_name(cipher));
508                         offset += snprintf(cipherstring + offset, 1024 - offset, "%s:", SSL_CIPHER_get_name(cipher));
509                 }
510                 cipherstring[offset - 1] = '\0';
511         }
512         
513         if (cipherlist_new)
514                 sk_SSL_CIPHER_free(cipherlist_new);
515         
516         if (strlen(cipherstring) == 0)
517                 Log_fatal("No suitable ciphers found!");
518         
519         if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
520                 Log_fatal("Failed to set cipher list!");
521                 
522         
523         SSL_free(ssl);
524         Log_info("OpenSSL library initialized");
525
526 }
527
528 void SSLi_deinit(void)
529 {
530         SSL_CTX_free(context);
531         EVP_cleanup();
532 }
533
534 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
535 {
536         int rc;
537         rc = SSL_accept(ssl);
538         if (rc < 0) {
539                 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
540                         SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
541                         Log_debug("SSL not ready");
542                         return 0;
543                 } else {
544                         Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
545                         return -1;
546                 }
547         }
548         *SSLready = true;
549         return 0;
550 }
551
552 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
553 {
554         SSL *ssl;
555         
556         *SSLready = false;
557         ssl = SSL_new(context);
558         SSL_set_fd(ssl, *fd);
559         if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
560                 SSL_free(ssl);
561                 return NULL;
562         }
563         return ssl;
564 }
565
566 void SSLi_closeconnection(SSL_handle_t *ssl)
567 {
568         SSL_free(ssl);
569 }
570
571 void SSLi_shutdown(SSL_handle_t *ssl)
572 {
573         SSL_shutdown(ssl);
574 }
575
576 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
577 {
578         return SSL_read(ssl, buf, len);
579 }
580
581 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
582 {
583         return SSL_write(ssl, buf, len);
584 }
585
586 int SSLi_get_error(SSL_handle_t *ssl, int code)
587 {
588         return SSL_get_error(ssl, code);
589 }
590
591 bool_t SSLi_data_pending(SSL_handle_t *ssl)
592 {
593         return SSL_pending(ssl);
594 }
595
596 void SSLi_free(SSL_handle_t *ssl)
597 {
598         SSL_free(ssl);
599 }
600
601 #endif