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