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