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