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