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