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