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