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