1 /* Copyright (C) 2009-2013, Martin Johansson <martin@fatbob.nu>
2 Copyright (C) 2005-2013, 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/config.h>
45 #include <polarssl/havege.h>
46 #include <polarssl/certs.h>
47 #include <polarssl/x509.h>
48 #include <polarssl/ssl.h>
49 #include <polarssl/net.h>
51 #ifdef POLARSSL_API_V1_2_ABOVE
54 TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
55 TLS_RSA_WITH_AES_256_CBC_SHA,
56 TLS_RSA_WITH_AES_128_CBC_SHA,
62 SSL_EDH_RSA_AES_256_SHA,
69 #ifdef POLARSSL_API_V1_3_ABOVE
70 static x509_crt certificate;
71 static inline int x509parse_keyfile(rsa_context *rsa, const char *path,
78 ret = pk_parse_keyfile(&pk, path, pwd);
79 if (ret == 0 && !pk_can_do( &pk, POLARSSL_PK_RSA))
80 ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
82 rsa_copy(rsa, pk_rsa(pk));
89 static x509_cert certificate;
92 static rsa_context key;
93 bool_t builtInTestCertificate;
95 #ifdef USE_POLARSSL_HAVEGE
103 "9CE85640903BF123906947FEDE767261" \
104 "D9B4A973EB8F7D984A8C656E2BCC161C" \
105 "183D4CA471BA78225F940F16D1D99CA3" \
106 "E66152CC68EDCE1311A390F307741835" \
107 "44FF6AB553EC7073AD0CB608F2A3B480" \
108 "19E6C02BCED40BD30E91BB2469089670" \
109 "DEF409C08E8AC24D1732A6128D2220DC53";
110 char *my_dhm_G = "4";
112 #ifdef USE_POLARSSL_TESTCERT
113 static void initTestCert()
116 builtInTestCertificate = true;
117 #ifdef POLARSSL_API_V1_3_ABOVE
118 rc = x509_crt_parse_rsa(&certificate, (unsigned char *)test_srv_crt,
119 strlen(test_srv_crt));
121 rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
122 strlen(test_srv_crt));
125 Log_fatal("Could not parse built-in test certificate");
128 static void initTestKey()
132 rc = x509parse_key_rsa(&key, (unsigned char *)test_srv_key,
133 strlen(test_srv_key), NULL, 0);
135 Log_fatal("Could not parse built-in test RSA key");
140 * How to generate a self-signed cert with openssl:
141 * openssl genrsa 1024 > host.key
142 * openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert
144 static void initCert()
147 char *crtfile = (char *)getStrConf(CERTIFICATE);
149 if (crtfile == NULL) {
150 #ifdef USE_POLARSSL_TESTCERT
151 Log_warn("No certificate file specified. Falling back to test certificate.");
154 Log_fatal("No certificate file specified");
158 #ifdef POLARSSL_API_V1_3_ABOVE
159 rc = x509_crt_parse_file(&certificate, crtfile);
161 rc = x509parse_crtfile(&certificate, crtfile);
164 #ifdef USE_POLARSSL_TESTCERT
165 Log_warn("Could not read certificate file '%s'. Falling back to test certificate.", crtfile);
168 Log_fatal("Could not read certificate file '%s'", crtfile);
174 static void initKey()
177 char *keyfile = (char *)getStrConf(KEY);
180 Log_fatal("No key file specified");
181 rc = x509parse_keyfile(&key, keyfile, NULL);
183 Log_fatal("Could not read RSA key file %s", keyfile);
186 #ifndef USE_POLARSSL_HAVEGE
187 int urandom_bytes(void *ctx, unsigned char *dest, size_t len)
192 cur = read(urandom_fd, dest, len);
201 #define DEBUG_LEVEL 0
202 static void pssl_debug(void *ctx, int level, const char *str)
204 if (level <= DEBUG_LEVEL)
205 Log_info("PolarSSL [level %d]: %s", level, str);
213 #ifdef USE_POLARSSL_TESTCERT
214 if (builtInTestCertificate) {
215 Log_warn("*** Using built-in test certificate and RSA key ***");
216 Log_warn("*** This is not secure! Please use a CA-signed certificate or create a key and self-signed certificate ***");
225 /* Initialize random number generator */
226 #ifdef USE_POLARSSL_HAVEGE
229 urandom_fd = open("/dev/urandom", O_RDONLY);
231 Log_fatal("Cannot open /dev/urandom");
234 version_get_string(verstring);
235 Log_info("PolarSSL library version %s initialized", verstring);
238 void SSLi_deinit(void)
240 #ifdef POLARSSL_API_V1_3_ABOVE
241 x509_crt_free(&certificate);
243 x509_free(&certificate);
248 /* Create SHA1 of last certificate in the peer's chain. */
249 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
251 #ifdef POLARSSL_API_V1_3_ABOVE
252 x509_crt const *cert;
254 x509_cert const *cert;
256 #ifdef POLARSSL_API_V1_2_ABOVE
257 cert = ssl_get_peer_cert(ssl);
259 cert = ssl->peer_cert;
264 sha1(cert->raw.p, cert->raw.len, hash);
268 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
274 ssl = malloc(sizeof(ssl_context));
275 ssn = malloc(sizeof(ssl_session));
277 Log_fatal("Out of memory");
278 memset(ssl, 0, sizeof(ssl_context));
279 memset(ssn, 0, sizeof(ssl_session));
283 Log_fatal("Failed to initialize: %d", rc);
285 ssl_set_endpoint(ssl, SSL_IS_SERVER);
286 ssl_set_authmode(ssl, SSL_VERIFY_OPTIONAL);
288 #ifdef USE_POLARSSL_HAVEGE
289 ssl_set_rng(ssl, HAVEGE_RAND, &hs);
291 ssl_set_rng(ssl, urandom_bytes, NULL);
294 ssl_set_dbg(ssl, pssl_debug, NULL);
295 ssl_set_bio(ssl, net_recv, fd, net_send, fd);
297 ssl_set_ciphersuites(ssl, ciphers);
299 #ifdef POLARSSL_API_V1_2_ABOVE
300 ssl_set_session(ssl, ssn);
302 ssl_set_session(ssl, 0, 0, ssn);
305 ssl_set_ca_chain(ssl, &certificate, NULL, NULL);
306 #ifdef POLARSSL_API_V1_3_ABOVE
307 ssl_set_own_cert_rsa(ssl, &certificate, &key);
309 ssl_set_own_cert(ssl, &certificate, &key);
311 ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
316 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
320 rc = ssl_handshake(ssl);
322 if (rc == POLARSSL_ERR_NET_WANT_READ || rc == POLARSSL_ERR_NET_WANT_WRITE) {
324 } else if (rc == POLARSSL_ERR_X509_CERT_VERIFY_FAILED) { /* Allow this (selfsigned etc) */
327 Log_warn("SSL handshake failed: %d", rc);
335 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
339 rc = ssl_read(ssl, buf, len);
340 if (rc == POLARSSL_ERR_NET_WANT_READ)
341 return SSLI_ERROR_WANT_READ;
345 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
349 rc = ssl_write(ssl, buf, len);
350 if (rc == POLARSSL_ERR_NET_WANT_WRITE)
351 return SSLI_ERROR_WANT_WRITE;
355 int SSLi_get_error(SSL_handle_t *ssl, int code)
360 bool_t SSLi_data_pending(SSL_handle_t *ssl)
362 return ssl_get_bytes_avail(ssl) > 0;
365 void SSLi_shutdown(SSL_handle_t *ssl)
367 ssl_close_notify(ssl);
370 void SSLi_free(SSL_handle_t *ssl)
372 Log_debug("SSLi_free");
373 #if (POLARSSL_VERSION_MINOR <= 2 && POLARSSL_VERSION_PATCH < 6)
374 free(ssl->session); /* Workaround for memory leak in PolarSSL < 1.2.6 */
386 #include <openssl/x509v3.h>
387 #include <openssl/ssl.h>
388 #include <openssl/err.h>
389 #include <openssl/safestack.h>
392 static SSL_CTX *context;
393 static EVP_PKEY *pkey;
395 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx);
397 static int SSL_add_ext(X509 * crt, int nid, char *value) {
400 X509V3_set_ctx_nodb(&ctx);
401 X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
402 ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
406 X509_add_ext(crt, ex, -1);
407 X509_EXTENSION_free(ex);
411 static X509 *SSL_readcert(char *certfile)
416 /* open the certificate file */
417 fp = fopen(certfile, "r");
419 Log_warn("Unable to open the X509 file %s for reading.", certfile);
423 /* allocate memory for the cert structure */
426 if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
427 /* error reading the x509 information - check the error stack */
428 Log_warn("Error trying to read X509 info.");
437 static RSA *SSL_readprivatekey(char *keyfile)
442 /* open the private key file for reading */
443 fp = fopen(keyfile, "r");
445 Log_warn("Unable to open the private key file %s for reading.", keyfile);
449 /* allocate memory for the RSA structure */
452 /* assign a callback function for the password */
454 /* read a private key from file */
455 if (PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL) <= 0) {
456 /* error reading the key - check the error stack */
457 Log_warn("Error trying to read private key.");
466 static void SSL_writecert(char *certfile, X509 *x509)
470 /* open the private key file */
471 fp = fopen(certfile, "w");
473 Log_warn("Unable to open the X509 file %s for writing", certfile);
476 if (PEM_write_X509(fp, x509) == 0) {
477 Log_warn("Error trying to write X509 info.");
482 static void SSL_writekey(char *keyfile, RSA *rsa)
486 /* open the private key file for reading */
487 fp = fopen(keyfile, "w");
489 Log_warn("Unable to open the private key file %s for writing.", keyfile);
493 if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
494 Log_warn("Error trying to write private key");
499 static void SSL_initializeCert() {
501 char *crt, *key, *pass;
503 crt = (char *)getStrConf(CERTIFICATE);
504 key = (char *)getStrConf(KEY);
505 pass = (char *)getStrConf(PASSPHRASE);
507 x509 = SSL_readcert(crt);
508 rsa = SSL_readprivatekey(key);
510 pkey = EVP_PKEY_new();
511 EVP_PKEY_assign_RSA(pkey, rsa);
518 qscCert = QSslCertificate(key);
519 if (! qscCert.isNull()) {
520 logthis("Using certificate from key.");
524 if (! qscCert.isNull()) {
525 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
526 /* Fetch algorith from cert */
527 if (! key.isEmpty()) {
529 qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
530 if (qskKey.isNull()) {
531 logthis("Failed to parse key.");
535 if (! crt.isEmpty() && qskKey.isNull()) {
536 /* get key from certificate */
537 qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
538 if (! qskKey.isNull()) {
539 logthis("Using key from certificate.");
547 Log_info("Generating new server certificate.");
550 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
553 pkey = EVP_PKEY_new();
554 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
555 EVP_PKEY_assign_RSA(pkey, rsa);
557 X509_set_version(x509, 2);
558 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
559 X509_gmtime_adj(X509_get_notBefore(x509),0);
560 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
561 X509_set_pubkey(x509, pkey);
563 X509_NAME *name=X509_get_subject_name(x509);
565 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
566 X509_set_issuer_name(x509, name);
567 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
568 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
569 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
570 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
572 X509_sign(x509, pkey, EVP_md5());
574 SSL_writecert(crt, x509);
575 SSL_writekey(key, rsa);
582 const SSL_METHOD *method;
584 int i, offset = 0, cipherstringlen = 0;
585 STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
587 char *cipherstring, tempstring[128];
590 OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
591 SSL_load_error_strings(); /* load all error messages */
592 ERR_load_crypto_strings(); /* load all error messages */
593 method = SSLv23_server_method(); /* create new server-method instance */
594 context = SSL_CTX_new(method); /* create new context from method */
597 ERR_print_errors_fp(stderr);
601 char* sslCAPath = getStrConf(CAPATH);
602 if(sslCAPath != NULL)
604 SSL_CTX_load_verify_locations(context, NULL, sslCAPath);
607 SSL_initializeCert();
608 if (SSL_CTX_use_certificate(context, x509) <= 0)
609 Log_fatal("Failed to initialize cert");
610 if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
611 ERR_print_errors_fp(stderr);
612 Log_fatal("Failed to initialize private key");
615 /* Set cipher list */
616 ssl = SSL_new(context);
617 cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
618 cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
620 for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
621 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
622 sk_SSL_CIPHER_push(cipherlist_new, cipher);
625 Log_debug("List of ciphers:");
626 if (cipherlist_new) {
627 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
628 Log_debug("%s", SSL_CIPHER_get_name(cipher));
629 cipherstringlen += strlen(SSL_CIPHER_get_name(cipher)) + 1;
631 cipherstring = malloc(cipherstringlen + 1);
632 if (cipherstring == NULL)
633 Log_fatal("Out of memory");
634 for (i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
635 offset += sprintf(cipherstring + offset, "%s:", SSL_CIPHER_get_name(cipher));
640 sk_SSL_CIPHER_free(cipherlist_new);
642 if (strlen(cipherstring) == 0)
643 Log_fatal("No suitable ciphers found!");
645 if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
646 Log_fatal("Failed to set cipher list!");
650 SSL_CTX_set_verify(context, SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
654 Log_info("OpenSSL library initialized");
658 void SSLi_deinit(void)
660 SSL_CTX_free(context);
664 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
667 rc = SSL_accept(ssl);
669 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
670 SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
671 Log_debug("SSL not ready");
674 Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
682 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
687 ssl = SSL_new(context);
688 SSL_set_fd(ssl, *fd);
689 if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
696 /* Create SHA1 of last certificate in the peer's chain. */
697 bool_t SSLi_getSHA1Hash(SSL_handle_t *ssl, uint8_t *hash)
703 x509 = SSL_get_peer_certificate(ssl);
708 len = i2d_X509(x509, NULL);
717 SHA1(buf, len, hash);
722 void SSLi_closeconnection(SSL_handle_t *ssl)
727 void SSLi_shutdown(SSL_handle_t *ssl)
732 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
734 return SSL_read(ssl, buf, len);
737 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
739 return SSL_write(ssl, buf, len);
742 int SSLi_get_error(SSL_handle_t *ssl, int code)
744 return SSL_get_error(ssl, code);
747 bool_t SSLi_data_pending(SSL_handle_t *ssl)
749 return SSL_pending(ssl);
752 void SSLi_free(SSL_handle_t *ssl)
757 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
764 err_cert = X509_STORE_CTX_get_current_cert(ctx);
765 err = X509_STORE_CTX_get_error(ctx);
766 depth = X509_STORE_CTX_get_error_depth(ctx);
768 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
769 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
773 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
774 X509_STORE_CTX_set_error(ctx, err);
777 Log_warn("SSL: verify error:num=%d:%s:depth=%d:%s\n", err,
778 X509_verify_cert_error_string(err), depth, buf);
781 * At this point, err contains the last verification error. We can use
782 * it for something special
784 if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) {
785 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
786 Log_warn("issuer= %s", buf);