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