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