tls: add custom openssl bio
[vpp.git] / src / plugins / tlsopenssl / tls_openssl.c
1 /*
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:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15
16 #include <openssl/ssl.h>
17 #include <openssl/conf.h>
18 #include <openssl/err.h>
19
20 #ifdef HAVE_OPENSSL_ASYNC
21 #include <openssl/async.h>
22 #endif
23 #include <dlfcn.h>
24 #include <vnet/plugin/plugin.h>
25 #include <vpp/app/version.h>
26 #include <vnet/tls/tls.h>
27 #include <ctype.h>
28 #include <tlsopenssl/tls_openssl.h>
29 #include <tlsopenssl/tls_bio.h>
30
31 #define MAX_CRYPTO_LEN 64
32
33 openssl_main_t openssl_main;
34 static u32
35 openssl_ctx_alloc (void)
36 {
37   u8 thread_index = vlib_get_thread_index ();
38   openssl_main_t *tm = &openssl_main;
39   openssl_ctx_t **ctx;
40
41   pool_get (tm->ctx_pool[thread_index], ctx);
42   if (!(*ctx))
43     *ctx = clib_mem_alloc (sizeof (openssl_ctx_t));
44
45   clib_memset (*ctx, 0, sizeof (openssl_ctx_t));
46   (*ctx)->ctx.c_thread_index = thread_index;
47   (*ctx)->ctx.tls_ctx_engine = CRYPTO_ENGINE_OPENSSL;
48   (*ctx)->ctx.app_session_handle = SESSION_INVALID_HANDLE;
49   (*ctx)->openssl_ctx_index = ctx - tm->ctx_pool[thread_index];
50   return ((*ctx)->openssl_ctx_index);
51 }
52
53 static void
54 openssl_ctx_free (tls_ctx_t * ctx)
55 {
56   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
57
58   if (SSL_is_init_finished (oc->ssl) && !ctx->is_passive_close)
59     SSL_shutdown (oc->ssl);
60
61   SSL_free (oc->ssl);
62
63 #ifdef HAVE_OPENSSL_ASYNC
64   openssl_evt_free (ctx->evt_index, ctx->c_thread_index);
65 #endif
66   vec_free (ctx->srv_hostname);
67   pool_put_index (openssl_main.ctx_pool[ctx->c_thread_index],
68                   oc->openssl_ctx_index);
69 }
70
71 tls_ctx_t *
72 openssl_ctx_get (u32 ctx_index)
73 {
74   openssl_ctx_t **ctx;
75   ctx = pool_elt_at_index (openssl_main.ctx_pool[vlib_get_thread_index ()],
76                            ctx_index);
77   return &(*ctx)->ctx;
78 }
79
80 tls_ctx_t *
81 openssl_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
82 {
83   openssl_ctx_t **ctx;
84   ctx = pool_elt_at_index (openssl_main.ctx_pool[thread_index], ctx_index);
85   return &(*ctx)->ctx;
86 }
87
88 static u32
89 openssl_listen_ctx_alloc (void)
90 {
91   openssl_main_t *om = &openssl_main;
92   openssl_listen_ctx_t *lctx;
93
94   pool_get (om->lctx_pool, lctx);
95
96   clib_memset (lctx, 0, sizeof (openssl_listen_ctx_t));
97   lctx->openssl_lctx_index = lctx - om->lctx_pool;
98   return lctx->openssl_lctx_index;
99 }
100
101 static void
102 openssl_listen_ctx_free (openssl_listen_ctx_t * lctx)
103 {
104   pool_put_index (openssl_main.lctx_pool, lctx->openssl_lctx_index);
105 }
106
107 openssl_listen_ctx_t *
108 openssl_lctx_get (u32 lctx_index)
109 {
110   return pool_elt_at_index (openssl_main.lctx_pool, lctx_index);
111 }
112
113 static int
114 openssl_read_from_ssl_into_fifo (svm_fifo_t * f, SSL * ssl)
115 {
116   u32 enq_now, enq_max;
117   svm_fifo_chunk_t *c;
118   int read, rv;
119
120   enq_max = svm_fifo_max_enqueue_prod (f);
121   if (!enq_max)
122     return 0;
123
124   svm_fifo_fill_chunk_list (f);
125
126   enq_now = clib_min (svm_fifo_max_write_chunk (f), enq_max);
127   if (!enq_now)
128     return 0;
129
130   read = SSL_read (ssl, svm_fifo_tail (f), enq_now);
131   if (read <= 0)
132     return 0;
133
134   c = svm_fifo_tail_chunk (f);
135   while ((c = c->next) && read < enq_max)
136     {
137       enq_now = clib_min (c->length, enq_max - read);
138       rv = SSL_read (ssl, c->data, enq_now);
139       read += rv > 0 ? rv : 0;
140
141       if (rv < enq_now)
142         break;
143     }
144
145   svm_fifo_enqueue_nocopy (f, read);
146
147   return read;
148 }
149
150 static int
151 openssl_write_from_fifo_into_ssl (svm_fifo_t * f, SSL * ssl, u32 len)
152 {
153   svm_fifo_chunk_t *c;
154   int wrote = 0, rv;
155   u32 deq_now;
156
157   deq_now = clib_min (svm_fifo_max_read_chunk (f), len);
158   wrote = SSL_write (ssl, svm_fifo_head (f), deq_now);
159   if (wrote <= 0)
160     return 0;
161
162   c = svm_fifo_head_chunk (f);
163   while ((c = c->next) && wrote < len)
164     {
165       deq_now = clib_min (c->length, len - wrote);
166       rv = SSL_write (ssl, c->data, deq_now);
167       wrote += rv > 0 ? rv : 0;
168
169       if (rv < deq_now)
170         break;
171     }
172
173   svm_fifo_dequeue_drop (f, wrote);
174
175   return wrote;
176 }
177
178 #ifdef HAVE_OPENSSL_ASYNC
179 static int
180 openssl_check_async_status (tls_ctx_t * ctx, openssl_resume_handler * handler,
181                             session_t * session)
182 {
183   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
184   int estatus;
185
186   SSL_get_async_status (oc->ssl, &estatus);
187   if (estatus == ASYNC_STATUS_EAGAIN)
188     {
189       vpp_tls_async_update_event (ctx, 1);
190     }
191   else
192     {
193       vpp_tls_async_update_event (ctx, 0);
194     }
195
196   return 1;
197
198 }
199
200 #endif
201
202 static void
203 openssl_handle_handshake_failure (tls_ctx_t * ctx)
204 {
205   session_t *app_session;
206
207   if (SSL_is_server (((openssl_ctx_t *) ctx)->ssl))
208     {
209       /*
210        * Cleanup pre-allocated app session and close transport
211        */
212       app_session =
213         session_get_if_valid (ctx->c_s_index, ctx->c_thread_index);
214       if (app_session)
215         {
216           session_free (app_session);
217           ctx->no_app_session = 1;
218           ctx->c_s_index = SESSION_INVALID_INDEX;
219           tls_disconnect_transport (ctx);
220         }
221     }
222   else
223     {
224       /*
225        * Also handles cleanup of the pre-allocated session
226        */
227       tls_notify_app_connected (ctx, SESSION_E_TLS_HANDSHAKE);
228     }
229 }
230
231 int
232 openssl_ctx_handshake_rx (tls_ctx_t * ctx, session_t * tls_session)
233 {
234   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
235   int rv = 0, err;
236
237   while (SSL_in_init (oc->ssl))
238     {
239       if (ctx->resume)
240         {
241           ctx->resume = 0;
242         }
243       else if (!svm_fifo_max_dequeue_cons (tls_session->rx_fifo))
244         break;
245
246       rv = SSL_do_handshake (oc->ssl);
247       err = SSL_get_error (oc->ssl, rv);
248
249 #ifdef HAVE_OPENSSL_ASYNC
250       if (err == SSL_ERROR_WANT_ASYNC)
251         {
252           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
253                                       tls_session);
254         }
255 #endif
256       if (err == SSL_ERROR_SSL)
257         {
258           char buf[512];
259           ERR_error_string (ERR_get_error (), buf);
260           clib_warning ("Err: %s", buf);
261
262           openssl_handle_handshake_failure (ctx);
263           return -1;
264         }
265
266       if (err != SSL_ERROR_WANT_WRITE && err != SSL_ERROR_WANT_READ)
267         break;
268     }
269   TLS_DBG (2, "tls state for %u is %s", oc->openssl_ctx_index,
270            SSL_state_string_long (oc->ssl));
271
272   if (SSL_in_init (oc->ssl))
273     return -1;
274
275   /*
276    * Handshake complete
277    */
278   if (!SSL_is_server (oc->ssl))
279     {
280       /*
281        * Verify server certificate
282        */
283       if ((rv = SSL_get_verify_result (oc->ssl)) != X509_V_OK)
284         {
285           TLS_DBG (1, " failed verify: %s\n",
286                    X509_verify_cert_error_string (rv));
287
288           /*
289            * Presence of hostname enforces strict certificate verification
290            */
291           if (ctx->srv_hostname)
292             {
293               tls_notify_app_connected (ctx, SESSION_E_TLS_HANDSHAKE);
294               return -1;
295             }
296         }
297       tls_notify_app_connected (ctx, SESSION_E_NONE);
298     }
299   else
300     {
301       /* Need to check transport status */
302       if (ctx->is_passive_close)
303         openssl_handle_handshake_failure (ctx);
304       else
305         tls_notify_app_accept (ctx);
306     }
307
308   TLS_DBG (1, "Handshake for %u complete. TLS cipher is %s",
309            oc->openssl_ctx_index, SSL_get_cipher (oc->ssl));
310   return rv;
311 }
312
313 static void
314 openssl_confirm_app_close (tls_ctx_t * ctx)
315 {
316   tls_disconnect_transport (ctx);
317   session_transport_closed_notify (&ctx->connection);
318 }
319
320 static inline int
321 openssl_ctx_write (tls_ctx_t * ctx, session_t * app_session,
322                    transport_send_params_t * sp)
323 {
324   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
325   u32 deq_max, space, enq_buf;
326   session_t *ts;
327   int wrote = 0;
328   svm_fifo_t *f;
329
330   ts = session_get_from_handle (ctx->tls_session_handle);
331   space = svm_fifo_max_enqueue_prod (ts->tx_fifo);
332   /* Leave a bit of extra space for tls ctrl data, if any needed */
333   space = clib_max ((int) space - TLSO_CTRL_BYTES, 0);
334
335   f = app_session->tx_fifo;
336
337   deq_max = svm_fifo_max_dequeue_cons (f);
338   deq_max = clib_min (deq_max, space);
339   if (!deq_max)
340     goto check_tls_fifo;
341
342   deq_max = clib_min (deq_max, sp->max_burst_size);
343
344   wrote = openssl_write_from_fifo_into_ssl (f, oc->ssl, deq_max);
345   if (!wrote)
346     goto check_tls_fifo;
347
348   if (svm_fifo_needs_deq_ntf (f, wrote))
349     session_dequeue_notify (app_session);
350
351 check_tls_fifo:
352
353   /* Deschedule and wait for deq notification if fifo is almost full */
354   enq_buf = clib_min (svm_fifo_size (ts->tx_fifo) / 2, TLSO_MIN_ENQ_SPACE);
355   if (space < wrote + enq_buf)
356     {
357       svm_fifo_add_want_deq_ntf (ts->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
358       transport_connection_deschedule (&ctx->connection);
359       sp->flags |= TRANSPORT_SND_F_DESCHED;
360     }
361   else
362     /* Request tx reschedule of the app session */
363     app_session->flags |= SESSION_F_CUSTOM_TX;
364
365   return wrote;
366 }
367
368 static inline int
369 openssl_ctx_read (tls_ctx_t * ctx, session_t * tls_session)
370 {
371   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
372   session_t *app_session;
373   int read, wrote = 0;
374   svm_fifo_t *f;
375
376   if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
377     {
378       if (openssl_ctx_handshake_rx (ctx, tls_session) < 0)
379         return 0;
380     }
381
382   app_session = session_get_from_handle (ctx->app_session_handle);
383   f = app_session->rx_fifo;
384
385   read = openssl_read_from_ssl_into_fifo (f, oc->ssl);
386
387   /* If handshake just completed, session may still be in accepting state */
388   if (read && app_session->session_state >= SESSION_STATE_READY)
389     tls_notify_app_enqueue (ctx, app_session);
390
391   if (SSL_pending (oc->ssl) > 0)
392     tls_add_vpp_q_builtin_rx_evt (tls_session);
393
394   return wrote;
395 }
396
397 static int
398 openssl_ctx_init_client (tls_ctx_t * ctx)
399 {
400   long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
401   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
402   openssl_main_t *om = &openssl_main;
403   const SSL_METHOD *method;
404   int rv, err;
405
406   method = SSLv23_client_method ();
407   if (method == NULL)
408     {
409       TLS_DBG (1, "SSLv23_method returned null");
410       return -1;
411     }
412
413   oc->ssl_ctx = SSL_CTX_new (method);
414   if (oc->ssl_ctx == NULL)
415     {
416       TLS_DBG (1, "SSL_CTX_new returned null");
417       return -1;
418     }
419
420   SSL_CTX_set_ecdh_auto (oc->ssl_ctx, 1);
421   SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
422 #ifdef HAVE_OPENSSL_ASYNC
423   if (om->async)
424     SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ASYNC);
425 #endif
426   rv = SSL_CTX_set_cipher_list (oc->ssl_ctx, (const char *) om->ciphers);
427   if (rv != 1)
428     {
429       TLS_DBG (1, "Couldn't set cipher");
430       return -1;
431     }
432
433   SSL_CTX_set_options (oc->ssl_ctx, flags);
434   SSL_CTX_set_cert_store (oc->ssl_ctx, om->cert_store);
435
436   oc->ssl = SSL_new (oc->ssl_ctx);
437   if (oc->ssl == NULL)
438     {
439       TLS_DBG (1, "Couldn't initialize ssl struct");
440       return -1;
441     }
442
443   oc->rbio = BIO_new_tls (ctx->tls_session_handle);
444   oc->wbio = BIO_new_tls (ctx->tls_session_handle);
445
446   SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
447   SSL_set_connect_state (oc->ssl);
448
449   rv = SSL_set_tlsext_host_name (oc->ssl, ctx->srv_hostname);
450   if (rv != 1)
451     {
452       TLS_DBG (1, "Couldn't set hostname");
453       return -1;
454     }
455
456   /*
457    * 2. Do the first steps in the handshake.
458    */
459   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
460            oc->openssl_ctx_index);
461
462 #ifdef HAVE_OPENSSL_ASYNC
463   session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
464   vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
465 #endif
466   while (1)
467     {
468       rv = SSL_do_handshake (oc->ssl);
469       err = SSL_get_error (oc->ssl, rv);
470 #ifdef HAVE_OPENSSL_ASYNC
471       if (err == SSL_ERROR_WANT_ASYNC)
472         {
473           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
474                                       tls_session);
475           break;
476         }
477 #endif
478       if (err != SSL_ERROR_WANT_WRITE)
479         break;
480     }
481
482   TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
483            oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
484   return 0;
485 }
486
487 static int
488 openssl_start_listen (tls_ctx_t * lctx)
489 {
490   const SSL_METHOD *method;
491   SSL_CTX *ssl_ctx;
492   int rv;
493   BIO *cert_bio;
494   X509 *srvcert;
495   EVP_PKEY *pkey;
496   u32 olc_index;
497   openssl_listen_ctx_t *olc;
498   app_cert_key_pair_t *ckpair;
499
500   long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
501   openssl_main_t *om = &openssl_main;
502
503   ckpair = app_cert_key_pair_get_if_valid (lctx->ckpair_index);
504   if (!ckpair)
505     return -1;
506
507   if (!ckpair->cert || !ckpair->key)
508     {
509       TLS_DBG (1, "tls cert and/or key not configured %d",
510                lctx->parent_app_wrk_index);
511       return -1;
512     }
513
514   method = SSLv23_method ();
515   ssl_ctx = SSL_CTX_new (method);
516   if (!ssl_ctx)
517     {
518       clib_warning ("Unable to create SSL context");
519       return -1;
520     }
521
522   SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
523 #ifdef HAVE_OPENSSL_ASYNC
524   if (om->async)
525     {
526       SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ASYNC);
527       SSL_CTX_set_async_callback (ssl_ctx, tls_async_openssl_callback);
528     }
529 #endif
530   SSL_CTX_set_options (ssl_ctx, flags);
531   SSL_CTX_set_ecdh_auto (ssl_ctx, 1);
532
533   rv = SSL_CTX_set_cipher_list (ssl_ctx, (const char *) om->ciphers);
534   if (rv != 1)
535     {
536       TLS_DBG (1, "Couldn't set cipher");
537       return -1;
538     }
539
540   /*
541    * Set the key and cert
542    */
543   cert_bio = BIO_new (BIO_s_mem ());
544   BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
545   srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
546   if (!srvcert)
547     {
548       clib_warning ("unable to parse certificate");
549       return -1;
550     }
551   SSL_CTX_use_certificate (ssl_ctx, srvcert);
552   BIO_free (cert_bio);
553
554   cert_bio = BIO_new (BIO_s_mem ());
555   BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
556   pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
557   if (!pkey)
558     {
559       clib_warning ("unable to parse pkey");
560       return -1;
561     }
562   SSL_CTX_use_PrivateKey (ssl_ctx, pkey);
563   BIO_free (cert_bio);
564
565   olc_index = openssl_listen_ctx_alloc ();
566   olc = openssl_lctx_get (olc_index);
567   olc->ssl_ctx = ssl_ctx;
568   olc->srvcert = srvcert;
569   olc->pkey = pkey;
570
571   /* store SSL_CTX into TLS level structure */
572   lctx->tls_ssl_ctx = olc_index;
573
574   return 0;
575
576 }
577
578 static int
579 openssl_stop_listen (tls_ctx_t * lctx)
580 {
581   u32 olc_index;
582   openssl_listen_ctx_t *olc;
583
584   olc_index = lctx->tls_ssl_ctx;
585   olc = openssl_lctx_get (olc_index);
586
587   X509_free (olc->srvcert);
588   EVP_PKEY_free (olc->pkey);
589
590   SSL_CTX_free (olc->ssl_ctx);
591   openssl_listen_ctx_free (olc);
592
593   return 0;
594 }
595
596 static int
597 openssl_ctx_init_server (tls_ctx_t * ctx)
598 {
599   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
600   u32 olc_index = ctx->tls_ssl_ctx;
601   openssl_listen_ctx_t *olc;
602   int rv, err;
603
604   /* Start a new connection */
605
606   olc = openssl_lctx_get (olc_index);
607   oc->ssl = SSL_new (olc->ssl_ctx);
608   if (oc->ssl == NULL)
609     {
610       TLS_DBG (1, "Couldn't initialize ssl struct");
611       return -1;
612     }
613
614   oc->rbio = BIO_new_tls (ctx->tls_session_handle);
615   oc->wbio = BIO_new_tls (ctx->tls_session_handle);
616
617   SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
618   SSL_set_accept_state (oc->ssl);
619
620   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
621            oc->openssl_ctx_index);
622
623 #ifdef HAVE_OPENSSL_ASYNC
624   session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
625   vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
626 #endif
627   while (1)
628     {
629       rv = SSL_do_handshake (oc->ssl);
630       err = SSL_get_error (oc->ssl, rv);
631 #ifdef HAVE_OPENSSL_ASYNC
632       if (err == SSL_ERROR_WANT_ASYNC)
633         {
634           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
635                                       tls_session);
636           break;
637         }
638 #endif
639       if (err != SSL_ERROR_WANT_WRITE)
640         break;
641     }
642
643   TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
644            oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
645   return 0;
646 }
647
648 static u8
649 openssl_handshake_is_over (tls_ctx_t * ctx)
650 {
651   openssl_ctx_t *mc = (openssl_ctx_t *) ctx;
652   if (!mc->ssl)
653     return 0;
654   return SSL_is_init_finished (mc->ssl);
655 }
656
657 static int
658 openssl_transport_close (tls_ctx_t * ctx)
659 {
660 #ifdef HAVE_OPENSSL_ASYNC
661   if (vpp_openssl_is_inflight (ctx))
662     return 0;
663 #endif
664
665   if (!openssl_handshake_is_over (ctx))
666     {
667       openssl_handle_handshake_failure (ctx);
668       return 0;
669     }
670   session_transport_closing_notify (&ctx->connection);
671   return 0;
672 }
673
674 static int
675 openssl_app_close (tls_ctx_t * ctx)
676 {
677   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
678   session_t *app_session;
679
680   /* Wait for all data to be written to tcp */
681   app_session = session_get_from_handle (ctx->app_session_handle);
682   if (BIO_ctrl_pending (oc->rbio) <= 0
683       && !svm_fifo_max_dequeue_cons (app_session->tx_fifo))
684     openssl_confirm_app_close (ctx);
685   else
686     ctx->app_closed = 1;
687   return 0;
688 }
689
690 const static tls_engine_vft_t openssl_engine = {
691   .ctx_alloc = openssl_ctx_alloc,
692   .ctx_free = openssl_ctx_free,
693   .ctx_get = openssl_ctx_get,
694   .ctx_get_w_thread = openssl_ctx_get_w_thread,
695   .ctx_init_server = openssl_ctx_init_server,
696   .ctx_init_client = openssl_ctx_init_client,
697   .ctx_write = openssl_ctx_write,
698   .ctx_read = openssl_ctx_read,
699   .ctx_handshake_is_over = openssl_handshake_is_over,
700   .ctx_start_listen = openssl_start_listen,
701   .ctx_stop_listen = openssl_stop_listen,
702   .ctx_transport_close = openssl_transport_close,
703   .ctx_app_close = openssl_app_close,
704 };
705
706 int
707 tls_init_ca_chain (void)
708 {
709   openssl_main_t *om = &openssl_main;
710   tls_main_t *tm = vnet_tls_get_main ();
711   BIO *cert_bio;
712   X509 *testcert;
713   int rv;
714
715   if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
716     {
717       clib_warning ("Could not initialize TLS CA certificates");
718       return -1;
719     }
720
721   if (!(om->cert_store = X509_STORE_new ()))
722     {
723       clib_warning ("failed to create cert store");
724       return -1;
725     }
726
727 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
728   rv = X509_STORE_load_file (om->cert_store, tm->ca_cert_path);
729 #else
730   rv = X509_STORE_load_locations (om->cert_store, tm->ca_cert_path, 0);
731 #endif
732
733   if (rv < 0)
734     {
735       clib_warning ("failed to load ca certificate");
736     }
737
738   if (tm->use_test_cert_in_ca)
739     {
740       cert_bio = BIO_new (BIO_s_mem ());
741       BIO_write (cert_bio, test_srv_crt_rsa, test_srv_crt_rsa_len);
742       testcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
743       if (!testcert)
744         {
745           clib_warning ("unable to parse certificate");
746           return -1;
747         }
748       X509_STORE_add_cert (om->cert_store, testcert);
749       rv = 0;
750     }
751   return (rv < 0 ? -1 : 0);
752 }
753
754 int
755 tls_openssl_set_ciphers (char *ciphers)
756 {
757   openssl_main_t *om = &openssl_main;
758   int i;
759
760   if (!ciphers)
761     {
762       return -1;
763     }
764
765   vec_validate (om->ciphers, strlen (ciphers) - 1);
766   for (i = 0; i < vec_len (om->ciphers); i++)
767     {
768       om->ciphers[i] = toupper (ciphers[i]);
769     }
770
771   return 0;
772
773 }
774
775 static clib_error_t *
776 tls_openssl_init (vlib_main_t * vm)
777 {
778   vlib_thread_main_t *vtm = vlib_get_thread_main ();
779   openssl_main_t *om = &openssl_main;
780   clib_error_t *error = 0;
781   u32 num_threads;
782
783   error = tls_openssl_api_init (vm);
784   num_threads = 1 /* main thread */  + vtm->n_threads;
785
786   SSL_library_init ();
787   SSL_load_error_strings ();
788
789   if (tls_init_ca_chain ())
790     {
791       clib_warning ("failed to initialize TLS CA chain");
792       return 0;
793     }
794
795   vec_validate (om->ctx_pool, num_threads - 1);
796
797   tls_register_engine (&openssl_engine, CRYPTO_ENGINE_OPENSSL);
798
799   om->engine_init = 0;
800
801   /* default ciphers */
802   tls_openssl_set_ciphers
803     ("ALL:!ADH:!LOW:!EXP:!MD5:!RC4-SHA:!DES-CBC3-SHA:@STRENGTH");
804
805   return error;
806 }
807 /* *INDENT-OFF* */
808 VLIB_INIT_FUNCTION (tls_openssl_init) =
809 {
810   .runs_after = VLIB_INITS("tls_init"),
811 };
812 /* *INDENT-ON* */
813
814 #ifdef HAVE_OPENSSL_ASYNC
815 static clib_error_t *
816 tls_openssl_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
817                             vlib_cli_command_t * cmd)
818 {
819   openssl_main_t *om = &openssl_main;
820   char *engine_name = NULL;
821   char *engine_alg = NULL;
822   char *ciphers = NULL;
823   u8 engine_name_set = 0;
824   int i, async = 0;
825
826   /* By present, it is not allowed to configure engine again after running */
827   if (om->engine_init)
828     {
829       clib_warning ("engine has started!\n");
830       return clib_error_return
831         (0, "engine has started, and no config is accepted");
832     }
833
834   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
835     {
836       if (unformat (input, "engine %s", &engine_name))
837         {
838           engine_name_set = 1;
839         }
840       else if (unformat (input, "async"))
841         {
842           async = 1;
843         }
844       else if (unformat (input, "alg %s", &engine_alg))
845         {
846           for (i = 0; i < strnlen (engine_alg, MAX_CRYPTO_LEN); i++)
847             engine_alg[i] = toupper (engine_alg[i]);
848         }
849       else if (unformat (input, "ciphers %s", &ciphers))
850         {
851           tls_openssl_set_ciphers (ciphers);
852         }
853       else
854         return clib_error_return (0, "failed: unknown input `%U'",
855                                   format_unformat_error, input);
856     }
857
858   /* reset parameters if engine is not configured */
859   if (!engine_name_set)
860     {
861       clib_warning ("No engine provided! \n");
862       async = 0;
863     }
864   else
865     {
866       vnet_session_enable_disable (vm, 1);
867       if (openssl_engine_register (engine_name, engine_alg, async) < 0)
868         {
869           return clib_error_return (0, "Failed to register %s polling",
870                                     engine_name);
871         }
872       else
873         {
874           vlib_cli_output (vm, "Successfully register engine %s\n",
875                            engine_name);
876         }
877     }
878   om->async = async;
879
880   return 0;
881 }
882
883 /* *INDENT-OFF* */
884 VLIB_CLI_COMMAND (tls_openssl_set_command, static) =
885 {
886   .path = "tls openssl set",
887   .short_help = "tls openssl set [engine <engine name>] [alg [algorithm] [async]",
888   .function = tls_openssl_set_command_fn,
889 };
890 /* *INDENT-ON* */
891 #endif
892
893 /* *INDENT-OFF* */
894 VLIB_PLUGIN_REGISTER () = {
895     .version = VPP_BUILD_VER,
896     .description = "Transport Layer Security (TLS) Engine, OpenSSL Based",
897 };
898 /* *INDENT-ON* */
899
900 /*
901  * fd.io coding-style-patch-verification: ON
902  *
903  * Local Variables:
904  * eval: (c-set-style "gnu")
905  * End:
906  */