1 /* Copyright (C) 2009-2011, Martin Johansson <martin@fatbob.nu>
2 Copyright (C) 2005-2011, 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.
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>
51 SSL_EDH_RSA_AES_256_SHA,
52 SSL_EDH_RSA_CAMELLIA_256_SHA,
53 SSL_EDH_RSA_DES_168_SHA,
55 SSL_RSA_CAMELLIA_256_SHA,
57 SSL_RSA_CAMELLIA_128_SHA,
63 static x509_cert certificate;
64 static rsa_context key;
65 bool_t builtInTestCertificate;
67 havege_state hs; /* exported to crypt.c */
71 "9CE85640903BF123906947FEDE767261" \
72 "D9B4A973EB8F7D984A8C656E2BCC161C" \
73 "183D4CA471BA78225F940F16D1D99CA3" \
74 "E66152CC68EDCE1311A390F307741835" \
75 "44FF6AB553EC7073AD0CB608F2A3B480" \
76 "19E6C02BCED40BD30E91BB2469089670" \
77 "DEF409C08E8AC24D1732A6128D2220DC53";
80 static void initTestCert()
83 builtInTestCertificate = true;
84 rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
85 strlen(test_srv_crt));
87 Log_fatal("Could not parse built-in test certificate");
90 static void initTestKey()
94 rc = x509parse_key(&key, (unsigned char *)test_srv_key,
95 strlen(test_srv_key), NULL, 0);
97 Log_fatal("Could not parse built-in test RSA key");
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
105 static void initCert()
108 char *crtfile = (char *)getStrConf(CERTIFICATE);
110 if (crtfile == NULL) {
111 Log_warn("No certificate file specified");
115 rc = x509parse_crtfile(&certificate, crtfile);
117 Log_warn("Could not read certificate file %s", crtfile);
123 static void initKey()
126 char *keyfile = (char *)getStrConf(KEY);
129 Log_fatal("No key file specified");
130 rc = x509parse_keyfile(&key, keyfile, NULL);
132 Log_fatal("Could not read RSA key file %s", keyfile);
135 #define DEBUG_LEVEL 0
136 static void pssl_debug(void *ctx, int level, const char *str)
138 if (level <= DEBUG_LEVEL)
139 Log_debug("PolarSSL [level %d]: %s", level, str);
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 ***");
156 #ifdef POLARSSL_VERSION_MAJOR
157 version_get_string(verstring);
158 Log_info("PolarSSL library version %s initialized", verstring);
160 Log_info("PolarSSL library initialized");
164 void SSLi_deinit(void)
166 x509_free(&certificate);
170 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
176 ssl = malloc(sizeof(ssl_context));
177 ssn = malloc(sizeof(ssl_session));
179 Log_fatal("Out of memory");
180 memset(ssl, 0, sizeof(ssl_context));
181 memset(ssn, 0, sizeof(ssl_session));
185 Log_fatal("Failed to initalize: %d", rc);
187 ssl_set_endpoint(ssl, SSL_IS_SERVER);
188 ssl_set_authmode(ssl, SSL_VERIFY_NONE);
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);
194 #ifdef POLARSSL_API_V1
195 ssl_set_ciphersuites(ssl, ciphers);
197 ssl_set_ciphers(ssl, ciphers);
199 ssl_set_session(ssl, 0, 0, ssn);
201 ssl_set_own_cert(ssl, &certificate, &key);
202 ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
207 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
211 rc = ssl_handshake(ssl);
213 #ifdef POLARSSL_API_V1
214 if (rc == POLARSSL_ERR_NET_WANT_READ || rc == POLARSSL_ERR_NET_WANT_WRITE) {
216 if (rc == POLARSSL_ERR_NET_TRY_AGAIN) {
220 Log_warn("SSL handshake failed: %d", rc);
228 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
232 rc = ssl_read(ssl, buf, len);
233 #ifdef POLARSSL_API_V1
234 if (rc == POLARSSL_ERR_NET_WANT_READ)
236 if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
238 return SSLI_ERROR_WANT_READ;
242 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
246 rc = ssl_write(ssl, buf, len);
247 #ifdef POLARSSL_API_V1
248 if (rc == POLARSSL_ERR_NET_WANT_WRITE)
250 if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
252 return SSLI_ERROR_WANT_WRITE;
256 int SSLi_get_error(SSL_handle_t *ssl, int code)
261 bool_t SSLi_data_pending(SSL_handle_t *ssl)
263 return ssl_get_bytes_avail(ssl) > 0;
266 void SSLi_shutdown(SSL_handle_t *ssl)
268 ssl_close_notify(ssl);
271 void SSLi_free(SSL_handle_t *ssl)
273 Log_debug("SSLi_free");
274 free(ssl->session); /* XXX - Hmmm. */
284 #include <openssl/x509v3.h>
285 #include <openssl/ssl.h>
286 #include <openssl/err.h>
287 #include <openssl/safestack.h>
290 static SSL_CTX *context;
291 static EVP_PKEY *pkey;
293 static int SSL_add_ext(X509 * crt, int nid, char *value) {
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);
302 X509_add_ext(crt, ex, -1);
303 X509_EXTENSION_free(ex);
307 static X509 *SSL_readcert(char *certfile)
312 /* open the private key file */
313 fp = fopen(certfile, "r");
315 Log_warn("Unable to open the X509 file %s for reading.", certfile);
319 /* allocate memory for the cert structure */
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.");
333 static RSA *SSL_readprivatekey(char *keyfile)
338 /* open the private key file for reading */
339 fp = fopen(keyfile, "r");
341 Log_warn("Unable to open the private key file %s for reading.", keyfile);
345 /* allocate memory for the RSA structure */
348 /* assign a callback function for the password */
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.");
362 static void SSL_writecert(char *certfile, X509 *x509)
367 /* prepare a BIO for outputting error messages */
369 err_output = BIO_new_fp(stderr,BIO_NOCLOSE);
371 /* open the private key file */
372 fp = fopen(certfile, "w");
374 BIO_printf(err_output, "Unable to open the X509 file for writing.\n");
375 BIO_free(err_output);
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);
386 static void SSL_writekey(char *keyfile, RSA *rsa)
390 /* prepare a BIO for outputing error messages */
391 err_output = BIO_new_fp(stderr, BIO_NOCLOSE);
393 /* open the private key file for reading */
394 fp = fopen(keyfile, "w");
396 BIO_printf(err_output, "Unable to open the private key file %s for writing.\n", keyfile);
397 BIO_free(err_output);
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);
409 static void SSL_initializeCert() {
410 char *crt, *key, *pass;
412 crt = (char *)getStrConf(CERTIFICATE);
413 key = (char *)getStrConf(KEY);
414 pass = (char *)getStrConf(PASSPHRASE);
416 x509 = SSL_readcert(crt);
417 rsa = SSL_readprivatekey(key);
419 pkey = EVP_PKEY_new();
420 EVP_PKEY_assign_RSA(pkey, rsa);
426 qscCert = QSslCertificate(key);
427 if (! qscCert.isNull()) {
428 logthis("Using certificate from key.");
432 if (! qscCert.isNull()) {
433 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
434 /* Fetch algorith from cert */
435 if (! key.isEmpty()) {
437 qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
438 if (qskKey.isNull()) {
439 logthis("Failed to parse key.");
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.");
455 logthis("Generating new server certificate.");
459 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
461 bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
464 pkey = EVP_PKEY_new();
465 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
466 EVP_PKEY_assign_RSA(pkey, rsa);
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);
474 X509_NAME *name=X509_get_subject_name(x509);
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");
483 X509_sign(x509, pkey, EVP_md5());
485 SSL_writecert(crt, x509);
486 SSL_writekey(key, rsa);
493 const SSL_METHOD *method;
496 STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
498 char cipherstring[1024];
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 */
508 ERR_print_errors_fp(stderr);
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");
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();
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);
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));
535 cipherstring[offset - 1] = '\0';
539 sk_SSL_CIPHER_free(cipherlist_new);
541 if (strlen(cipherstring) == 0)
542 Log_fatal("No suitable ciphers found!");
544 if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
545 Log_fatal("Failed to set cipher list!");
549 Log_info("OpenSSL library initialized");
553 void SSLi_deinit(void)
555 SSL_CTX_free(context);
559 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
562 rc = SSL_accept(ssl);
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");
569 Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
577 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
582 ssl = SSL_new(context);
583 SSL_set_fd(ssl, *fd);
584 if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
591 void SSLi_closeconnection(SSL_handle_t *ssl)
596 void SSLi_shutdown(SSL_handle_t *ssl)
601 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
603 return SSL_read(ssl, buf, len);
606 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
608 return SSL_write(ssl, buf, len);
611 int SSLi_get_error(SSL_handle_t *ssl, int code)
613 return SSL_get_error(ssl, code);
616 bool_t SSLi_data_pending(SSL_handle_t *ssl)
618 return SSL_pending(ssl);
621 void SSLi_free(SSL_handle_t *ssl)