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