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