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