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