1 /* Copyright (C) 2009-2012, Martin Johansson <martin@fatbob.nu>
2 Copyright (C) 2005-2012, Thorvald Natvig <thorvald@natvig.com>
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
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.
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.
44 #include <polarssl/havege.h>
45 #include <polarssl/certs.h>
46 #include <polarssl/x509.h>
47 #include <polarssl/ssl.h>
48 #include <polarssl/net.h>
50 #ifdef POLARSSL_API_V1_2
53 TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
54 TLS_RSA_WITH_AES_256_CBC_SHA,
55 TLS_RSA_WITH_AES_128_CBC_SHA,
61 SSL_EDH_RSA_AES_256_SHA,
67 static x509_cert certificate;
68 static rsa_context key;
69 bool_t builtInTestCertificate;
71 #ifdef USE_POLARSSL_HAVEGE
79 "9CE85640903BF123906947FEDE767261" \
80 "D9B4A973EB8F7D984A8C656E2BCC161C" \
81 "183D4CA471BA78225F940F16D1D99CA3" \
82 "E66152CC68EDCE1311A390F307741835" \
83 "44FF6AB553EC7073AD0CB608F2A3B480" \
84 "19E6C02BCED40BD30E91BB2469089670" \
85 "DEF409C08E8AC24D1732A6128D2220DC53";
88 #ifdef USE_POLARSSL_TESTCERT
89 static void initTestCert()
92 builtInTestCertificate = true;
93 rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
94 strlen(test_srv_crt));
96 Log_fatal("Could not parse built-in test certificate");
99 static void initTestKey()
103 rc = x509parse_key(&key, (unsigned char *)test_srv_key,
104 strlen(test_srv_key), NULL, 0);
106 Log_fatal("Could not parse built-in test RSA key");
111 * How to generate a self-signed cert with openssl:
112 * openssl genrsa 1024 > host.key
113 * openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert
115 static void initCert()
118 char *crtfile = (char *)getStrConf(CERTIFICATE);
120 if (crtfile == NULL) {
121 #ifdef USE_POLARSSL_TESTCERT
122 Log_warn("No certificate file specified. Falling back to test certificate.");
125 Log_fatal("No certificate file specified");
129 rc = x509parse_crtfile(&certificate, crtfile);
131 #ifdef USE_POLARSSL_TESTCERT
132 Log_warn("Could not read certificate file '%s'. Falling back to test certificate.", crtfile);
135 Log_fatal("Could not read certificate file '%s'", crtfile);
141 static void initKey()
144 char *keyfile = (char *)getStrConf(KEY);
147 Log_fatal("No key file specified");
148 rc = x509parse_keyfile(&key, keyfile, NULL);
150 Log_fatal("Could not read RSA key file %s", keyfile);
153 #ifndef USE_POLARSSL_HAVEGE
154 int urandom_bytes(void *ctx, unsigned char *dest, size_t len)
159 cur = read(urandom_fd, dest, len);
167 #define DEBUG_LEVEL 0
168 static void pssl_debug(void *ctx, int level, const char *str)
170 if (level <= DEBUG_LEVEL)
171 Log_info("PolarSSL [level %d]: %s", level, str);
179 #ifdef USE_POLARSSL_TESTCERT
180 if (builtInTestCertificate) {
181 Log_warn("*** Using built-in test certificate and RSA key ***");
182 Log_warn("*** This is not secure! Please use a CA-signed certificate or create a key and self-signed certificate ***");
191 /* Initialize random number generator */
192 #ifdef USE_POLARSSL_HAVEGE
195 urandom_fd = open("/dev/urandom", O_RDONLY);
197 Log_fatal("Cannot open /dev/urandom");
200 version_get_string(verstring);
201 Log_info("PolarSSL library version %s initialized", verstring);
204 void SSLi_deinit(void)
206 x509_free(&certificate);
210 /* Create SHA1 of last certificate in the peer's chain. */
211 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
213 x509_cert const *cert;
214 #ifdef POLARSSL_API_V1_2
215 cert = ssl_get_peer_cert(ssl);
217 cert = ssl->peer_cert;
222 sha1(cert->raw.p, cert->raw.len, hash);
226 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
232 ssl = malloc(sizeof(ssl_context));
233 ssn = malloc(sizeof(ssl_session));
235 Log_fatal("Out of memory");
236 memset(ssl, 0, sizeof(ssl_context));
237 memset(ssn, 0, sizeof(ssl_session));
241 Log_fatal("Failed to initialize: %d", rc);
243 ssl_set_endpoint(ssl, SSL_IS_SERVER);
244 ssl_set_authmode(ssl, SSL_VERIFY_OPTIONAL);
246 #ifdef USE_POLARSSL_HAVEGE
247 ssl_set_rng(ssl, HAVEGE_RAND, &hs);
249 ssl_set_rng(ssl, urandom_bytes, NULL);
252 ssl_set_dbg(ssl, pssl_debug, NULL);
253 ssl_set_bio(ssl, net_recv, fd, net_send, fd);
255 ssl_set_ciphersuites(ssl, ciphers);
257 #ifdef POLARSSL_API_V1_2
258 ssl_set_session(ssl, ssn);
260 ssl_set_session(ssl, 0, 0, ssn);
263 ssl_set_ca_chain(ssl, &certificate, NULL, NULL);
264 ssl_set_own_cert(ssl, &certificate, &key);
265 ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
270 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
274 rc = ssl_handshake(ssl);
276 if (rc == POLARSSL_ERR_NET_WANT_READ || rc == POLARSSL_ERR_NET_WANT_WRITE) {
278 } else if (POLARSSL_ERR_X509_CERT_VERIFY_FAILED) { /* Allow this (selfsigned etc) */
281 Log_warn("SSL handshake failed: %d", rc);
289 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
293 rc = ssl_read(ssl, buf, len);
294 if (rc == POLARSSL_ERR_NET_WANT_READ)
295 return SSLI_ERROR_WANT_READ;
299 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
303 rc = ssl_write(ssl, buf, len);
304 if (rc == POLARSSL_ERR_NET_WANT_WRITE)
305 return SSLI_ERROR_WANT_WRITE;
309 int SSLi_get_error(SSL_handle_t *ssl, int code)
314 bool_t SSLi_data_pending(SSL_handle_t *ssl)
316 return ssl_get_bytes_avail(ssl) > 0;
319 void SSLi_shutdown(SSL_handle_t *ssl)
321 ssl_close_notify(ssl);
324 void SSLi_free(SSL_handle_t *ssl)
326 Log_debug("SSLi_free");
327 free(ssl->session); /* XXX - Hmmm. */
337 #include <openssl/x509v3.h>
338 #include <openssl/ssl.h>
339 #include <openssl/err.h>
340 #include <openssl/safestack.h>
343 static SSL_CTX *context;
344 static EVP_PKEY *pkey;
346 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx);
348 static int SSL_add_ext(X509 * crt, int nid, char *value) {
351 X509V3_set_ctx_nodb(&ctx);
352 X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
353 ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
357 X509_add_ext(crt, ex, -1);
358 X509_EXTENSION_free(ex);
362 static X509 *SSL_readcert(char *certfile)
367 /* open the private key file */
368 fp = fopen(certfile, "r");
370 Log_warn("Unable to open the X509 file %s for reading.", certfile);
374 /* allocate memory for the cert structure */
377 if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
378 /* error reading the x509 information - check the error stack */
379 Log_warn("Error trying to read X509 info.");
388 static RSA *SSL_readprivatekey(char *keyfile)
393 /* open the private key file for reading */
394 fp = fopen(keyfile, "r");
396 Log_warn("Unable to open the private key file %s for reading.", keyfile);
400 /* allocate memory for the RSA structure */
403 /* assign a callback function for the password */
405 /* read a private key from file */
406 if (PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL) <= 0) {
407 /* error reading the key - check the error stack */
408 Log_warn("Error trying to read private key.");
417 static void SSL_writecert(char *certfile, X509 *x509)
421 /* open the private key file */
422 fp = fopen(certfile, "w");
424 Log_warn("Unable to open the X509 file %s for writing", certfile);
427 if (PEM_write_X509(fp, x509) == 0) {
428 Log_warn("Error trying to write X509 info.");
433 static void SSL_writekey(char *keyfile, RSA *rsa)
437 /* open the private key file for reading */
438 fp = fopen(keyfile, "w");
440 Log_warn("Unable to open the private key file %s for writing.", keyfile);
444 if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
445 Log_warn("Error trying to write private key");
450 static void SSL_initializeCert() {
451 char *crt, *key, *pass;
453 crt = (char *)getStrConf(CERTIFICATE);
454 key = (char *)getStrConf(KEY);
455 pass = (char *)getStrConf(PASSPHRASE);
457 x509 = SSL_readcert(crt);
458 rsa = SSL_readprivatekey(key);
460 pkey = EVP_PKEY_new();
461 EVP_PKEY_assign_RSA(pkey, rsa);
467 qscCert = QSslCertificate(key);
468 if (! qscCert.isNull()) {
469 logthis("Using certificate from key.");
473 if (! qscCert.isNull()) {
474 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
475 /* Fetch algorith from cert */
476 if (! key.isEmpty()) {
478 qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
479 if (qskKey.isNull()) {
480 logthis("Failed to parse key.");
484 if (! crt.isEmpty() && qskKey.isNull()) {
485 /* get key from certificate */
486 qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
487 if (! qskKey.isNull()) {
488 logthis("Using key from certificate.");
496 Log_info("Generating new server certificate.");
499 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
502 pkey = EVP_PKEY_new();
503 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
504 EVP_PKEY_assign_RSA(pkey, rsa);
506 X509_set_version(x509, 2);
507 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
508 X509_gmtime_adj(X509_get_notBefore(x509),0);
509 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
510 X509_set_pubkey(x509, pkey);
512 X509_NAME *name=X509_get_subject_name(x509);
514 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
515 X509_set_issuer_name(x509, name);
516 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
517 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
518 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
519 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
521 X509_sign(x509, pkey, EVP_md5());
523 SSL_writecert(crt, x509);
524 SSL_writekey(key, rsa);
531 const SSL_METHOD *method;
533 int i, offset = 0, cipherstringlen = 0;
534 STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
536 char *cipherstring, tempstring[128];
539 OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
540 SSL_load_error_strings(); /* load all error messages */
541 ERR_load_crypto_strings(); /* load all error messages */
542 method = SSLv23_server_method(); /* create new server-method instance */
543 context = SSL_CTX_new(method); /* create new context from method */
546 ERR_print_errors_fp(stderr);
549 SSL_initializeCert();
550 if (SSL_CTX_use_certificate(context, x509) <= 0)
551 Log_fatal("Failed to initialize cert");
552 if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
553 ERR_print_errors_fp(stderr);
554 Log_fatal("Failed to initialize private key");
557 /* Set cipher list */
558 ssl = SSL_new(context);
559 cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
560 cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
562 for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
563 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
564 sk_SSL_CIPHER_push(cipherlist_new, cipher);
567 Log_debug("List of ciphers:");
568 if (cipherlist_new) {
569 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
570 Log_debug("%s", SSL_CIPHER_get_name(cipher));
571 cipherstringlen += strlen(SSL_CIPHER_get_name(cipher)) + 1;
573 cipherstring = malloc(cipherstringlen + 1);
574 if (cipherstring == NULL)
575 Log_fatal("Out of memory");
576 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
577 offset += sprintf(cipherstring + offset, "%s:", SSL_CIPHER_get_name(cipher));
582 sk_SSL_CIPHER_free(cipherlist_new);
584 if (strlen(cipherstring) == 0)
585 Log_fatal("No suitable ciphers found!");
587 if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
588 Log_fatal("Failed to set cipher list!");
592 SSL_CTX_set_verify(context, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
596 Log_info("OpenSSL library initialized");
600 void SSLi_deinit(void)
602 SSL_CTX_free(context);
606 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
609 rc = SSL_accept(ssl);
611 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
612 SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
613 Log_debug("SSL not ready");
616 Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
624 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
629 ssl = SSL_new(context);
630 SSL_set_fd(ssl, *fd);
631 if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
638 /* Create SHA1 of last certificate in the peer's chain. */
639 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
645 x509 = SSL_get_peer_certificate(ssl);
650 len = i2d_X509(x509, NULL);
659 SHA1(buf, len, hash);
664 void SSLi_closeconnection(SSL_handle_t *ssl)
669 void SSLi_shutdown(SSL_handle_t *ssl)
674 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
676 return SSL_read(ssl, buf, len);
679 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
681 return SSL_write(ssl, buf, len);
684 int SSLi_get_error(SSL_handle_t *ssl, int code)
686 return SSL_get_error(ssl, code);
689 bool_t SSLi_data_pending(SSL_handle_t *ssl)
691 return SSL_pending(ssl);
694 void SSLi_free(SSL_handle_t *ssl)
699 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
706 err_cert = X509_STORE_CTX_get_current_cert(ctx);
707 err = X509_STORE_CTX_get_error(ctx);
708 depth = X509_STORE_CTX_get_error_depth(ctx);
710 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
711 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
715 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
716 X509_STORE_CTX_set_error(ctx, err);
719 Log_warn("SSL: verify error:num=%d:%s:depth=%d:%s\n", err,
720 X509_verify_cert_error_string(err), depth, buf);
723 * At this point, err contains the last verification error. We can use
724 * it for something special
726 if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
727 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
728 Log_warn("issuer= %s", buf);