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>
48 #include <polarssl/version.h>
52 SSL_EDH_RSA_AES_256_SHA,
53 SSL_EDH_RSA_CAMELLIA_256_SHA,
54 SSL_EDH_RSA_DES_168_SHA,
56 SSL_RSA_CAMELLIA_256_SHA,
58 SSL_RSA_CAMELLIA_128_SHA,
64 static x509_cert certificate;
65 static rsa_context key;
66 bool_t builtInTestCertificate;
68 havege_state hs; /* exported to crypt.c */
72 "9CE85640903BF123906947FEDE767261" \
73 "D9B4A973EB8F7D984A8C656E2BCC161C" \
74 "183D4CA471BA78225F940F16D1D99CA3" \
75 "E66152CC68EDCE1311A390F307741835" \
76 "44FF6AB553EC7073AD0CB608F2A3B480" \
77 "19E6C02BCED40BD30E91BB2469089670" \
78 "DEF409C08E8AC24D1732A6128D2220DC53";
81 static void initTestCert()
84 builtInTestCertificate = true;
85 rc = x509parse_crt(&certificate, (unsigned char *)test_srv_crt,
86 strlen(test_srv_crt));
88 Log_fatal("Could not parse built-in test certificate");
91 static void initTestKey()
95 rc = x509parse_key(&key, (unsigned char *)test_srv_key,
96 strlen(test_srv_key), NULL, 0);
98 Log_fatal("Could not parse built-in test RSA key");
102 * How to generate a self-signed cert with openssl:
103 * openssl genrsa 1024 > host.key
104 * openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert
106 static void initCert()
109 char *crtfile = (char *)getStrConf(CERTIFICATE);
111 if (crtfile == NULL) {
112 Log_warn("No certificate file specified");
116 rc = x509parse_crtfile(&certificate, crtfile);
118 Log_warn("Could not read certificate file %s", crtfile);
124 static void initKey()
127 char *keyfile = (char *)getStrConf(KEY);
130 Log_fatal("No key file specified");
131 rc = x509parse_keyfile(&key, keyfile, NULL);
133 Log_fatal("Could not read RSA key file %s", keyfile);
136 #define DEBUG_LEVEL 0
137 static void pssl_debug(void *ctx, int level, const char *str)
139 if (level <= DEBUG_LEVEL)
140 Log_debug("PolarSSL [level %d]: %s", level, str);
146 if (builtInTestCertificate) {
147 Log_warn("*** Using built-in test certificate and RSA key ***");
148 Log_warn("*** This is not secure! Please use a CA-signed certificate or create a self-signed certificate ***");
154 Log_info("PolarSSL library initialized");
157 void SSLi_deinit(void)
159 x509_free(&certificate);
163 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
169 ssl = malloc(sizeof(ssl_context));
170 ssn = malloc(sizeof(ssl_session));
172 Log_fatal("Out of memory");
173 memset(ssl, 0, sizeof(ssl_context));
174 memset(ssn, 0, sizeof(ssl_session));
178 Log_fatal("Failed to initalize: %d", rc);
180 ssl_set_endpoint(ssl, SSL_IS_SERVER);
181 ssl_set_authmode(ssl, SSL_VERIFY_NONE);
183 ssl_set_rng(ssl, havege_rand, &hs);
184 ssl_set_dbg(ssl, pssl_debug, NULL);
185 ssl_set_bio(ssl, net_recv, fd, net_send, fd);
187 ssl_set_ciphers(ssl, ciphers);
188 ssl_set_session(ssl, 0, 0, ssn);
190 ssl_set_own_cert(ssl, &certificate, &key);
191 ssl_set_dh_param(ssl, my_dhm_P, my_dhm_G);
196 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
200 rc = ssl_handshake(ssl);
202 if (rc == POLARSSL_ERR_NET_TRY_AGAIN) {
205 Log_warn("SSL handshake failed: %d", rc);
213 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
216 rc = ssl_read(ssl, buf, len);
217 if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
218 return SSLI_ERROR_WANT_READ;
222 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
225 rc = ssl_write(ssl, buf, len);
226 if (rc == POLARSSL_ERR_NET_TRY_AGAIN)
227 return SSLI_ERROR_WANT_WRITE;
231 int SSLi_get_error(SSL_handle_t *ssl, int code)
236 bool_t SSLi_data_pending(SSL_handle_t *ssl)
238 return ssl_get_bytes_avail(ssl) > 0;
241 void SSLi_shutdown(SSL_handle_t *ssl)
243 ssl_close_notify(ssl);
246 void SSLi_free(SSL_handle_t *ssl)
248 Log_debug("SSLi_free");
249 free(ssl->session); /* XXX - Hmmm. */
259 #include <openssl/x509v3.h>
260 #include <openssl/ssl.h>
261 #include <openssl/err.h>
262 #include <openssl/safestack.h>
265 static SSL_CTX *context;
266 static EVP_PKEY *pkey;
268 static int SSL_add_ext(X509 * crt, int nid, char *value) {
271 X509V3_set_ctx_nodb(&ctx);
272 X509V3_set_ctx(&ctx, crt, crt, NULL, NULL, 0);
273 ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
277 X509_add_ext(crt, ex, -1);
278 X509_EXTENSION_free(ex);
282 static X509 *SSL_readcert(char *certfile)
287 /* open the private key file */
288 fp = fopen(certfile, "r");
290 Log_warn("Unable to open the X509 file %s for reading.", certfile);
294 /* allocate memory for the cert structure */
297 if (PEM_read_X509(fp, &x509, NULL, NULL) == 0) {
298 /* error reading the x509 information - check the error stack */
299 Log_warn("Error trying to read X509 info.");
308 static RSA *SSL_readprivatekey(char *keyfile)
313 /* open the private key file for reading */
314 fp = fopen(keyfile, "r");
316 Log_warn("Unable to open the private key file %s for reading.", keyfile);
320 /* allocate memory for the RSA structure */
323 /* assign a callback function for the password */
325 /* read a private key from file */
326 if (PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL) <= 0) {
327 /* error reading the key - check the error stack */
328 Log_warn("Error trying to read private key.");
337 static void SSL_writecert(char *certfile, X509 *x509)
342 /* prepare a BIO for outputting error messages */
344 err_output = BIO_new_fp(stderr,BIO_NOCLOSE);
346 /* open the private key file */
347 fp = fopen(certfile, "w");
349 BIO_printf(err_output, "Unable to open the X509 file for writing.\n");
350 BIO_free(err_output);
354 if (PEM_write_X509(fp, x509) == 0) {
355 BIO_printf(err_output, "Error trying to write X509 info.\n");
356 ERR_print_errors(err_output);
361 static void SSL_writekey(char *keyfile, RSA *rsa)
365 /* prepare a BIO for outputing error messages */
366 err_output = BIO_new_fp(stderr, BIO_NOCLOSE);
368 /* open the private key file for reading */
369 fp = fopen(keyfile, "w");
371 BIO_printf(err_output, "Unable to open the private key file %s for writing.\n", keyfile);
372 BIO_free(err_output);
376 if (PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL) == 0) {
377 /* error reading the key - check the error stack */
378 BIO_printf(err_output, "Error trying to write private key\n");
379 ERR_print_errors(err_output);
384 static void SSL_initializeCert() {
385 char *crt, *key, *pass;
387 crt = (char *)getStrConf(CERTIFICATE);
388 key = (char *)getStrConf(KEY);
389 pass = (char *)getStrConf(PASSPHRASE);
391 x509 = SSL_readcert(crt);
392 rsa = SSL_readprivatekey(key);
394 pkey = EVP_PKEY_new();
395 EVP_PKEY_assign_RSA(pkey, rsa);
401 qscCert = QSslCertificate(key);
402 if (! qscCert.isNull()) {
403 logthis("Using certificate from key.");
407 if (! qscCert.isNull()) {
408 QSsl::KeyAlgorithm alg = qscCert.publicKey().algorithm();
409 /* Fetch algorith from cert */
410 if (! key.isEmpty()) {
412 qskKey = QSslKey(key, alg, QSsl::Pem, QSsl::PrivateKey, pass);
413 if (qskKey.isNull()) {
414 logthis("Failed to parse key.");
418 if (! crt.isEmpty() && qskKey.isNull()) {
419 /* get key from certificate */
420 qskKey = QSslKey(crt, alg, QSsl::Pem, QSsl::PrivateKey, pass);
421 if (! qskKey.isNull()) {
422 logthis("Using key from certificate.");
430 logthis("Generating new server certificate.");
434 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
436 bio_err=BIO_new_fp(stderr, BIO_NOCLOSE);
439 pkey = EVP_PKEY_new();
440 rsa = RSA_generate_key(1024,RSA_F4,NULL,NULL);
441 EVP_PKEY_assign_RSA(pkey, rsa);
443 X509_set_version(x509, 2);
444 ASN1_INTEGER_set(X509_get_serialNumber(x509),1);
445 X509_gmtime_adj(X509_get_notBefore(x509),0);
446 X509_gmtime_adj(X509_get_notAfter(x509),60*60*24*365);
447 X509_set_pubkey(x509, pkey);
449 X509_NAME *name=X509_get_subject_name(x509);
451 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (const uint8_t *)"Murmur Autogenerated Certificate v2", -1, -1, 0);
452 X509_set_issuer_name(x509, name);
453 SSL_add_ext(x509, NID_basic_constraints, "critical,CA:FALSE");
454 SSL_add_ext(x509, NID_ext_key_usage, "serverAuth,clientAuth");
455 SSL_add_ext(x509, NID_subject_key_identifier, "hash");
456 SSL_add_ext(x509, NID_netscape_comment, "Generated from umurmur");
458 X509_sign(x509, pkey, EVP_md5());
460 SSL_writecert(crt, x509);
461 SSL_writekey(key, rsa);
468 const SSL_METHOD *method;
471 STACK_OF(SSL_CIPHER) *cipherlist = NULL, *cipherlist_new = NULL;
473 char cipherstring[1024];
476 OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
477 SSL_load_error_strings(); /* load all error messages */
478 ERR_load_crypto_strings(); /* load all error messages */
479 method = SSLv23_server_method(); /* create new server-method instance */
480 context = SSL_CTX_new(method); /* create new context from method */
483 ERR_print_errors_fp(stderr);
486 SSL_initializeCert();
487 if (SSL_CTX_use_certificate(context, x509) <= 0)
488 Log_fatal("Failed to initialize cert");
489 if (SSL_CTX_use_PrivateKey(context, pkey) <= 0) {
490 ERR_print_errors_fp(stderr);
491 Log_fatal("Failed to initialize private key");
494 /* Set cipher list */
495 ssl = SSL_new(context);
496 cipherlist = (STACK_OF(SSL_CIPHER) *) SSL_get_ciphers(ssl);
497 cipherlist_new = (STACK_OF(SSL_CIPHER) *) sk_SSL_CIPHER_new_null();
499 for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist, i)) != NULL; i++) {
500 if (SSL_CIPHER_get_bits(cipher, NULL) >= 128) {
501 sk_SSL_CIPHER_push(cipherlist_new, cipher);
504 Log_debug("List of ciphers:");
505 if (cipherlist_new) {
506 for ( i = 0; (cipher = sk_SSL_CIPHER_value(cipherlist_new, i)) != NULL; i++) {
507 Log_debug("%s", SSL_CIPHER_get_name(cipher));
508 offset += snprintf(cipherstring + offset, 1024 - offset, "%s:", SSL_CIPHER_get_name(cipher));
510 cipherstring[offset - 1] = '\0';
514 sk_SSL_CIPHER_free(cipherlist_new);
516 if (strlen(cipherstring) == 0)
517 Log_fatal("No suitable ciphers found!");
519 if (SSL_CTX_set_cipher_list(context, cipherstring) == 0)
520 Log_fatal("Failed to set cipher list!");
524 Log_info("OpenSSL library initialized");
528 void SSLi_deinit(void)
530 SSL_CTX_free(context);
534 int SSLi_nonblockaccept(SSL_handle_t *ssl, bool_t *SSLready)
537 rc = SSL_accept(ssl);
539 if (SSL_get_error(ssl, rc) == SSL_ERROR_WANT_READ ||
540 SSL_get_error(ssl, rc) == SSL_ERROR_WANT_WRITE) {
541 Log_debug("SSL not ready");
544 Log_warn("SSL error: %s", ERR_error_string(SSL_get_error(ssl, rc), NULL));
552 SSL_handle_t *SSLi_newconnection(int *fd, bool_t *SSLready)
557 ssl = SSL_new(context);
558 SSL_set_fd(ssl, *fd);
559 if (SSLi_nonblockaccept(ssl, SSLready) < 0) {
566 void SSLi_closeconnection(SSL_handle_t *ssl)
571 void SSLi_shutdown(SSL_handle_t *ssl)
576 int SSLi_read(SSL_handle_t *ssl, uint8_t *buf, int len)
578 return SSL_read(ssl, buf, len);
581 int SSLi_write(SSL_handle_t *ssl, uint8_t *buf, int len)
583 return SSL_write(ssl, buf, len);
586 int SSLi_get_error(SSL_handle_t *ssl, int code)
588 return SSL_get_error(ssl, code);
591 bool_t SSLi_data_pending(SSL_handle_t *ssl)
593 return SSL_pending(ssl);
596 void SSLi_free(SSL_handle_t *ssl)