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