2 * Copyright (c) 2018 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include <openssl/ssl.h>
17 #include <openssl/conf.h>
18 #include <openssl/err.h>
20 #ifdef HAVE_OPENSSL_ASYNC
21 #include <openssl/async.h>
24 #include <vnet/plugin/plugin.h>
25 #include <vpp/app/version.h>
26 #include <vnet/tls/tls.h>
28 #include <tlsopenssl/tls_openssl.h>
29 #include <tlsopenssl/tls_bios.h>
30 #include <openssl/x509_vfy.h>
31 #include <openssl/x509v3.h>
33 #define MAX_CRYPTO_LEN 64
35 openssl_main_t openssl_main;
38 openssl_ctx_alloc_w_thread (u32 thread_index)
40 openssl_main_t *om = &openssl_main;
43 pool_get (om->ctx_pool[thread_index], ctx);
45 *ctx = clib_mem_alloc (sizeof (openssl_ctx_t));
47 clib_memset (*ctx, 0, sizeof (openssl_ctx_t));
48 (*ctx)->ctx.c_thread_index = thread_index;
49 (*ctx)->ctx.tls_ctx_engine = CRYPTO_ENGINE_OPENSSL;
50 (*ctx)->ctx.app_session_handle = SESSION_INVALID_HANDLE;
51 (*ctx)->openssl_ctx_index = ctx - om->ctx_pool[thread_index];
52 return ((*ctx)->openssl_ctx_index);
56 openssl_ctx_alloc (void)
58 return openssl_ctx_alloc_w_thread (vlib_get_thread_index ());
62 openssl_ctx_free (tls_ctx_t * ctx)
64 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
66 /* Cleanup ssl ctx unless migrated */
67 if (!ctx->is_migrated)
69 if (SSL_is_init_finished (oc->ssl) && !ctx->is_passive_close)
70 SSL_shutdown (oc->ssl);
73 vec_free (ctx->srv_hostname);
75 #ifdef HAVE_OPENSSL_ASYNC
76 openssl_evt_free (ctx->evt_index, ctx->c_thread_index);
80 pool_put_index (openssl_main.ctx_pool[ctx->c_thread_index],
81 oc->openssl_ctx_index);
85 openssl_ctx_detach (tls_ctx_t *ctx)
87 openssl_ctx_t *oc = (openssl_ctx_t *) ctx, *oc_copy;
89 oc_copy = clib_mem_alloc (sizeof (*oc_copy));
90 clib_memcpy (oc_copy, oc, sizeof (*oc));
96 openssl_ctx_attach (u32 thread_index, void *ctx_ptr)
98 openssl_main_t *om = &openssl_main;
102 pool_get (om->ctx_pool[thread_index], oc);
103 /* Free the old instance instead of looking for an empty spot */
108 (*oc)->openssl_ctx_index = oc - om->ctx_pool[thread_index];
109 (*oc)->ctx.c_thread_index = thread_index;
111 sh = (*oc)->ctx.tls_session_handle;
112 BIO_set_data ((*oc)->rbio, uword_to_pointer (sh, void *));
113 BIO_set_data ((*oc)->wbio, uword_to_pointer (sh, void *));
115 return ((*oc)->openssl_ctx_index);
119 openssl_ctx_get (u32 ctx_index)
122 ctx = pool_elt_at_index (openssl_main.ctx_pool[vlib_get_thread_index ()],
128 openssl_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
131 ctx = pool_elt_at_index (openssl_main.ctx_pool[thread_index], ctx_index);
136 openssl_listen_ctx_alloc (void)
138 openssl_main_t *om = &openssl_main;
139 openssl_listen_ctx_t *lctx;
141 pool_get (om->lctx_pool, lctx);
143 clib_memset (lctx, 0, sizeof (openssl_listen_ctx_t));
144 lctx->openssl_lctx_index = lctx - om->lctx_pool;
145 return lctx->openssl_lctx_index;
149 openssl_listen_ctx_free (openssl_listen_ctx_t * lctx)
151 pool_put_index (openssl_main.lctx_pool, lctx->openssl_lctx_index);
154 openssl_listen_ctx_t *
155 openssl_lctx_get (u32 lctx_index)
157 return pool_elt_at_index (openssl_main.lctx_pool, lctx_index);
160 #define ossl_check_err_is_fatal(_ssl, _rv) \
161 if (PREDICT_FALSE (_rv < 0 && SSL_get_error (_ssl, _rv) == SSL_ERROR_SSL)) \
165 openssl_read_from_ssl_into_fifo (svm_fifo_t * f, SSL * ssl)
167 int read, rv, n_fs, i;
168 const int n_segs = 2;
169 svm_fifo_seg_t fs[n_segs];
172 max_enq = svm_fifo_max_enqueue_prod (f);
176 n_fs = svm_fifo_provision_chunks (f, fs, n_segs, max_enq);
180 /* Return early if we can't read anything */
181 read = SSL_read (ssl, fs[0].data, fs[0].len);
184 ossl_check_err_is_fatal (ssl, read);
188 for (i = 1; i < n_fs; i++)
190 rv = SSL_read (ssl, fs[i].data, fs[i].len);
191 read += rv > 0 ? rv : 0;
193 if (rv < (int) fs[i].len)
195 ossl_check_err_is_fatal (ssl, rv);
200 svm_fifo_enqueue_nocopy (f, read);
206 openssl_write_from_fifo_into_ssl (svm_fifo_t *f, SSL *ssl, u32 max_len)
208 int wrote = 0, rv, i = 0, len;
210 svm_fifo_seg_t fs[n_segs];
212 len = svm_fifo_segments (f, 0, fs, &n_segs, max_len);
216 while (wrote < len && i < n_segs)
218 rv = SSL_write (ssl, fs[i].data, fs[i].len);
219 wrote += (rv > 0) ? rv : 0;
220 if (rv < (int) fs[i].len)
222 ossl_check_err_is_fatal (ssl, rv);
229 svm_fifo_dequeue_drop (f, wrote);
234 #ifdef HAVE_OPENSSL_ASYNC
236 openssl_check_async_status (tls_ctx_t * ctx, openssl_resume_handler * handler,
239 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
242 SSL_get_async_status (oc->ssl, &estatus);
243 if (estatus == ASYNC_STATUS_EAGAIN)
245 vpp_tls_async_update_event (ctx, 1);
249 vpp_tls_async_update_event (ctx, 0);
259 openssl_handle_handshake_failure (tls_ctx_t * ctx)
261 session_t *app_session;
263 if (SSL_is_server (((openssl_ctx_t *) ctx)->ssl))
266 * Cleanup pre-allocated app session and close transport
269 session_get_if_valid (ctx->c_s_index, ctx->c_thread_index);
272 session_free (app_session);
273 ctx->no_app_session = 1;
274 ctx->c_s_index = SESSION_INVALID_INDEX;
275 tls_disconnect_transport (ctx);
281 * Also handles cleanup of the pre-allocated session
283 tls_notify_app_connected (ctx, SESSION_E_TLS_HANDSHAKE);
284 tls_disconnect_transport (ctx);
289 openssl_ctx_handshake_rx (tls_ctx_t * ctx, session_t * tls_session)
291 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
294 while (SSL_in_init (oc->ssl))
300 else if (!svm_fifo_max_dequeue_cons (tls_session->rx_fifo))
303 rv = SSL_do_handshake (oc->ssl);
304 err = SSL_get_error (oc->ssl, rv);
306 #ifdef HAVE_OPENSSL_ASYNC
307 if (err == SSL_ERROR_WANT_ASYNC)
309 openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
313 if (err == SSL_ERROR_SSL)
316 ERR_error_string (ERR_get_error (), buf);
317 clib_warning ("Err: %s", buf);
319 openssl_handle_handshake_failure (ctx);
323 if (err != SSL_ERROR_WANT_WRITE && err != SSL_ERROR_WANT_READ)
326 TLS_DBG (2, "tls state for %u is %s", oc->openssl_ctx_index,
327 SSL_state_string_long (oc->ssl));
329 if (SSL_in_init (oc->ssl))
335 if (!SSL_is_server (oc->ssl))
338 * Verify server certificate
340 if ((rv = SSL_get_verify_result (oc->ssl)) != X509_V_OK)
342 TLS_DBG (1, " failed verify: %s\n",
343 X509_verify_cert_error_string (rv));
346 * Presence of hostname enforces strict certificate verification
348 if (ctx->srv_hostname)
350 openssl_handle_handshake_failure (ctx);
354 tls_notify_app_connected (ctx, SESSION_E_NONE);
358 /* Need to check transport status */
359 if (ctx->is_passive_close)
361 openssl_handle_handshake_failure (ctx);
365 /* Accept failed, cleanup */
366 if (tls_notify_app_accept (ctx))
368 ctx->c_s_index = SESSION_INVALID_INDEX;
369 tls_disconnect_transport (ctx);
374 TLS_DBG (1, "Handshake for %u complete. TLS cipher is %s",
375 oc->openssl_ctx_index, SSL_get_cipher (oc->ssl));
380 openssl_confirm_app_close (tls_ctx_t * ctx)
382 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
383 SSL_shutdown (oc->ssl);
384 tls_disconnect_transport (ctx);
385 session_transport_closed_notify (&ctx->connection);
389 openssl_ctx_write_tls (tls_ctx_t *ctx, session_t *app_session,
390 transport_send_params_t *sp)
392 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
393 u32 deq_max, space, enq_buf;
398 ts = session_get_from_handle (ctx->tls_session_handle);
399 space = svm_fifo_max_enqueue_prod (ts->tx_fifo);
400 /* Leave a bit of extra space for tls ctrl data, if any needed */
401 space = clib_max ((int) space - TLSO_CTRL_BYTES, 0);
403 f = app_session->tx_fifo;
405 deq_max = svm_fifo_max_dequeue_cons (f);
406 deq_max = clib_min (deq_max, space);
410 deq_max = clib_min (deq_max, sp->max_burst_size);
412 /* Make sure tcp's tx fifo can actually buffer all bytes to be dequeued.
413 * If under memory pressure, tls's fifo segment might not be able to
414 * allocate the chunks needed. This also avoids errors from the underlying
415 * custom bio to the ssl infra which at times can get stuck. */
416 if (svm_fifo_provision_chunks (ts->tx_fifo, 0, 0, deq_max + TLSO_CTRL_BYTES))
419 wrote = openssl_write_from_fifo_into_ssl (f, oc->ssl, deq_max);
421 /* Unrecoverable protocol error. Reset connection */
422 if (PREDICT_FALSE (wrote < 0))
424 tls_notify_app_io_error (ctx);
431 if (svm_fifo_needs_deq_ntf (f, wrote))
432 session_dequeue_notify (app_session);
436 if (PREDICT_FALSE (ctx->app_closed && BIO_ctrl_pending (oc->rbio) <= 0))
437 openssl_confirm_app_close (ctx);
439 /* Deschedule and wait for deq notification if fifo is almost full */
440 enq_buf = clib_min (svm_fifo_size (ts->tx_fifo) / 2, TLSO_MIN_ENQ_SPACE);
441 if (space < wrote + enq_buf)
443 svm_fifo_add_want_deq_ntf (ts->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
444 transport_connection_deschedule (&ctx->connection);
445 sp->flags |= TRANSPORT_SND_F_DESCHED;
448 /* Request tx reschedule of the app session */
449 app_session->flags |= SESSION_F_CUSTOM_TX;
455 openssl_ctx_write_dtls (tls_ctx_t *ctx, session_t *app_session,
456 transport_send_params_t *sp)
458 openssl_main_t *om = &openssl_main;
459 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
460 u32 read = 0, to_deq, dgram_sz, enq_max;
461 session_dgram_pre_hdr_t hdr;
466 us = session_get_from_handle (ctx->tls_session_handle);
467 to_deq = svm_fifo_max_dequeue_cons (app_session->tx_fifo);
468 buf = om->tx_bufs[ctx->c_thread_index];
472 /* Peeking only pre-header dgram because the session is connected */
473 rv = svm_fifo_peek (app_session->tx_fifo, 0, sizeof (hdr), (u8 *) &hdr);
474 ASSERT (rv == sizeof (hdr) && hdr.data_length < vec_len (buf));
475 ASSERT (to_deq >= hdr.data_length + SESSION_CONN_HDR_LEN);
477 dgram_sz = hdr.data_length + SESSION_CONN_HDR_LEN;
478 enq_max = dgram_sz + TLSO_CTRL_BYTES;
479 if (svm_fifo_max_enqueue_prod (us->tx_fifo) < enq_max ||
480 svm_fifo_provision_chunks (us->tx_fifo, 0, 0, enq_max))
482 svm_fifo_add_want_deq_ntf (us->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
483 transport_connection_deschedule (&ctx->connection);
484 sp->flags |= TRANSPORT_SND_F_DESCHED;
488 rv = svm_fifo_peek (app_session->tx_fifo, SESSION_CONN_HDR_LEN,
489 hdr.data_length, buf);
490 ASSERT (rv == hdr.data_length);
491 svm_fifo_dequeue_drop (app_session->tx_fifo, dgram_sz);
493 wrote = SSL_write (oc->ssl, buf, rv);
502 if (svm_fifo_needs_deq_ntf (app_session->tx_fifo, read))
503 session_dequeue_notify (app_session);
506 tls_add_vpp_q_tx_evt (us);
508 if (PREDICT_FALSE (ctx->app_closed &&
509 !svm_fifo_max_enqueue_prod (us->rx_fifo)))
510 openssl_confirm_app_close (ctx);
516 openssl_ctx_write (tls_ctx_t *ctx, session_t *app_session,
517 transport_send_params_t *sp)
519 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
520 return openssl_ctx_write_tls (ctx, app_session, sp);
522 return openssl_ctx_write_dtls (ctx, app_session, sp);
526 openssl_ctx_read_tls (tls_ctx_t *ctx, session_t *tls_session)
528 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
529 session_t *app_session;
533 if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
535 if (openssl_ctx_handshake_rx (ctx, tls_session) < 0)
539 app_session = session_get_from_handle (ctx->app_session_handle);
540 f = app_session->rx_fifo;
542 read = openssl_read_from_ssl_into_fifo (f, oc->ssl);
544 /* Unrecoverable protocol error. Reset connection */
545 if (PREDICT_FALSE (read < 0))
547 tls_notify_app_io_error (ctx);
551 /* If handshake just completed, session may still be in accepting state */
552 if (read && app_session->session_state >= SESSION_STATE_READY)
553 tls_notify_app_enqueue (ctx, app_session);
555 if ((SSL_pending (oc->ssl) > 0) ||
556 svm_fifo_max_dequeue_cons (tls_session->rx_fifo))
557 tls_add_vpp_q_builtin_rx_evt (tls_session);
563 openssl_ctx_read_dtls (tls_ctx_t *ctx, session_t *us)
565 openssl_main_t *om = &openssl_main;
566 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
567 session_dgram_hdr_t hdr;
568 session_t *app_session;
573 if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
575 u32 us_index = us->session_index;
576 if (openssl_ctx_handshake_rx (ctx, us) < 0)
578 /* Session pool might grow when allocating the app's session */
579 us = session_get (us_index, ctx->c_thread_index);
582 buf = om->rx_bufs[ctx->c_thread_index];
583 app_session = session_get_from_handle (ctx->app_session_handle);
584 svm_fifo_fill_chunk_list (app_session->rx_fifo);
586 while (svm_fifo_max_dequeue_cons (us->rx_fifo) > 0)
588 if (svm_fifo_max_enqueue_prod (app_session->rx_fifo) < DTLSO_MAX_DGRAM)
590 tls_add_vpp_q_builtin_rx_evt (us);
594 read = SSL_read (oc->ssl, buf, vec_len (buf));
595 if (PREDICT_FALSE (read <= 0))
598 tls_add_vpp_q_builtin_rx_evt (us);
603 hdr.data_length = read;
606 svm_fifo_seg_t segs[2] = { { (u8 *) &hdr, sizeof (hdr) },
609 rv = svm_fifo_enqueue_segments (app_session->rx_fifo, segs, 2,
610 0 /* allow partial */);
616 /* If handshake just completed, session may still be in accepting state */
617 if (app_session->session_state >= SESSION_STATE_READY)
618 tls_notify_app_enqueue (ctx, app_session);
624 openssl_ctx_read (tls_ctx_t *ctx, session_t *ts)
626 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
627 return openssl_ctx_read_tls (ctx, ts);
629 return openssl_ctx_read_dtls (ctx, ts);
633 openssl_set_ckpair (SSL *ssl_connection, u32 ckpair_index)
635 app_cert_key_pair_t *ckpair;
640 ckpair = app_cert_key_pair_get_if_valid (ckpair_index);
644 if (!ckpair->cert || !ckpair->key)
646 TLS_DBG (1, "tls cert and/or key not configured");
650 * Set the key and cert
652 cert_bio = BIO_new (BIO_s_mem ());
653 BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
654 srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
657 clib_warning ("unable to parse certificate");
660 SSL_use_certificate (ssl_connection, srvcert);
663 cert_bio = BIO_new (BIO_s_mem ());
664 BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
665 pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
668 clib_warning ("unable to parse pkey");
671 SSL_use_PrivateKey (ssl_connection, pkey);
673 TLS_DBG (1, "TLS client using ckpair index: %d", ckpair_index);
678 openssl_ctx_init_verify (tls_ctx_t *ctx, int set_hostname_verification,
679 int set_hostname_strict_check)
681 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
684 if (set_hostname_verification)
686 X509_VERIFY_PARAM *param = SSL_get0_param (ssl);
689 TLS_DBG (1, "Couldn't fetch SSL param");
693 if (set_hostname_strict_check)
694 X509_VERIFY_PARAM_set_hostflags (param,
695 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
697 if (!X509_VERIFY_PARAM_set1_host (param,
698 (const char *) ctx->srv_hostname, 0))
700 TLS_DBG (1, "Couldn't set hostname for verification");
703 SSL_set_verify (ssl, SSL_VERIFY_PEER, 0);
705 if (!SSL_set_tlsext_host_name (ssl, ctx->srv_hostname))
707 TLS_DBG (1, "Couldn't set hostname");
714 openssl_ctx_init_client (tls_ctx_t * ctx)
716 long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
717 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
718 openssl_main_t *om = &openssl_main;
719 const SSL_METHOD *method;
722 method = ctx->tls_type == TRANSPORT_PROTO_TLS ? SSLv23_client_method () :
723 DTLS_client_method ();
726 TLS_DBG (1, "(D)TLS_method returned null");
730 oc->ssl_ctx = SSL_CTX_new (method);
731 if (oc->ssl_ctx == NULL)
733 TLS_DBG (1, "SSL_CTX_new returned null");
737 SSL_CTX_set_ecdh_auto (oc->ssl_ctx, 1);
738 SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
739 #ifdef HAVE_OPENSSL_ASYNC
741 SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ASYNC);
743 rv = SSL_CTX_set_cipher_list (oc->ssl_ctx, (const char *) om->ciphers);
746 TLS_DBG (1, "Couldn't set cipher");
750 SSL_CTX_set_options (oc->ssl_ctx, flags);
751 SSL_CTX_set_cert_store (oc->ssl_ctx, om->cert_store);
753 oc->ssl = SSL_new (oc->ssl_ctx);
756 TLS_DBG (1, "Couldn't initialize ssl struct");
760 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
762 oc->rbio = BIO_new_tls (ctx->tls_session_handle);
763 oc->wbio = BIO_new_tls (ctx->tls_session_handle);
767 oc->rbio = BIO_new_dtls (ctx->tls_session_handle);
768 oc->wbio = BIO_new_dtls (ctx->tls_session_handle);
771 SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
772 SSL_set_connect_state (oc->ssl);
774 /* Hostname validation and strict check by name, are disable by default */
775 rv = openssl_ctx_init_verify (ctx, 0, 0);
778 TLS_DBG (1, "ERROR:verify init failed:%d", rv);
781 if (openssl_set_ckpair (oc->ssl, ctx->ckpair_index))
783 TLS_DBG (1, "Couldn't set client certificate-key pair");
787 * 2. Do the first steps in the handshake.
789 TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
790 oc->openssl_ctx_index);
792 #ifdef HAVE_OPENSSL_ASYNC
793 session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
794 vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
798 rv = SSL_do_handshake (oc->ssl);
799 err = SSL_get_error (oc->ssl, rv);
800 #ifdef HAVE_OPENSSL_ASYNC
801 if (err == SSL_ERROR_WANT_ASYNC)
803 openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
808 if (err != SSL_ERROR_WANT_WRITE)
812 TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
813 oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
818 openssl_start_listen (tls_ctx_t * lctx)
820 const SSL_METHOD *method;
827 openssl_listen_ctx_t *olc;
828 app_cert_key_pair_t *ckpair;
830 long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
831 openssl_main_t *om = &openssl_main;
833 ckpair = app_cert_key_pair_get_if_valid (lctx->ckpair_index);
837 if (!ckpair->cert || !ckpair->key)
839 TLS_DBG (1, "tls cert and/or key not configured %d",
840 lctx->parent_app_wrk_index);
844 method = lctx->tls_type == TRANSPORT_PROTO_TLS ? SSLv23_server_method () :
845 DTLS_server_method ();
846 ssl_ctx = SSL_CTX_new (method);
849 clib_warning ("Unable to create SSL context");
853 SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
854 #ifdef HAVE_OPENSSL_ASYNC
857 SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ASYNC);
858 SSL_CTX_set_async_callback (ssl_ctx, tls_async_openssl_callback);
861 SSL_CTX_set_options (ssl_ctx, flags);
862 SSL_CTX_set_ecdh_auto (ssl_ctx, 1);
864 rv = SSL_CTX_set_cipher_list (ssl_ctx, (const char *) om->ciphers);
867 TLS_DBG (1, "Couldn't set cipher");
871 /* use the default OpenSSL built-in DH parameters */
872 rv = SSL_CTX_set_dh_auto (ssl_ctx, 1);
875 TLS_DBG (1, "Couldn't set temp DH parameters");
880 * Set the key and cert
882 cert_bio = BIO_new (BIO_s_mem ());
885 clib_warning ("unable to allocate memory");
888 BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
889 srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
892 clib_warning ("unable to parse certificate");
895 rv = SSL_CTX_use_certificate (ssl_ctx, srvcert);
898 clib_warning ("unable to use SSL certificate");
904 cert_bio = BIO_new (BIO_s_mem ());
907 clib_warning ("unable to allocate memory");
910 BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
911 pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
914 clib_warning ("unable to parse pkey");
917 rv = SSL_CTX_use_PrivateKey (ssl_ctx, pkey);
920 clib_warning ("unable to use SSL PrivateKey");
926 olc_index = openssl_listen_ctx_alloc ();
927 olc = openssl_lctx_get (olc_index);
928 olc->ssl_ctx = ssl_ctx;
929 olc->srvcert = srvcert;
932 /* store SSL_CTX into TLS level structure */
933 lctx->tls_ssl_ctx = olc_index;
944 openssl_stop_listen (tls_ctx_t * lctx)
947 openssl_listen_ctx_t *olc;
949 olc_index = lctx->tls_ssl_ctx;
950 olc = openssl_lctx_get (olc_index);
952 X509_free (olc->srvcert);
953 EVP_PKEY_free (olc->pkey);
955 SSL_CTX_free (olc->ssl_ctx);
956 openssl_listen_ctx_free (olc);
962 openssl_ctx_init_server (tls_ctx_t * ctx)
964 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
965 u32 olc_index = ctx->tls_ssl_ctx;
966 openssl_listen_ctx_t *olc;
969 /* Start a new connection */
971 olc = openssl_lctx_get (olc_index);
972 oc->ssl = SSL_new (olc->ssl_ctx);
975 TLS_DBG (1, "Couldn't initialize ssl struct");
979 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
981 oc->rbio = BIO_new_tls (ctx->tls_session_handle);
982 oc->wbio = BIO_new_tls (ctx->tls_session_handle);
986 oc->rbio = BIO_new_dtls (ctx->tls_session_handle);
987 oc->wbio = BIO_new_dtls (ctx->tls_session_handle);
990 SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
991 SSL_set_accept_state (oc->ssl);
993 TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
994 oc->openssl_ctx_index);
996 #ifdef HAVE_OPENSSL_ASYNC
997 session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
998 vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
1002 rv = SSL_do_handshake (oc->ssl);
1003 err = SSL_get_error (oc->ssl, rv);
1004 #ifdef HAVE_OPENSSL_ASYNC
1005 if (err == SSL_ERROR_WANT_ASYNC)
1007 openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
1012 if (err != SSL_ERROR_WANT_WRITE)
1016 TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
1017 oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
1022 openssl_handshake_is_over (tls_ctx_t * ctx)
1024 openssl_ctx_t *mc = (openssl_ctx_t *) ctx;
1027 return SSL_is_init_finished (mc->ssl);
1031 openssl_transport_close (tls_ctx_t * ctx)
1033 #ifdef HAVE_OPENSSL_ASYNC
1034 if (vpp_openssl_is_inflight (ctx))
1038 if (!openssl_handshake_is_over (ctx))
1040 openssl_handle_handshake_failure (ctx);
1043 session_transport_closing_notify (&ctx->connection);
1048 openssl_app_close (tls_ctx_t * ctx)
1050 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
1051 session_t *app_session;
1053 /* Wait for all data to be written to tcp */
1054 app_session = session_get_from_handle (ctx->app_session_handle);
1055 if (BIO_ctrl_pending (oc->rbio) <= 0
1056 && !svm_fifo_max_dequeue_cons (app_session->tx_fifo))
1057 openssl_confirm_app_close (ctx);
1059 ctx->app_closed = 1;
1064 tls_init_ca_chain (void)
1066 openssl_main_t *om = &openssl_main;
1067 tls_main_t *tm = vnet_tls_get_main ();
1072 if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
1074 clib_warning ("Could not initialize TLS CA certificates");
1078 if (!(om->cert_store = X509_STORE_new ()))
1080 clib_warning ("failed to create cert store");
1084 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1085 rv = X509_STORE_load_file (om->cert_store, tm->ca_cert_path);
1087 rv = X509_STORE_load_locations (om->cert_store, tm->ca_cert_path, 0);
1092 clib_warning ("failed to load ca certificate");
1095 if (tm->use_test_cert_in_ca)
1097 cert_bio = BIO_new (BIO_s_mem ());
1098 BIO_write (cert_bio, test_srv_crt_rsa, test_srv_crt_rsa_len);
1099 testcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
1102 clib_warning ("unable to parse certificate");
1105 X509_STORE_add_cert (om->cert_store, testcert);
1108 return (rv < 0 ? -1 : 0);
1112 openssl_reinit_ca_chain (void)
1114 openssl_main_t *om = &openssl_main;
1116 /* Remove/free existing x509_store */
1119 X509_STORE_free (om->cert_store);
1121 return tls_init_ca_chain ();
1124 const static tls_engine_vft_t openssl_engine = {
1125 .ctx_alloc = openssl_ctx_alloc,
1126 .ctx_alloc_w_thread = openssl_ctx_alloc_w_thread,
1127 .ctx_free = openssl_ctx_free,
1128 .ctx_attach = openssl_ctx_attach,
1129 .ctx_detach = openssl_ctx_detach,
1130 .ctx_get = openssl_ctx_get,
1131 .ctx_get_w_thread = openssl_ctx_get_w_thread,
1132 .ctx_init_server = openssl_ctx_init_server,
1133 .ctx_init_client = openssl_ctx_init_client,
1134 .ctx_write = openssl_ctx_write,
1135 .ctx_read = openssl_ctx_read,
1136 .ctx_handshake_is_over = openssl_handshake_is_over,
1137 .ctx_start_listen = openssl_start_listen,
1138 .ctx_stop_listen = openssl_stop_listen,
1139 .ctx_transport_close = openssl_transport_close,
1140 .ctx_app_close = openssl_app_close,
1141 .ctx_reinit_cachain = openssl_reinit_ca_chain,
1145 tls_openssl_set_ciphers (char *ciphers)
1147 openssl_main_t *om = &openssl_main;
1155 vec_validate (om->ciphers, strlen (ciphers));
1156 for (i = 0; i < vec_len (om->ciphers) - 1; i++)
1158 om->ciphers[i] = toupper (ciphers[i]);
1165 static clib_error_t *
1166 tls_openssl_init (vlib_main_t * vm)
1168 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1169 openssl_main_t *om = &openssl_main;
1170 clib_error_t *error = 0;
1173 error = tls_openssl_api_init (vm);
1174 num_threads = 1 /* main thread */ + vtm->n_threads;
1176 SSL_library_init ();
1177 SSL_load_error_strings ();
1179 vec_validate (om->ctx_pool, num_threads - 1);
1180 vec_validate (om->rx_bufs, num_threads - 1);
1181 vec_validate (om->tx_bufs, num_threads - 1);
1182 for (i = 0; i < num_threads; i++)
1184 vec_validate (om->rx_bufs[i], DTLSO_MAX_DGRAM);
1185 vec_validate (om->tx_bufs[i], DTLSO_MAX_DGRAM);
1187 tls_register_engine (&openssl_engine, CRYPTO_ENGINE_OPENSSL);
1189 om->engine_init = 0;
1191 /* default ciphers */
1192 tls_openssl_set_ciphers
1193 ("ALL:!ADH:!LOW:!EXP:!MD5:!RC4-SHA:!DES-CBC3-SHA:@STRENGTH");
1195 if (tls_init_ca_chain ())
1197 clib_warning ("failed to initialize TLS CA chain");
1204 VLIB_INIT_FUNCTION (tls_openssl_init) =
1206 .runs_after = VLIB_INITS("tls_init"),
1210 #ifdef HAVE_OPENSSL_ASYNC
1211 static clib_error_t *
1212 tls_openssl_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
1213 vlib_cli_command_t * cmd)
1215 openssl_main_t *om = &openssl_main;
1216 char *engine_name = NULL;
1217 char *engine_alg = NULL;
1218 char *ciphers = NULL;
1219 u8 engine_name_set = 0;
1222 /* By present, it is not allowed to configure engine again after running */
1223 if (om->engine_init)
1225 clib_warning ("engine has started!\n");
1226 return clib_error_return
1227 (0, "engine has started, and no config is accepted");
1230 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1232 if (unformat (input, "engine %s", &engine_name))
1234 engine_name_set = 1;
1236 else if (unformat (input, "async"))
1240 else if (unformat (input, "alg %s", &engine_alg))
1242 for (i = 0; i < strnlen (engine_alg, MAX_CRYPTO_LEN); i++)
1243 engine_alg[i] = toupper (engine_alg[i]);
1245 else if (unformat (input, "ciphers %s", &ciphers))
1247 tls_openssl_set_ciphers (ciphers);
1250 return clib_error_return (0, "failed: unknown input `%U'",
1251 format_unformat_error, input);
1254 /* reset parameters if engine is not configured */
1255 if (!engine_name_set)
1257 clib_warning ("No engine provided! \n");
1262 vnet_session_enable_disable (vm, 1);
1263 if (openssl_engine_register (engine_name, engine_alg, async) < 0)
1265 return clib_error_return (0, "Failed to register %s polling",
1270 vlib_cli_output (vm, "Successfully register engine %s\n",
1280 VLIB_CLI_COMMAND (tls_openssl_set_command, static) =
1282 .path = "tls openssl set",
1283 .short_help = "tls openssl set [engine <engine name>] [alg [algorithm] [async]",
1284 .function = tls_openssl_set_command_fn,
1290 VLIB_PLUGIN_REGISTER () = {
1291 .version = VPP_BUILD_VER,
1292 .description = "Transport Layer Security (TLS) Engine, OpenSSL Based",
1297 * fd.io coding-style-patch-verification: ON
1300 * eval: (c-set-style "gnu")