session tls: improve app transports tx scheduling
[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
30 #define MAX_CRYPTO_LEN 64
31
32 openssl_main_t openssl_main;
33 static u32
34 openssl_ctx_alloc (void)
35 {
36   u8 thread_index = vlib_get_thread_index ();
37   openssl_main_t *tm = &openssl_main;
38   openssl_ctx_t **ctx;
39
40   pool_get (tm->ctx_pool[thread_index], ctx);
41   if (!(*ctx))
42     *ctx = clib_mem_alloc (sizeof (openssl_ctx_t));
43
44   clib_memset (*ctx, 0, sizeof (openssl_ctx_t));
45   (*ctx)->ctx.c_thread_index = thread_index;
46   (*ctx)->ctx.tls_ctx_engine = CRYPTO_ENGINE_OPENSSL;
47   (*ctx)->ctx.app_session_handle = SESSION_INVALID_HANDLE;
48   (*ctx)->openssl_ctx_index = ctx - tm->ctx_pool[thread_index];
49   return ((*ctx)->openssl_ctx_index);
50 }
51
52 static void
53 openssl_ctx_free (tls_ctx_t * ctx)
54 {
55   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
56
57   if (SSL_is_init_finished (oc->ssl) && !ctx->is_passive_close)
58     SSL_shutdown (oc->ssl);
59
60   SSL_free (oc->ssl);
61
62 #ifdef HAVE_OPENSSL_ASYNC
63   openssl_evt_free (ctx->evt_index, ctx->c_thread_index);
64 #endif
65   vec_free (ctx->srv_hostname);
66   pool_put_index (openssl_main.ctx_pool[ctx->c_thread_index],
67                   oc->openssl_ctx_index);
68 }
69
70 tls_ctx_t *
71 openssl_ctx_get (u32 ctx_index)
72 {
73   openssl_ctx_t **ctx;
74   ctx = pool_elt_at_index (openssl_main.ctx_pool[vlib_get_thread_index ()],
75                            ctx_index);
76   return &(*ctx)->ctx;
77 }
78
79 tls_ctx_t *
80 openssl_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
81 {
82   openssl_ctx_t **ctx;
83   ctx = pool_elt_at_index (openssl_main.ctx_pool[thread_index], ctx_index);
84   return &(*ctx)->ctx;
85 }
86
87 static u32
88 openssl_listen_ctx_alloc (void)
89 {
90   openssl_main_t *om = &openssl_main;
91   openssl_listen_ctx_t *lctx;
92
93   pool_get (om->lctx_pool, lctx);
94
95   clib_memset (lctx, 0, sizeof (openssl_listen_ctx_t));
96   lctx->openssl_lctx_index = lctx - om->lctx_pool;
97   return lctx->openssl_lctx_index;
98 }
99
100 static void
101 openssl_listen_ctx_free (openssl_listen_ctx_t * lctx)
102 {
103   pool_put_index (openssl_main.lctx_pool, lctx->openssl_lctx_index);
104 }
105
106 openssl_listen_ctx_t *
107 openssl_lctx_get (u32 lctx_index)
108 {
109   return pool_elt_at_index (openssl_main.lctx_pool, lctx_index);
110 }
111
112 static int
113 openssl_read_from_bio_into_fifo (svm_fifo_t * f, BIO * bio)
114 {
115   u32 enq_now, enq_max;
116   svm_fifo_chunk_t *c;
117   int read, rv;
118
119   enq_max = svm_fifo_max_enqueue_prod (f);
120   if (!enq_max)
121     return 0;
122
123   svm_fifo_fill_chunk_list (f);
124
125   enq_now = clib_min (svm_fifo_max_write_chunk (f), enq_max);
126   if (!enq_now)
127     return 0;
128
129   read = BIO_read (bio, svm_fifo_tail (f), enq_now);
130   if (read <= 0)
131     return 0;
132
133   c = svm_fifo_tail_chunk (f);
134   while ((c = c->next) && read < enq_max)
135     {
136       enq_now = clib_min (c->length, enq_max - read);
137       rv = BIO_read (bio, c->data, enq_now);
138       read += rv > 0 ? rv : 0;
139
140       if (rv < enq_now)
141         break;
142     }
143
144   svm_fifo_enqueue_nocopy (f, read);
145
146   return read;
147 }
148
149 static int
150 openssl_read_from_ssl_into_fifo (svm_fifo_t * f, SSL * ssl)
151 {
152   u32 enq_now, enq_max;
153   svm_fifo_chunk_t *c;
154   int read, rv;
155
156   enq_max = svm_fifo_max_enqueue_prod (f);
157   if (!enq_max)
158     return 0;
159
160   svm_fifo_fill_chunk_list (f);
161
162   enq_now = clib_min (svm_fifo_max_write_chunk (f), enq_max);
163   if (!enq_now)
164     return 0;
165
166   read = SSL_read (ssl, svm_fifo_tail (f), enq_now);
167   if (read <= 0)
168     return 0;
169
170   c = svm_fifo_tail_chunk (f);
171   while ((c = c->next) && read < enq_max)
172     {
173       enq_now = clib_min (c->length, enq_max - read);
174       rv = SSL_read (ssl, c->data, enq_now);
175       read += rv > 0 ? rv : 0;
176
177       if (rv < enq_now)
178         break;
179     }
180
181   svm_fifo_enqueue_nocopy (f, read);
182
183   return read;
184 }
185
186 static int
187 openssl_write_from_fifo_into_bio (svm_fifo_t * f, BIO * bio, u32 len)
188 {
189   svm_fifo_chunk_t *c;
190   int wrote, rv;
191   u32 deq_now;
192
193   deq_now = clib_min (svm_fifo_max_read_chunk (f), len);
194   wrote = BIO_write (bio, svm_fifo_head (f), deq_now);
195   if (wrote <= 0)
196     return 0;
197
198   c = svm_fifo_head_chunk (f);
199   while ((c = c->next) && wrote < len)
200     {
201       deq_now = clib_min (c->length, len - wrote);
202       rv = BIO_write (bio, c->data, deq_now);
203       wrote += rv > 0 ? rv : 0;
204
205       if (rv < deq_now)
206         break;
207     }
208
209   svm_fifo_dequeue_drop (f, wrote);
210
211   return wrote;
212 }
213
214 static int
215 openssl_write_from_fifo_into_ssl (svm_fifo_t * f, SSL * ssl, u32 len)
216 {
217   svm_fifo_chunk_t *c;
218   int wrote = 0, rv;
219   u32 deq_now;
220
221   deq_now = clib_min (svm_fifo_max_read_chunk (f), len);
222   wrote = SSL_write (ssl, svm_fifo_head (f), deq_now);
223   if (wrote <= 0)
224     return 0;
225
226   c = svm_fifo_head_chunk (f);
227   while ((c = c->next) && wrote < len)
228     {
229       deq_now = clib_min (c->length, len - wrote);
230       rv = SSL_write (ssl, c->data, deq_now);
231       wrote += rv > 0 ? rv : 0;
232
233       if (rv < deq_now)
234         break;
235     }
236
237   svm_fifo_dequeue_drop (f, wrote);
238
239   return wrote;
240 }
241
242 static int
243 openssl_try_handshake_read (openssl_ctx_t * oc, session_t * tls_session)
244 {
245   svm_fifo_t *f;
246   u32 deq_max;
247
248   f = tls_session->rx_fifo;
249   deq_max = svm_fifo_max_dequeue_cons (f);
250   if (!deq_max)
251     return 0;
252
253   return openssl_write_from_fifo_into_bio (f, oc->wbio, deq_max);
254 }
255
256 static int
257 openssl_try_handshake_write (openssl_ctx_t * oc, session_t * tls_session)
258 {
259   u32 read;
260
261   if (BIO_ctrl_pending (oc->rbio) <= 0)
262     return 0;
263
264   read = openssl_read_from_bio_into_fifo (tls_session->tx_fifo, oc->rbio);
265   if (read)
266     tls_add_vpp_q_tx_evt (tls_session);
267
268   return read;
269 }
270
271 #ifdef HAVE_OPENSSL_ASYNC
272 static int
273 openssl_check_async_status (tls_ctx_t * ctx, openssl_resume_handler * handler,
274                             session_t * session)
275 {
276   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
277   int estatus;
278
279   SSL_get_async_status (oc->ssl, &estatus);
280   if (estatus == ASYNC_STATUS_EAGAIN)
281     {
282       vpp_tls_async_update_event (ctx, 1);
283     }
284   else
285     {
286       vpp_tls_async_update_event (ctx, 0);
287     }
288
289   return 1;
290
291 }
292
293 #endif
294
295 static void
296 openssl_handle_handshake_failure (tls_ctx_t * ctx)
297 {
298   session_t *app_session;
299
300   if (SSL_is_server (((openssl_ctx_t *) ctx)->ssl))
301     {
302       /*
303        * Cleanup pre-allocated app session and close transport
304        */
305       app_session =
306         session_get_if_valid (ctx->c_s_index, ctx->c_thread_index);
307       if (app_session)
308         {
309           session_free (app_session);
310           ctx->no_app_session = 1;
311           ctx->c_s_index = SESSION_INVALID_INDEX;
312           tls_disconnect_transport (ctx);
313         }
314     }
315   else
316     {
317       /*
318        * Also handles cleanup of the pre-allocated session
319        */
320       tls_notify_app_connected (ctx, SESSION_E_TLS_HANDSHAKE);
321     }
322 }
323
324 int
325 openssl_ctx_handshake_rx (tls_ctx_t * ctx, session_t * tls_session)
326 {
327   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
328   int rv = 0, err;
329
330   while (SSL_in_init (oc->ssl))
331     {
332       if (ctx->resume)
333         {
334           ctx->resume = 0;
335         }
336       else if (!openssl_try_handshake_read (oc, tls_session))
337         break;
338
339       rv = SSL_do_handshake (oc->ssl);
340       err = SSL_get_error (oc->ssl, rv);
341
342 #ifdef HAVE_OPENSSL_ASYNC
343       if (err == SSL_ERROR_WANT_ASYNC)
344         {
345           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
346                                       tls_session);
347         }
348 #endif
349       if (err == SSL_ERROR_SSL)
350         {
351           char buf[512];
352           ERR_error_string (ERR_get_error (), buf);
353           clib_warning ("Err: %s", buf);
354
355           openssl_handle_handshake_failure (ctx);
356           return -1;
357         }
358
359       openssl_try_handshake_write (oc, tls_session);
360
361       if (err != SSL_ERROR_WANT_WRITE)
362         break;
363     }
364   TLS_DBG (2, "tls state for %u is %s", oc->openssl_ctx_index,
365            SSL_state_string_long (oc->ssl));
366
367   if (SSL_in_init (oc->ssl))
368     return -1;
369
370   /*
371    * Handshake complete
372    */
373   if (!SSL_is_server (oc->ssl))
374     {
375       /*
376        * Verify server certificate
377        */
378       if ((rv = SSL_get_verify_result (oc->ssl)) != X509_V_OK)
379         {
380           TLS_DBG (1, " failed verify: %s\n",
381                    X509_verify_cert_error_string (rv));
382
383           /*
384            * Presence of hostname enforces strict certificate verification
385            */
386           if (ctx->srv_hostname)
387             {
388               tls_notify_app_connected (ctx, SESSION_E_TLS_HANDSHAKE);
389               return -1;
390             }
391         }
392       tls_notify_app_connected (ctx, SESSION_E_NONE);
393     }
394   else
395     {
396       /* Need to check transport status */
397       if (ctx->is_passive_close)
398         openssl_handle_handshake_failure (ctx);
399       else
400         tls_notify_app_accept (ctx);
401     }
402
403   TLS_DBG (1, "Handshake for %u complete. TLS cipher is %s",
404            oc->openssl_ctx_index, SSL_get_cipher (oc->ssl));
405   return rv;
406 }
407
408 static void
409 openssl_confirm_app_close (tls_ctx_t * ctx)
410 {
411   tls_disconnect_transport (ctx);
412   session_transport_closed_notify (&ctx->connection);
413 }
414
415 static inline int
416 openssl_ctx_write (tls_ctx_t * ctx, session_t * app_session, u32 max_write)
417 {
418   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
419   int wrote = 0, read, max_buf = 4 * TLS_CHUNK_SIZE, max_space;
420   u32 deq_max, to_write;
421   session_t *tls_session;
422   svm_fifo_t *f;
423
424   f = app_session->tx_fifo;
425
426   deq_max = svm_fifo_max_dequeue_cons (f);
427   if (!deq_max)
428     goto check_tls_fifo;
429
430   deq_max = clib_min (deq_max, max_write);
431
432   /* Figure out how much data to write */
433   max_space = max_buf - BIO_ctrl_pending (oc->rbio);
434   max_space = (max_space < 0) ? 0 : max_space;
435   to_write = clib_min (deq_max, (u32) max_space);
436
437   wrote = openssl_write_from_fifo_into_ssl (f, oc->ssl, to_write);
438   if (!wrote)
439     goto check_tls_fifo;
440
441   if (svm_fifo_needs_deq_ntf (f, wrote))
442     session_dequeue_notify (app_session);
443
444 check_tls_fifo:
445
446   if (BIO_ctrl_pending (oc->rbio) <= 0)
447     return wrote;
448
449   tls_session = session_get_from_handle (ctx->tls_session_handle);
450
451   read = openssl_read_from_bio_into_fifo (tls_session->tx_fifo, oc->rbio);
452   if (!read)
453     {
454       /* Request tx reschedule of the app session */
455       app_session->flags |= SESSION_F_CUSTOM_TX;
456       return wrote;
457     }
458
459   tls_add_vpp_q_tx_evt (tls_session);
460
461   if (BIO_ctrl_pending (oc->rbio) > 0)
462     app_session->flags |= SESSION_F_CUSTOM_TX;
463   else if (ctx->app_closed)
464     openssl_confirm_app_close (ctx);
465
466   return wrote;
467 }
468
469 static inline int
470 openssl_ctx_read (tls_ctx_t * ctx, session_t * tls_session)
471 {
472   int read, wrote = 0, max_space, max_buf = 4 * TLS_CHUNK_SIZE;
473   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
474   u32 deq_max, to_write;
475   session_t *app_session;
476   svm_fifo_t *f;
477
478   if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
479     {
480       if (openssl_ctx_handshake_rx (ctx, tls_session) < 0)
481         return 0;
482       else
483         goto check_app_fifo;
484     }
485
486   f = tls_session->rx_fifo;
487
488   deq_max = svm_fifo_max_dequeue_cons (f);
489   max_space = max_buf - BIO_ctrl_pending (oc->wbio);
490   max_space = max_space < 0 ? 0 : max_space;
491   to_write = clib_min (deq_max, max_space);
492   if (!to_write)
493     goto check_app_fifo;
494
495   wrote = openssl_write_from_fifo_into_bio (f, oc->wbio, to_write);
496   if (!wrote)
497     {
498       tls_add_vpp_q_builtin_rx_evt (tls_session);
499       goto check_app_fifo;
500     }
501
502   if (svm_fifo_max_dequeue_cons (f))
503     tls_add_vpp_q_builtin_rx_evt (tls_session);
504
505 check_app_fifo:
506
507   if (BIO_ctrl_pending (oc->wbio) <= 0)
508     return wrote;
509
510   app_session = session_get_from_handle (ctx->app_session_handle);
511   f = app_session->rx_fifo;
512
513   read = openssl_read_from_ssl_into_fifo (f, oc->ssl);
514   if (!read)
515     {
516       tls_add_vpp_q_builtin_rx_evt (tls_session);
517       return wrote;
518     }
519
520   /* If handshake just completed, session may still be in accepting state */
521   if (app_session->session_state >= SESSION_STATE_READY)
522     tls_notify_app_enqueue (ctx, app_session);
523   if (SSL_pending (oc->ssl) > 0)
524     tls_add_vpp_q_builtin_rx_evt (tls_session);
525
526   return wrote;
527 }
528
529 static int
530 openssl_ctx_init_client (tls_ctx_t * ctx)
531 {
532   long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
533   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
534   openssl_main_t *om = &openssl_main;
535   session_t *tls_session;
536   const SSL_METHOD *method;
537   int rv, err;
538
539   method = SSLv23_client_method ();
540   if (method == NULL)
541     {
542       TLS_DBG (1, "SSLv23_method returned null");
543       return -1;
544     }
545
546   oc->ssl_ctx = SSL_CTX_new (method);
547   if (oc->ssl_ctx == NULL)
548     {
549       TLS_DBG (1, "SSL_CTX_new returned null");
550       return -1;
551     }
552
553   SSL_CTX_set_ecdh_auto (oc->ssl_ctx, 1);
554   SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
555 #ifdef HAVE_OPENSSL_ASYNC
556   if (om->async)
557     SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ASYNC);
558 #endif
559   rv = SSL_CTX_set_cipher_list (oc->ssl_ctx, (const char *) om->ciphers);
560   if (rv != 1)
561     {
562       TLS_DBG (1, "Couldn't set cipher");
563       return -1;
564     }
565
566   SSL_CTX_set_options (oc->ssl_ctx, flags);
567   SSL_CTX_set_cert_store (oc->ssl_ctx, om->cert_store);
568
569   oc->ssl = SSL_new (oc->ssl_ctx);
570   if (oc->ssl == NULL)
571     {
572       TLS_DBG (1, "Couldn't initialize ssl struct");
573       return -1;
574     }
575
576   oc->rbio = BIO_new (BIO_s_mem ());
577   oc->wbio = BIO_new (BIO_s_mem ());
578
579   BIO_set_mem_eof_return (oc->rbio, -1);
580   BIO_set_mem_eof_return (oc->wbio, -1);
581
582   SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
583   SSL_set_connect_state (oc->ssl);
584
585   rv = SSL_set_tlsext_host_name (oc->ssl, ctx->srv_hostname);
586   if (rv != 1)
587     {
588       TLS_DBG (1, "Couldn't set hostname");
589       return -1;
590     }
591
592   /*
593    * 2. Do the first steps in the handshake.
594    */
595   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
596            oc->openssl_ctx_index);
597
598   tls_session = session_get_from_handle (ctx->tls_session_handle);
599
600 #ifdef HAVE_OPENSSL_ASYNC
601   vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
602 #endif
603   while (1)
604     {
605       rv = SSL_do_handshake (oc->ssl);
606       err = SSL_get_error (oc->ssl, rv);
607       openssl_try_handshake_write (oc, tls_session);
608 #ifdef HAVE_OPENSSL_ASYNC
609       if (err == SSL_ERROR_WANT_ASYNC)
610         {
611           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
612                                       tls_session);
613           break;
614         }
615 #endif
616       if (err != SSL_ERROR_WANT_WRITE)
617         break;
618     }
619
620   TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
621            oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
622   return 0;
623 }
624
625 static int
626 openssl_start_listen (tls_ctx_t * lctx)
627 {
628   const SSL_METHOD *method;
629   SSL_CTX *ssl_ctx;
630   int rv;
631   BIO *cert_bio;
632   X509 *srvcert;
633   EVP_PKEY *pkey;
634   u32 olc_index;
635   openssl_listen_ctx_t *olc;
636   app_cert_key_pair_t *ckpair;
637
638   long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
639   openssl_main_t *om = &openssl_main;
640
641   ckpair = app_cert_key_pair_get_if_valid (lctx->ckpair_index);
642   if (!ckpair)
643     return -1;
644
645   if (!ckpair->cert || !ckpair->key)
646     {
647       TLS_DBG (1, "tls cert and/or key not configured %d",
648                lctx->parent_app_wrk_index);
649       return -1;
650     }
651
652   method = SSLv23_method ();
653   ssl_ctx = SSL_CTX_new (method);
654   if (!ssl_ctx)
655     {
656       clib_warning ("Unable to create SSL context");
657       return -1;
658     }
659
660   SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
661 #ifdef HAVE_OPENSSL_ASYNC
662   if (om->async)
663     {
664       SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ASYNC);
665       SSL_CTX_set_async_callback (ssl_ctx, tls_async_openssl_callback);
666     }
667 #endif
668   SSL_CTX_set_options (ssl_ctx, flags);
669   SSL_CTX_set_ecdh_auto (ssl_ctx, 1);
670
671   rv = SSL_CTX_set_cipher_list (ssl_ctx, (const char *) om->ciphers);
672   if (rv != 1)
673     {
674       TLS_DBG (1, "Couldn't set cipher");
675       return -1;
676     }
677
678   /*
679    * Set the key and cert
680    */
681   cert_bio = BIO_new (BIO_s_mem ());
682   BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
683   srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
684   if (!srvcert)
685     {
686       clib_warning ("unable to parse certificate");
687       return -1;
688     }
689   SSL_CTX_use_certificate (ssl_ctx, srvcert);
690   BIO_free (cert_bio);
691
692   cert_bio = BIO_new (BIO_s_mem ());
693   BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
694   pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
695   if (!pkey)
696     {
697       clib_warning ("unable to parse pkey");
698       return -1;
699     }
700   SSL_CTX_use_PrivateKey (ssl_ctx, pkey);
701   BIO_free (cert_bio);
702
703   olc_index = openssl_listen_ctx_alloc ();
704   olc = openssl_lctx_get (olc_index);
705   olc->ssl_ctx = ssl_ctx;
706   olc->srvcert = srvcert;
707   olc->pkey = pkey;
708
709   /* store SSL_CTX into TLS level structure */
710   lctx->tls_ssl_ctx = olc_index;
711
712   return 0;
713
714 }
715
716 static int
717 openssl_stop_listen (tls_ctx_t * lctx)
718 {
719   u32 olc_index;
720   openssl_listen_ctx_t *olc;
721
722   olc_index = lctx->tls_ssl_ctx;
723   olc = openssl_lctx_get (olc_index);
724
725   X509_free (olc->srvcert);
726   EVP_PKEY_free (olc->pkey);
727
728   SSL_CTX_free (olc->ssl_ctx);
729   openssl_listen_ctx_free (olc);
730
731   return 0;
732 }
733
734 static int
735 openssl_ctx_init_server (tls_ctx_t * ctx)
736 {
737   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
738   u32 olc_index = ctx->tls_ssl_ctx;
739   openssl_listen_ctx_t *olc;
740   session_t *tls_session;
741   int rv, err;
742
743   /* Start a new connection */
744
745   olc = openssl_lctx_get (olc_index);
746   oc->ssl = SSL_new (olc->ssl_ctx);
747   if (oc->ssl == NULL)
748     {
749       TLS_DBG (1, "Couldn't initialize ssl struct");
750       return -1;
751     }
752
753   oc->rbio = BIO_new (BIO_s_mem ());
754   oc->wbio = BIO_new (BIO_s_mem ());
755
756   BIO_set_mem_eof_return (oc->rbio, -1);
757   BIO_set_mem_eof_return (oc->wbio, -1);
758
759   SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
760   SSL_set_accept_state (oc->ssl);
761
762   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
763            oc->openssl_ctx_index);
764
765   tls_session = session_get_from_handle (ctx->tls_session_handle);
766 #ifdef HAVE_OPENSSL_ASYNC
767   vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
768 #endif
769   while (1)
770     {
771       rv = SSL_do_handshake (oc->ssl);
772       err = SSL_get_error (oc->ssl, rv);
773       openssl_try_handshake_write (oc, tls_session);
774 #ifdef HAVE_OPENSSL_ASYNC
775       if (err == SSL_ERROR_WANT_ASYNC)
776         {
777           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
778                                       tls_session);
779           break;
780         }
781 #endif
782       if (err != SSL_ERROR_WANT_WRITE)
783         break;
784     }
785
786   TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
787            oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
788   return 0;
789 }
790
791 static u8
792 openssl_handshake_is_over (tls_ctx_t * ctx)
793 {
794   openssl_ctx_t *mc = (openssl_ctx_t *) ctx;
795   if (!mc->ssl)
796     return 0;
797   return SSL_is_init_finished (mc->ssl);
798 }
799
800 static int
801 openssl_transport_close (tls_ctx_t * ctx)
802 {
803 #ifdef HAVE_OPENSSL_ASYNC
804   if (vpp_openssl_is_inflight (ctx))
805     return 0;
806 #endif
807
808   if (!openssl_handshake_is_over (ctx))
809     {
810       openssl_handle_handshake_failure (ctx);
811       return 0;
812     }
813   session_transport_closing_notify (&ctx->connection);
814   return 0;
815 }
816
817 static int
818 openssl_app_close (tls_ctx_t * ctx)
819 {
820   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
821   session_t *app_session;
822
823   /* Wait for all data to be written to tcp */
824   app_session = session_get_from_handle (ctx->app_session_handle);
825   if (BIO_ctrl_pending (oc->rbio) <= 0
826       && !svm_fifo_max_dequeue_cons (app_session->tx_fifo))
827     openssl_confirm_app_close (ctx);
828   else
829     ctx->app_closed = 1;
830   return 0;
831 }
832
833 const static tls_engine_vft_t openssl_engine = {
834   .ctx_alloc = openssl_ctx_alloc,
835   .ctx_free = openssl_ctx_free,
836   .ctx_get = openssl_ctx_get,
837   .ctx_get_w_thread = openssl_ctx_get_w_thread,
838   .ctx_init_server = openssl_ctx_init_server,
839   .ctx_init_client = openssl_ctx_init_client,
840   .ctx_write = openssl_ctx_write,
841   .ctx_read = openssl_ctx_read,
842   .ctx_handshake_is_over = openssl_handshake_is_over,
843   .ctx_start_listen = openssl_start_listen,
844   .ctx_stop_listen = openssl_stop_listen,
845   .ctx_transport_close = openssl_transport_close,
846   .ctx_app_close = openssl_app_close,
847 };
848
849 int
850 tls_init_ca_chain (void)
851 {
852   openssl_main_t *om = &openssl_main;
853   tls_main_t *tm = vnet_tls_get_main ();
854   BIO *cert_bio;
855   X509 *testcert;
856   int rv;
857
858   if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
859     {
860       clib_warning ("Could not initialize TLS CA certificates");
861       return -1;
862     }
863
864   if (!(om->cert_store = X509_STORE_new ()))
865     {
866       clib_warning ("failed to create cert store");
867       return -1;
868     }
869
870 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
871   rv = X509_STORE_load_file (om->cert_store, tm->ca_cert_path);
872 #else
873   rv = X509_STORE_load_locations (om->cert_store, tm->ca_cert_path, 0);
874 #endif
875
876   if (rv < 0)
877     {
878       clib_warning ("failed to load ca certificate");
879     }
880
881   if (tm->use_test_cert_in_ca)
882     {
883       cert_bio = BIO_new (BIO_s_mem ());
884       BIO_write (cert_bio, test_srv_crt_rsa, test_srv_crt_rsa_len);
885       testcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
886       if (!testcert)
887         {
888           clib_warning ("unable to parse certificate");
889           return -1;
890         }
891       X509_STORE_add_cert (om->cert_store, testcert);
892       rv = 0;
893     }
894   return (rv < 0 ? -1 : 0);
895 }
896
897 int
898 tls_openssl_set_ciphers (char *ciphers)
899 {
900   openssl_main_t *om = &openssl_main;
901   int i;
902
903   if (!ciphers)
904     {
905       return -1;
906     }
907
908   vec_validate (om->ciphers, strlen (ciphers) - 1);
909   for (i = 0; i < vec_len (om->ciphers); i++)
910     {
911       om->ciphers[i] = toupper (ciphers[i]);
912     }
913
914   return 0;
915
916 }
917
918 static clib_error_t *
919 tls_openssl_init (vlib_main_t * vm)
920 {
921   vlib_thread_main_t *vtm = vlib_get_thread_main ();
922   openssl_main_t *om = &openssl_main;
923   clib_error_t *error = 0;
924   u32 num_threads;
925
926   error = tls_openssl_api_init (vm);
927   num_threads = 1 /* main thread */  + vtm->n_threads;
928
929   SSL_library_init ();
930   SSL_load_error_strings ();
931
932   if (tls_init_ca_chain ())
933     {
934       clib_warning ("failed to initialize TLS CA chain");
935       return 0;
936     }
937
938   vec_validate (om->ctx_pool, num_threads - 1);
939
940   tls_register_engine (&openssl_engine, CRYPTO_ENGINE_OPENSSL);
941
942   om->engine_init = 0;
943
944   /* default ciphers */
945   tls_openssl_set_ciphers
946     ("ALL:!ADH:!LOW:!EXP:!MD5:!RC4-SHA:!DES-CBC3-SHA:@STRENGTH");
947
948   return error;
949 }
950 /* *INDENT-OFF* */
951 VLIB_INIT_FUNCTION (tls_openssl_init) =
952 {
953   .runs_after = VLIB_INITS("tls_init"),
954 };
955 /* *INDENT-ON* */
956
957 #ifdef HAVE_OPENSSL_ASYNC
958 static clib_error_t *
959 tls_openssl_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
960                             vlib_cli_command_t * cmd)
961 {
962   openssl_main_t *om = &openssl_main;
963   char *engine_name = NULL;
964   char *engine_alg = NULL;
965   char *ciphers = NULL;
966   u8 engine_name_set = 0;
967   int i, async = 0;
968
969   /* By present, it is not allowed to configure engine again after running */
970   if (om->engine_init)
971     {
972       clib_warning ("engine has started!\n");
973       return clib_error_return
974         (0, "engine has started, and no config is accepted");
975     }
976
977   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
978     {
979       if (unformat (input, "engine %s", &engine_name))
980         {
981           engine_name_set = 1;
982         }
983       else if (unformat (input, "async"))
984         {
985           async = 1;
986         }
987       else if (unformat (input, "alg %s", &engine_alg))
988         {
989           for (i = 0; i < strnlen (engine_alg, MAX_CRYPTO_LEN); i++)
990             engine_alg[i] = toupper (engine_alg[i]);
991         }
992       else if (unformat (input, "ciphers %s", &ciphers))
993         {
994           tls_openssl_set_ciphers (ciphers);
995         }
996       else
997         return clib_error_return (0, "failed: unknown input `%U'",
998                                   format_unformat_error, input);
999     }
1000
1001   /* reset parameters if engine is not configured */
1002   if (!engine_name_set)
1003     {
1004       clib_warning ("No engine provided! \n");
1005       async = 0;
1006     }
1007   else
1008     {
1009       vnet_session_enable_disable (vm, 1);
1010       if (openssl_engine_register (engine_name, engine_alg, async) < 0)
1011         {
1012           return clib_error_return (0, "Failed to register %s polling",
1013                                     engine_name);
1014         }
1015       else
1016         {
1017           vlib_cli_output (vm, "Successfully register engine %s\n",
1018                            engine_name);
1019         }
1020     }
1021   om->async = async;
1022
1023   return 0;
1024 }
1025
1026 /* *INDENT-OFF* */
1027 VLIB_CLI_COMMAND (tls_openssl_set_command, static) =
1028 {
1029   .path = "tls openssl set",
1030   .short_help = "tls openssl set [engine <engine name>] [alg [algorithm] [async]",
1031   .function = tls_openssl_set_command_fn,
1032 };
1033 /* *INDENT-ON* */
1034 #endif
1035
1036 /* *INDENT-OFF* */
1037 VLIB_PLUGIN_REGISTER () = {
1038     .version = VPP_BUILD_VER,
1039     .description = "Transport Layer Security (TLS) Engine, OpenSSL Based",
1040 };
1041 /* *INDENT-ON* */
1042
1043 /*
1044  * fd.io coding-style-patch-verification: ON
1045  *
1046  * Local Variables:
1047  * eval: (c-set-style "gnu")
1048  * End:
1049  */