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_aligned_safe (om->ctx_pool[thread_index], ctx, 0);
46 *ctx = clib_mem_alloc (sizeof (openssl_ctx_t));
48 clib_memset (*ctx, 0, sizeof (openssl_ctx_t));
49 (*ctx)->ctx.c_thread_index = thread_index;
50 (*ctx)->ctx.tls_ctx_engine = CRYPTO_ENGINE_OPENSSL;
51 (*ctx)->ctx.app_session_handle = SESSION_INVALID_HANDLE;
52 (*ctx)->openssl_ctx_index = ctx - om->ctx_pool[thread_index];
53 return ((*ctx)->openssl_ctx_index);
57 openssl_ctx_alloc (void)
59 return openssl_ctx_alloc_w_thread (vlib_get_thread_index ());
63 openssl_ctx_free (tls_ctx_t * ctx)
65 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
67 /* Cleanup ssl ctx unless migrated */
68 if (!(ctx->flags & TLS_CONN_F_MIGRATED))
70 if (SSL_is_init_finished (oc->ssl) &&
71 !(ctx->flags & TLS_CONN_F_PASSIVE_CLOSE))
72 SSL_shutdown (oc->ssl);
75 vec_free (ctx->srv_hostname);
76 SSL_CTX_free (oc->client_ssl_ctx);
77 #ifdef HAVE_OPENSSL_ASYNC
78 openssl_evt_free (ctx->evt_index, ctx->c_thread_index);
82 pool_put_index (openssl_main.ctx_pool[ctx->c_thread_index],
83 oc->openssl_ctx_index);
87 openssl_ctx_detach (tls_ctx_t *ctx)
89 openssl_ctx_t *oc = (openssl_ctx_t *) ctx, *oc_copy;
91 oc_copy = clib_mem_alloc (sizeof (*oc_copy));
92 clib_memcpy (oc_copy, oc, sizeof (*oc));
98 openssl_ctx_attach (u32 thread_index, void *ctx_ptr)
100 openssl_main_t *om = &openssl_main;
104 pool_get_aligned_safe (om->ctx_pool[thread_index], oc, 0);
105 /* Free the old instance instead of looking for an empty spot */
110 (*oc)->openssl_ctx_index = oc - om->ctx_pool[thread_index];
111 (*oc)->ctx.c_thread_index = thread_index;
113 sh = (*oc)->ctx.tls_session_handle;
114 BIO_set_data ((*oc)->rbio, uword_to_pointer (sh, void *));
115 BIO_set_data ((*oc)->wbio, uword_to_pointer (sh, void *));
117 return ((*oc)->openssl_ctx_index);
121 openssl_ctx_get (u32 ctx_index)
124 ctx = pool_elt_at_index (openssl_main.ctx_pool[vlib_get_thread_index ()],
130 openssl_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
133 ctx = pool_elt_at_index (openssl_main.ctx_pool[thread_index], ctx_index);
138 openssl_listen_ctx_alloc (void)
140 openssl_main_t *om = &openssl_main;
141 openssl_listen_ctx_t *lctx;
143 pool_get (om->lctx_pool, lctx);
145 clib_memset (lctx, 0, sizeof (openssl_listen_ctx_t));
146 lctx->openssl_lctx_index = lctx - om->lctx_pool;
147 return lctx->openssl_lctx_index;
151 openssl_listen_ctx_free (openssl_listen_ctx_t * lctx)
153 pool_put_index (openssl_main.lctx_pool, lctx->openssl_lctx_index);
156 openssl_listen_ctx_t *
157 openssl_lctx_get (u32 lctx_index)
159 return pool_elt_at_index (openssl_main.lctx_pool, lctx_index);
162 #define ossl_check_err_is_fatal(_ssl, _rv) \
163 if (PREDICT_FALSE (_rv < 0 && SSL_get_error (_ssl, _rv) == SSL_ERROR_SSL)) \
167 openssl_read_from_ssl_into_fifo (svm_fifo_t *f, SSL *ssl, u32 max_len)
169 int read, rv, n_fs, i;
170 const int n_segs = 2;
171 svm_fifo_seg_t fs[n_segs];
174 max_enq = svm_fifo_max_enqueue_prod (f);
178 max_enq = clib_min (max_len, max_enq);
179 n_fs = svm_fifo_provision_chunks (f, fs, n_segs, max_enq);
183 /* Return early if we can't read anything */
184 read = SSL_read (ssl, fs[0].data, fs[0].len);
187 ossl_check_err_is_fatal (ssl, read);
191 if (read == (int) fs[0].len)
193 for (i = 1; i < n_fs; i++)
195 rv = SSL_read (ssl, fs[i].data, fs[i].len);
196 read += rv > 0 ? rv : 0;
198 if (rv < (int) fs[i].len)
200 ossl_check_err_is_fatal (ssl, rv);
205 svm_fifo_enqueue_nocopy (f, read);
211 openssl_write_from_fifo_into_ssl (svm_fifo_t *f, SSL *ssl, u32 max_len)
213 int wrote = 0, rv, i = 0, len;
215 svm_fifo_seg_t fs[n_segs];
217 len = svm_fifo_segments (f, 0, fs, &n_segs, max_len);
221 while (wrote < len && i < n_segs)
223 rv = SSL_write (ssl, fs[i].data, fs[i].len);
224 wrote += (rv > 0) ? rv : 0;
225 if (rv < (int) fs[i].len)
227 ossl_check_err_is_fatal (ssl, rv);
234 svm_fifo_dequeue_drop (f, wrote);
239 #ifdef HAVE_OPENSSL_ASYNC
241 openssl_check_async_status (tls_ctx_t * ctx, openssl_resume_handler * handler,
244 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
247 SSL_get_async_status (oc->ssl, &estatus);
248 if (estatus == ASYNC_STATUS_EAGAIN)
250 vpp_tls_async_update_event (ctx, 1);
254 vpp_tls_async_update_event (ctx, 0);
264 openssl_handle_handshake_failure (tls_ctx_t * ctx)
266 /* Failed to renegotiate handshake */
267 if (ctx->flags & TLS_CONN_F_HS_DONE)
269 tls_notify_app_io_error (ctx);
270 tls_disconnect_transport (ctx);
274 if (SSL_is_server (((openssl_ctx_t *) ctx)->ssl))
276 ctx->flags |= TLS_CONN_F_NO_APP_SESSION;
277 tls_disconnect_transport (ctx);
282 * Also handles cleanup of the pre-allocated session
284 tls_notify_app_connected (ctx, SESSION_E_TLS_HANDSHAKE);
285 tls_disconnect_transport (ctx);
290 openssl_ctx_handshake_rx (tls_ctx_t * ctx, session_t * tls_session)
292 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
295 while (SSL_in_init (oc->ssl))
297 if (ctx->flags & TLS_CONN_F_RESUME)
299 ctx->flags &= ~TLS_CONN_F_RESUME;
301 else if (!svm_fifo_max_dequeue_cons (tls_session->rx_fifo))
304 rv = SSL_do_handshake (oc->ssl);
305 err = SSL_get_error (oc->ssl, rv);
307 #ifdef HAVE_OPENSSL_ASYNC
308 if (err == SSL_ERROR_WANT_ASYNC)
310 openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
314 if (err == SSL_ERROR_SSL)
317 ERR_error_string (ERR_get_error (), buf);
318 clib_warning ("Err: %s", buf);
320 openssl_handle_handshake_failure (ctx);
324 if (err != SSL_ERROR_WANT_WRITE && err != SSL_ERROR_WANT_READ)
327 TLS_DBG (2, "tls state for %u is %s", oc->openssl_ctx_index,
328 SSL_state_string_long (oc->ssl));
330 if (SSL_in_init (oc->ssl))
333 /* Renegotiated handshake, app must not be notified */
334 if (PREDICT_FALSE (ctx->flags & TLS_CONN_F_HS_DONE))
340 if (!SSL_is_server (oc->ssl))
343 * Verify server certificate
345 if ((rv = SSL_get_verify_result (oc->ssl)) != X509_V_OK)
347 TLS_DBG (1, " failed verify: %s\n",
348 X509_verify_cert_error_string (rv));
351 * Presence of hostname enforces strict certificate verification
353 if (ctx->srv_hostname)
355 openssl_handle_handshake_failure (ctx);
359 if (tls_notify_app_connected (ctx, SESSION_E_NONE))
361 tls_disconnect_transport (ctx);
367 /* Need to check transport status */
368 if (ctx->flags & TLS_CONN_F_PASSIVE_CLOSE)
370 openssl_handle_handshake_failure (ctx);
374 /* Accept failed, cleanup */
375 if (tls_notify_app_accept (ctx))
377 ctx->c_s_index = SESSION_INVALID_INDEX;
378 tls_disconnect_transport (ctx);
382 ctx->flags |= TLS_CONN_F_HS_DONE;
383 TLS_DBG (1, "Handshake for %u complete. TLS cipher is %s",
384 oc->openssl_ctx_index, SSL_get_cipher (oc->ssl));
389 openssl_confirm_app_close (tls_ctx_t * ctx)
391 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
392 SSL_shutdown (oc->ssl);
393 tls_disconnect_transport (ctx);
394 session_transport_closed_notify (&ctx->connection);
398 openssl_ctx_write_tls (tls_ctx_t *ctx, session_t *app_session,
399 transport_send_params_t *sp)
401 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
402 u32 deq_max, space, enq_buf;
407 ts = session_get_from_handle (ctx->tls_session_handle);
408 space = svm_fifo_max_enqueue_prod (ts->tx_fifo);
409 /* Leave a bit of extra space for tls ctrl data, if any needed */
410 space = clib_max ((int) space - TLSO_CTRL_BYTES, 0);
412 f = app_session->tx_fifo;
414 deq_max = svm_fifo_max_dequeue_cons (f);
415 deq_max = clib_min (deq_max, space);
419 deq_max = clib_min (deq_max, sp->max_burst_size);
421 /* Make sure tcp's tx fifo can actually buffer all bytes to be dequeued.
422 * If under memory pressure, tls's fifo segment might not be able to
423 * allocate the chunks needed. This also avoids errors from the underlying
424 * custom bio to the ssl infra which at times can get stuck. */
425 if (svm_fifo_provision_chunks (ts->tx_fifo, 0, 0, deq_max + TLSO_CTRL_BYTES))
428 wrote = openssl_write_from_fifo_into_ssl (f, oc->ssl, deq_max);
430 /* Unrecoverable protocol error. Reset connection */
431 if (PREDICT_FALSE (wrote < 0))
433 tls_notify_app_io_error (ctx);
440 if (svm_fifo_needs_deq_ntf (f, wrote))
441 session_dequeue_notify (app_session);
445 if (PREDICT_FALSE ((ctx->flags & TLS_CONN_F_APP_CLOSED) &&
446 BIO_ctrl_pending (oc->rbio) <= 0))
447 openssl_confirm_app_close (ctx);
449 /* Deschedule and wait for deq notification if fifo is almost full */
450 enq_buf = clib_min (svm_fifo_size (ts->tx_fifo) / 2, TLSO_MIN_ENQ_SPACE);
451 if (space < wrote + enq_buf)
453 svm_fifo_add_want_deq_ntf (ts->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
454 transport_connection_deschedule (&ctx->connection);
455 sp->flags |= TRANSPORT_SND_F_DESCHED;
458 /* Request tx reschedule of the app session */
459 app_session->flags |= SESSION_F_CUSTOM_TX;
465 openssl_ctx_write_dtls (tls_ctx_t *ctx, session_t *app_session,
466 transport_send_params_t *sp)
468 openssl_main_t *om = &openssl_main;
469 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
470 u32 read = 0, to_deq, dgram_sz, enq_max;
471 session_dgram_pre_hdr_t hdr;
476 us = session_get_from_handle (ctx->tls_session_handle);
477 to_deq = svm_fifo_max_dequeue_cons (app_session->tx_fifo);
478 buf = om->tx_bufs[ctx->c_thread_index];
482 /* Peeking only pre-header dgram because the session is connected */
483 rv = svm_fifo_peek (app_session->tx_fifo, 0, sizeof (hdr), (u8 *) &hdr);
484 ASSERT (rv == sizeof (hdr) && hdr.data_length < vec_len (buf));
485 ASSERT (to_deq >= hdr.data_length + SESSION_CONN_HDR_LEN);
487 dgram_sz = hdr.data_length + SESSION_CONN_HDR_LEN;
488 enq_max = dgram_sz + TLSO_CTRL_BYTES;
489 if (svm_fifo_max_enqueue_prod (us->tx_fifo) < enq_max ||
490 svm_fifo_provision_chunks (us->tx_fifo, 0, 0, enq_max))
492 svm_fifo_add_want_deq_ntf (us->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
493 transport_connection_deschedule (&ctx->connection);
494 sp->flags |= TRANSPORT_SND_F_DESCHED;
498 rv = svm_fifo_peek (app_session->tx_fifo, SESSION_CONN_HDR_LEN,
499 hdr.data_length, buf);
500 ASSERT (rv == hdr.data_length);
501 svm_fifo_dequeue_drop (app_session->tx_fifo, dgram_sz);
503 wrote = SSL_write (oc->ssl, buf, rv);
512 if (svm_fifo_needs_deq_ntf (app_session->tx_fifo, read))
513 session_dequeue_notify (app_session);
516 tls_add_vpp_q_tx_evt (us);
518 if (PREDICT_FALSE ((ctx->flags & TLS_CONN_F_APP_CLOSED) &&
519 !svm_fifo_max_enqueue_prod (us->rx_fifo)))
520 openssl_confirm_app_close (ctx);
526 openssl_ctx_write (tls_ctx_t *ctx, session_t *app_session,
527 transport_send_params_t *sp)
529 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
530 return openssl_ctx_write_tls (ctx, app_session, sp);
532 return openssl_ctx_write_dtls (ctx, app_session, sp);
536 openssl_ctx_read_tls (tls_ctx_t *ctx, session_t *tls_session)
538 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
539 const u32 max_len = 128 << 10;
540 session_t *app_session;
544 if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
546 if (openssl_ctx_handshake_rx (ctx, tls_session) < 0)
549 /* Application might force a session pool realloc on accept */
550 tls_session = session_get_from_handle (ctx->tls_session_handle);
553 app_session = session_get_from_handle (ctx->app_session_handle);
554 f = app_session->rx_fifo;
556 read = openssl_read_from_ssl_into_fifo (f, oc->ssl, max_len);
558 /* Unrecoverable protocol error. Reset connection */
559 if (PREDICT_FALSE (read < 0))
561 tls_notify_app_io_error (ctx);
566 tls_notify_app_enqueue (ctx, app_session);
568 if ((SSL_pending (oc->ssl) > 0) ||
569 svm_fifo_max_dequeue_cons (tls_session->rx_fifo))
570 tls_add_vpp_q_builtin_rx_evt (tls_session);
576 openssl_ctx_read_dtls (tls_ctx_t *ctx, session_t *us)
578 openssl_main_t *om = &openssl_main;
579 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
580 session_dgram_hdr_t hdr;
581 session_t *app_session;
586 if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
588 u32 us_index = us->session_index;
589 if (openssl_ctx_handshake_rx (ctx, us) < 0)
591 /* Session pool might grow when allocating the app's session */
592 us = session_get (us_index, ctx->c_thread_index);
595 buf = om->rx_bufs[ctx->c_thread_index];
596 app_session = session_get_from_handle (ctx->app_session_handle);
597 svm_fifo_fill_chunk_list (app_session->rx_fifo);
599 while (svm_fifo_max_dequeue_cons (us->rx_fifo) > 0)
601 if (svm_fifo_max_enqueue_prod (app_session->rx_fifo) < DTLSO_MAX_DGRAM)
603 tls_add_vpp_q_builtin_rx_evt (us);
607 read = SSL_read (oc->ssl, buf, vec_len (buf));
608 if (PREDICT_FALSE (read <= 0))
611 tls_add_vpp_q_builtin_rx_evt (us);
616 hdr.data_length = read;
619 svm_fifo_seg_t segs[2] = { { (u8 *) &hdr, sizeof (hdr) },
622 rv = svm_fifo_enqueue_segments (app_session->rx_fifo, segs, 2,
623 0 /* allow partial */);
629 /* If handshake just completed, session may still be in accepting state */
630 if (app_session->session_state >= SESSION_STATE_READY)
631 tls_notify_app_enqueue (ctx, app_session);
637 openssl_ctx_read (tls_ctx_t *ctx, session_t *ts)
639 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
640 return openssl_ctx_read_tls (ctx, ts);
642 return openssl_ctx_read_dtls (ctx, ts);
646 openssl_set_ckpair (SSL *ssl, u32 ckpair_index)
648 app_cert_key_pair_t *ckpair;
653 /* Configure a ckpair index only if non-default/test provided */
654 if (ckpair_index == 0)
657 ckpair = app_cert_key_pair_get_if_valid (ckpair_index);
661 if (!ckpair->cert || !ckpair->key)
663 TLS_DBG (1, "tls cert and/or key not configured");
667 * Set the key and cert
669 cert_bio = BIO_new (BIO_s_mem ());
670 BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
671 srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
674 clib_warning ("unable to parse certificate");
677 SSL_use_certificate (ssl, srvcert);
680 cert_bio = BIO_new (BIO_s_mem ());
681 BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
682 pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
685 clib_warning ("unable to parse pkey");
688 SSL_use_PrivateKey (ssl, pkey);
690 TLS_DBG (1, "TLS client using ckpair index: %d", ckpair_index);
695 openssl_client_init_verify (SSL *ssl, const char *srv_hostname,
696 int set_hostname_verification,
697 int set_hostname_strict_check)
699 if (set_hostname_verification)
701 X509_VERIFY_PARAM *param = SSL_get0_param (ssl);
704 TLS_DBG (1, "Couldn't fetch SSL param");
708 if (set_hostname_strict_check)
709 X509_VERIFY_PARAM_set_hostflags (param,
710 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
712 if (!X509_VERIFY_PARAM_set1_host (param, srv_hostname, 0))
714 TLS_DBG (1, "Couldn't set hostname for verification");
717 SSL_set_verify (ssl, SSL_VERIFY_PEER, 0);
719 if (!SSL_set_tlsext_host_name (ssl, srv_hostname))
721 TLS_DBG (1, "Couldn't set hostname");
728 openssl_ctx_init_client (tls_ctx_t * ctx)
730 long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
731 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
732 openssl_main_t *om = &openssl_main;
733 const SSL_METHOD *method;
736 method = ctx->tls_type == TRANSPORT_PROTO_TLS ? SSLv23_client_method () :
737 DTLS_client_method ();
740 TLS_DBG (1, "(D)TLS_method returned null");
744 oc->client_ssl_ctx = SSL_CTX_new (method);
745 if (oc->client_ssl_ctx == NULL)
747 TLS_DBG (1, "SSL_CTX_new returned null");
751 SSL_CTX_set_ecdh_auto (oc->client_ssl_ctx, 1);
752 SSL_CTX_set_mode (oc->client_ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
753 #ifdef HAVE_OPENSSL_ASYNC
755 SSL_CTX_set_mode (oc->client_ssl_ctx, SSL_MODE_ASYNC);
758 SSL_CTX_set_cipher_list (oc->client_ssl_ctx, (const char *) om->ciphers);
761 TLS_DBG (1, "Couldn't set cipher");
765 SSL_CTX_set_options (oc->client_ssl_ctx, flags);
766 SSL_CTX_set1_cert_store (oc->client_ssl_ctx, om->cert_store);
768 oc->ssl = SSL_new (oc->client_ssl_ctx);
771 TLS_DBG (1, "Couldn't initialize ssl struct");
775 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
777 oc->rbio = BIO_new_tls (ctx->tls_session_handle);
778 oc->wbio = BIO_new_tls (ctx->tls_session_handle);
782 oc->rbio = BIO_new_dtls (ctx->tls_session_handle);
783 oc->wbio = BIO_new_dtls (ctx->tls_session_handle);
786 SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
787 SSL_set_connect_state (oc->ssl);
789 /* Hostname validation and strict check by name are disabled by default */
790 rv = openssl_client_init_verify (oc->ssl, (const char *) ctx->srv_hostname,
794 TLS_DBG (1, "ERROR:verify init failed:%d", rv);
797 if (openssl_set_ckpair (oc->ssl, ctx->ckpair_index))
799 TLS_DBG (1, "Couldn't set client certificate-key pair");
803 * 2. Do the first steps in the handshake.
805 TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
806 oc->openssl_ctx_index);
808 #ifdef HAVE_OPENSSL_ASYNC
809 session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
810 vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
814 rv = SSL_do_handshake (oc->ssl);
815 err = SSL_get_error (oc->ssl, rv);
816 #ifdef HAVE_OPENSSL_ASYNC
817 if (err == SSL_ERROR_WANT_ASYNC)
819 openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
824 if (err != SSL_ERROR_WANT_WRITE)
828 TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
829 oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
834 openssl_start_listen (tls_ctx_t * lctx)
836 const SSL_METHOD *method;
843 openssl_listen_ctx_t *olc;
844 app_cert_key_pair_t *ckpair;
846 long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
847 openssl_main_t *om = &openssl_main;
849 ckpair = app_cert_key_pair_get_if_valid (lctx->ckpair_index);
853 if (!ckpair->cert || !ckpair->key)
855 TLS_DBG (1, "tls cert and/or key not configured %d",
856 lctx->parent_app_wrk_index);
860 method = lctx->tls_type == TRANSPORT_PROTO_TLS ? SSLv23_server_method () :
861 DTLS_server_method ();
862 ssl_ctx = SSL_CTX_new (method);
865 clib_warning ("Unable to create SSL context");
869 SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
870 #ifdef HAVE_OPENSSL_ASYNC
873 SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ASYNC);
874 SSL_CTX_set_async_callback (ssl_ctx, tls_async_openssl_callback);
877 SSL_CTX_set_options (ssl_ctx, flags);
878 SSL_CTX_set_ecdh_auto (ssl_ctx, 1);
880 rv = SSL_CTX_set_cipher_list (ssl_ctx, (const char *) om->ciphers);
883 TLS_DBG (1, "Couldn't set cipher");
887 /* use the default OpenSSL built-in DH parameters */
888 rv = SSL_CTX_set_dh_auto (ssl_ctx, 1);
891 TLS_DBG (1, "Couldn't set temp DH parameters");
896 * Set the key and cert
898 cert_bio = BIO_new (BIO_s_mem ());
901 clib_warning ("unable to allocate memory");
904 BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
905 srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
908 clib_warning ("unable to parse certificate");
911 rv = SSL_CTX_use_certificate (ssl_ctx, srvcert);
914 clib_warning ("unable to use SSL certificate");
920 cert_bio = BIO_new (BIO_s_mem ());
923 clib_warning ("unable to allocate memory");
926 BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
927 pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
930 clib_warning ("unable to parse pkey");
933 rv = SSL_CTX_use_PrivateKey (ssl_ctx, pkey);
936 clib_warning ("unable to use SSL PrivateKey");
942 olc_index = openssl_listen_ctx_alloc ();
943 olc = openssl_lctx_get (olc_index);
944 olc->ssl_ctx = ssl_ctx;
945 olc->srvcert = srvcert;
948 /* store SSL_CTX into TLS level structure */
949 lctx->tls_ssl_ctx = olc_index;
960 openssl_stop_listen (tls_ctx_t * lctx)
963 openssl_listen_ctx_t *olc;
965 olc_index = lctx->tls_ssl_ctx;
966 olc = openssl_lctx_get (olc_index);
968 X509_free (olc->srvcert);
969 EVP_PKEY_free (olc->pkey);
971 SSL_CTX_free (olc->ssl_ctx);
972 openssl_listen_ctx_free (olc);
978 openssl_ctx_init_server (tls_ctx_t * ctx)
980 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
981 u32 olc_index = ctx->tls_ssl_ctx;
982 openssl_listen_ctx_t *olc;
985 /* Start a new connection */
987 olc = openssl_lctx_get (olc_index);
988 oc->ssl = SSL_new (olc->ssl_ctx);
991 TLS_DBG (1, "Couldn't initialize ssl struct");
995 if (ctx->tls_type == TRANSPORT_PROTO_TLS)
997 oc->rbio = BIO_new_tls (ctx->tls_session_handle);
998 oc->wbio = BIO_new_tls (ctx->tls_session_handle);
1002 oc->rbio = BIO_new_dtls (ctx->tls_session_handle);
1003 oc->wbio = BIO_new_dtls (ctx->tls_session_handle);
1006 SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
1007 SSL_set_accept_state (oc->ssl);
1009 TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
1010 oc->openssl_ctx_index);
1012 #ifdef HAVE_OPENSSL_ASYNC
1013 session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
1014 vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
1018 rv = SSL_do_handshake (oc->ssl);
1019 err = SSL_get_error (oc->ssl, rv);
1020 #ifdef HAVE_OPENSSL_ASYNC
1021 if (err == SSL_ERROR_WANT_ASYNC)
1023 openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
1028 if (err != SSL_ERROR_WANT_WRITE)
1032 TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
1033 oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
1038 openssl_handshake_is_over (tls_ctx_t * ctx)
1040 openssl_ctx_t *mc = (openssl_ctx_t *) ctx;
1043 return SSL_is_init_finished (mc->ssl);
1047 openssl_transport_close (tls_ctx_t * ctx)
1049 #ifdef HAVE_OPENSSL_ASYNC
1050 if (vpp_openssl_is_inflight (ctx))
1054 if (!openssl_handshake_is_over (ctx))
1056 openssl_handle_handshake_failure (ctx);
1059 session_transport_closing_notify (&ctx->connection);
1064 openssl_transport_reset (tls_ctx_t *ctx)
1066 if (!openssl_handshake_is_over (ctx))
1068 openssl_handle_handshake_failure (ctx);
1072 session_transport_reset_notify (&ctx->connection);
1073 session_transport_closed_notify (&ctx->connection);
1074 tls_disconnect_transport (ctx);
1080 openssl_app_close (tls_ctx_t * ctx)
1082 openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
1083 session_t *app_session;
1085 /* Wait for all data to be written to tcp */
1086 app_session = session_get_from_handle (ctx->app_session_handle);
1087 if (BIO_ctrl_pending (oc->rbio) <= 0
1088 && !svm_fifo_max_dequeue_cons (app_session->tx_fifo))
1089 openssl_confirm_app_close (ctx);
1094 tls_init_ca_chain (void)
1096 openssl_main_t *om = &openssl_main;
1097 tls_main_t *tm = vnet_tls_get_main ();
1102 if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
1104 clib_warning ("Could not initialize TLS CA certificates");
1108 if (!(om->cert_store = X509_STORE_new ()))
1110 clib_warning ("failed to create cert store");
1114 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1115 rv = X509_STORE_load_file (om->cert_store, tm->ca_cert_path);
1117 rv = X509_STORE_load_locations (om->cert_store, tm->ca_cert_path, 0);
1122 clib_warning ("failed to load ca certificate");
1125 if (tm->use_test_cert_in_ca)
1127 cert_bio = BIO_new (BIO_s_mem ());
1128 BIO_write (cert_bio, test_srv_crt_rsa, test_srv_crt_rsa_len);
1129 testcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
1132 clib_warning ("unable to parse certificate");
1135 X509_STORE_add_cert (om->cert_store, testcert);
1138 return (rv < 0 ? -1 : 0);
1142 openssl_reinit_ca_chain (void)
1144 openssl_main_t *om = &openssl_main;
1146 /* Remove/free existing x509_store */
1149 X509_STORE_free (om->cert_store);
1151 return tls_init_ca_chain ();
1154 const static tls_engine_vft_t openssl_engine = {
1155 .ctx_alloc = openssl_ctx_alloc,
1156 .ctx_alloc_w_thread = openssl_ctx_alloc_w_thread,
1157 .ctx_free = openssl_ctx_free,
1158 .ctx_attach = openssl_ctx_attach,
1159 .ctx_detach = openssl_ctx_detach,
1160 .ctx_get = openssl_ctx_get,
1161 .ctx_get_w_thread = openssl_ctx_get_w_thread,
1162 .ctx_init_server = openssl_ctx_init_server,
1163 .ctx_init_client = openssl_ctx_init_client,
1164 .ctx_write = openssl_ctx_write,
1165 .ctx_read = openssl_ctx_read,
1166 .ctx_handshake_is_over = openssl_handshake_is_over,
1167 .ctx_start_listen = openssl_start_listen,
1168 .ctx_stop_listen = openssl_stop_listen,
1169 .ctx_transport_close = openssl_transport_close,
1170 .ctx_transport_reset = openssl_transport_reset,
1171 .ctx_app_close = openssl_app_close,
1172 .ctx_reinit_cachain = openssl_reinit_ca_chain,
1176 tls_openssl_set_ciphers (char *ciphers)
1178 openssl_main_t *om = &openssl_main;
1186 vec_validate (om->ciphers, strlen (ciphers));
1187 for (i = 0; i < vec_len (om->ciphers) - 1; i++)
1189 om->ciphers[i] = toupper (ciphers[i]);
1196 static clib_error_t *
1197 tls_openssl_init (vlib_main_t * vm)
1199 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1200 openssl_main_t *om = &openssl_main;
1201 clib_error_t *error = 0;
1204 error = tls_openssl_api_init (vm);
1205 num_threads = 1 /* main thread */ + vtm->n_threads;
1207 SSL_library_init ();
1208 SSL_load_error_strings ();
1210 vec_validate (om->ctx_pool, num_threads - 1);
1211 vec_validate (om->rx_bufs, num_threads - 1);
1212 vec_validate (om->tx_bufs, num_threads - 1);
1213 for (i = 0; i < num_threads; i++)
1215 vec_validate (om->rx_bufs[i], DTLSO_MAX_DGRAM);
1216 vec_validate (om->tx_bufs[i], DTLSO_MAX_DGRAM);
1218 tls_register_engine (&openssl_engine, CRYPTO_ENGINE_OPENSSL);
1220 om->engine_init = 0;
1222 /* default ciphers */
1223 tls_openssl_set_ciphers
1224 ("ALL:!ADH:!LOW:!EXP:!MD5:!RC4-SHA:!DES-CBC3-SHA:@STRENGTH");
1226 if (tls_init_ca_chain ())
1228 clib_warning ("failed to initialize TLS CA chain");
1234 VLIB_INIT_FUNCTION (tls_openssl_init) =
1236 .runs_after = VLIB_INITS("tls_init"),
1239 #ifdef HAVE_OPENSSL_ASYNC
1240 static clib_error_t *
1241 tls_openssl_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
1242 vlib_cli_command_t * cmd)
1244 openssl_main_t *om = &openssl_main;
1245 char *engine_name = NULL;
1246 char *engine_alg = NULL;
1247 char *ciphers = NULL;
1248 u8 engine_name_set = 0;
1251 /* By present, it is not allowed to configure engine again after running */
1252 if (om->engine_init)
1254 clib_warning ("engine has started!\n");
1255 return clib_error_return
1256 (0, "engine has started, and no config is accepted");
1259 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1261 if (unformat (input, "engine %s", &engine_name))
1263 engine_name_set = 1;
1265 else if (unformat (input, "async"))
1269 else if (unformat (input, "alg %s", &engine_alg))
1271 for (i = 0; i < strnlen (engine_alg, MAX_CRYPTO_LEN); i++)
1272 engine_alg[i] = toupper (engine_alg[i]);
1274 else if (unformat (input, "ciphers %s", &ciphers))
1276 tls_openssl_set_ciphers (ciphers);
1279 return clib_error_return (0, "failed: unknown input `%U'",
1280 format_unformat_error, input);
1283 /* reset parameters if engine is not configured */
1284 if (!engine_name_set)
1286 clib_warning ("No engine provided! \n");
1291 vnet_session_enable_disable (vm, 1);
1292 if (openssl_engine_register (engine_name, engine_alg, async) < 0)
1294 return clib_error_return (0, "Failed to register %s polling",
1299 vlib_cli_output (vm, "Successfully register engine %s\n",
1308 VLIB_CLI_COMMAND (tls_openssl_set_command, static) =
1310 .path = "tls openssl set",
1311 .short_help = "tls openssl set [engine <engine name>] [alg [algorithm] [async]",
1312 .function = tls_openssl_set_command_fn,
1316 VLIB_PLUGIN_REGISTER () = {
1317 .version = VPP_BUILD_VER,
1318 .description = "Transport Layer Security (TLS) Engine, OpenSSL Based",
1322 * fd.io coding-style-patch-verification: ON
1325 * eval: (c-set-style "gnu")