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