tls: fix bulk bio read/write
[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, /* is failed */ 1);
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, /* is failed */ 0);
389               return -1;
390             }
391         }
392       tls_notify_app_connected (ctx, /* is failed */ 0);
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)
417 {
418   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
419   int wrote = 0, read, max_buf = 100 * 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   /* Figure out how much data to write */
431   max_space = max_buf - BIO_ctrl_pending (oc->rbio);
432   max_space = (max_space < 0) ? 0 : max_space;
433   to_write = clib_min (deq_max, (u32) max_space);
434
435   wrote = openssl_write_from_fifo_into_ssl (f, oc->ssl, to_write);
436   if (!wrote)
437     {
438       tls_add_vpp_q_builtin_tx_evt (app_session);
439       goto check_tls_fifo;
440     }
441
442   if (svm_fifo_needs_deq_ntf (f, wrote))
443     session_dequeue_notify (app_session);
444
445   if (svm_fifo_max_dequeue_cons (f))
446     tls_add_vpp_q_builtin_tx_evt (app_session);
447
448 check_tls_fifo:
449
450   if (BIO_ctrl_pending (oc->rbio) <= 0)
451     return wrote;
452
453   tls_session = session_get_from_handle (ctx->tls_session_handle);
454
455   read = openssl_read_from_bio_into_fifo (tls_session->tx_fifo, oc->rbio);
456   if (!read)
457     {
458       tls_add_vpp_q_builtin_tx_evt (app_session);
459       return wrote;
460     }
461
462   tls_add_vpp_q_tx_evt (tls_session);
463
464   if (BIO_ctrl_pending (oc->rbio) > 0)
465     tls_add_vpp_q_builtin_tx_evt (app_session);
466   else if (ctx->app_closed)
467     openssl_confirm_app_close (ctx);
468
469   return wrote;
470 }
471
472 static inline int
473 openssl_ctx_read (tls_ctx_t * ctx, session_t * tls_session)
474 {
475   int read, wrote = 0, max_space, max_buf = 100 * TLS_CHUNK_SIZE;
476   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
477   u32 deq_max, to_write;
478   session_t *app_session;
479   svm_fifo_t *f;
480
481   if (PREDICT_FALSE (SSL_in_init (oc->ssl)))
482     {
483       if (openssl_ctx_handshake_rx (ctx, tls_session) < 0)
484         return 0;
485       else
486         goto check_app_fifo;
487     }
488
489   f = tls_session->rx_fifo;
490
491   deq_max = svm_fifo_max_dequeue_cons (f);
492   max_space = max_buf - BIO_ctrl_pending (oc->wbio);
493   max_space = max_space < 0 ? 0 : max_space;
494   to_write = clib_min (deq_max, max_space);
495   if (!to_write)
496     goto check_app_fifo;
497
498   wrote = openssl_write_from_fifo_into_bio (f, oc->wbio, to_write);
499   if (!wrote)
500     {
501       tls_add_vpp_q_builtin_rx_evt (tls_session);
502       goto check_app_fifo;
503     }
504
505   if (svm_fifo_max_dequeue_cons (f))
506     tls_add_vpp_q_builtin_rx_evt (tls_session);
507
508 check_app_fifo:
509
510   if (BIO_ctrl_pending (oc->wbio) <= 0)
511     return wrote;
512
513   app_session = session_get_from_handle (ctx->app_session_handle);
514   f = app_session->rx_fifo;
515
516   read = openssl_read_from_ssl_into_fifo (f, oc->ssl);
517   if (!read)
518     {
519       tls_add_vpp_q_builtin_rx_evt (tls_session);
520       return wrote;
521     }
522
523   /* If handshake just completed, session may still be in accepting state */
524   if (app_session->session_state >= SESSION_STATE_READY)
525     tls_notify_app_enqueue (ctx, app_session);
526   if (SSL_pending (oc->ssl) > 0)
527     tls_add_vpp_q_builtin_rx_evt (tls_session);
528
529   return wrote;
530 }
531
532 static int
533 openssl_ctx_init_client (tls_ctx_t * ctx)
534 {
535   long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
536   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
537   openssl_main_t *om = &openssl_main;
538   session_t *tls_session;
539   const SSL_METHOD *method;
540   int rv, err;
541
542   method = SSLv23_client_method ();
543   if (method == NULL)
544     {
545       TLS_DBG (1, "SSLv23_method returned null");
546       return -1;
547     }
548
549   oc->ssl_ctx = SSL_CTX_new (method);
550   if (oc->ssl_ctx == NULL)
551     {
552       TLS_DBG (1, "SSL_CTX_new returned null");
553       return -1;
554     }
555
556   SSL_CTX_set_ecdh_auto (oc->ssl_ctx, 1);
557   SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
558 #ifdef HAVE_OPENSSL_ASYNC
559   if (om->async)
560     SSL_CTX_set_mode (oc->ssl_ctx, SSL_MODE_ASYNC);
561 #endif
562   rv = SSL_CTX_set_cipher_list (oc->ssl_ctx, (const char *) om->ciphers);
563   if (rv != 1)
564     {
565       TLS_DBG (1, "Couldn't set cipher");
566       return -1;
567     }
568
569   SSL_CTX_set_options (oc->ssl_ctx, flags);
570   SSL_CTX_set_cert_store (oc->ssl_ctx, om->cert_store);
571
572   oc->ssl = SSL_new (oc->ssl_ctx);
573   if (oc->ssl == NULL)
574     {
575       TLS_DBG (1, "Couldn't initialize ssl struct");
576       return -1;
577     }
578
579   oc->rbio = BIO_new (BIO_s_mem ());
580   oc->wbio = BIO_new (BIO_s_mem ());
581
582   BIO_set_mem_eof_return (oc->rbio, -1);
583   BIO_set_mem_eof_return (oc->wbio, -1);
584
585   SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
586   SSL_set_connect_state (oc->ssl);
587
588   rv = SSL_set_tlsext_host_name (oc->ssl, ctx->srv_hostname);
589   if (rv != 1)
590     {
591       TLS_DBG (1, "Couldn't set hostname");
592       return -1;
593     }
594
595   /*
596    * 2. Do the first steps in the handshake.
597    */
598   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
599            oc->openssl_ctx_index);
600
601   tls_session = session_get_from_handle (ctx->tls_session_handle);
602
603 #ifdef HAVE_OPENSSL_ASYNC
604   vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
605 #endif
606   while (1)
607     {
608       rv = SSL_do_handshake (oc->ssl);
609       err = SSL_get_error (oc->ssl, rv);
610       openssl_try_handshake_write (oc, tls_session);
611 #ifdef HAVE_OPENSSL_ASYNC
612       if (err == SSL_ERROR_WANT_ASYNC)
613         {
614           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
615                                       tls_session);
616           break;
617         }
618 #endif
619       if (err != SSL_ERROR_WANT_WRITE)
620         break;
621     }
622
623   TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
624            oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
625   return 0;
626 }
627
628 static int
629 openssl_start_listen (tls_ctx_t * lctx)
630 {
631   const SSL_METHOD *method;
632   SSL_CTX *ssl_ctx;
633   int rv;
634   BIO *cert_bio;
635   X509 *srvcert;
636   EVP_PKEY *pkey;
637   u32 olc_index;
638   openssl_listen_ctx_t *olc;
639   app_cert_key_pair_t *ckpair;
640
641   long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
642   openssl_main_t *om = &openssl_main;
643
644   ckpair = app_cert_key_pair_get_if_valid (lctx->ckpair_index);
645   if (!ckpair)
646     return -1;
647
648   if (!ckpair->cert || !ckpair->key)
649     {
650       TLS_DBG (1, "tls cert and/or key not configured %d",
651                lctx->parent_app_wrk_index);
652       return -1;
653     }
654
655   method = SSLv23_method ();
656   ssl_ctx = SSL_CTX_new (method);
657   if (!ssl_ctx)
658     {
659       clib_warning ("Unable to create SSL context");
660       return -1;
661     }
662
663   SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
664 #ifdef HAVE_OPENSSL_ASYNC
665   if (om->async)
666     {
667       SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ASYNC);
668       SSL_CTX_set_async_callback (ssl_ctx, tls_async_openssl_callback);
669     }
670 #endif
671   SSL_CTX_set_options (ssl_ctx, flags);
672   SSL_CTX_set_ecdh_auto (ssl_ctx, 1);
673
674   rv = SSL_CTX_set_cipher_list (ssl_ctx, (const char *) om->ciphers);
675   if (rv != 1)
676     {
677       TLS_DBG (1, "Couldn't set cipher");
678       return -1;
679     }
680
681   /*
682    * Set the key and cert
683    */
684   cert_bio = BIO_new (BIO_s_mem ());
685   BIO_write (cert_bio, ckpair->cert, vec_len (ckpair->cert));
686   srvcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
687   if (!srvcert)
688     {
689       clib_warning ("unable to parse certificate");
690       return -1;
691     }
692   SSL_CTX_use_certificate (ssl_ctx, srvcert);
693   BIO_free (cert_bio);
694
695   cert_bio = BIO_new (BIO_s_mem ());
696   BIO_write (cert_bio, ckpair->key, vec_len (ckpair->key));
697   pkey = PEM_read_bio_PrivateKey (cert_bio, NULL, NULL, NULL);
698   if (!pkey)
699     {
700       clib_warning ("unable to parse pkey");
701       return -1;
702     }
703   SSL_CTX_use_PrivateKey (ssl_ctx, pkey);
704   BIO_free (cert_bio);
705
706   olc_index = openssl_listen_ctx_alloc ();
707   olc = openssl_lctx_get (olc_index);
708   olc->ssl_ctx = ssl_ctx;
709   olc->srvcert = srvcert;
710   olc->pkey = pkey;
711
712   /* store SSL_CTX into TLS level structure */
713   lctx->tls_ssl_ctx = olc_index;
714
715   return 0;
716
717 }
718
719 static int
720 openssl_stop_listen (tls_ctx_t * lctx)
721 {
722   u32 olc_index;
723   openssl_listen_ctx_t *olc;
724
725   olc_index = lctx->tls_ssl_ctx;
726   olc = openssl_lctx_get (olc_index);
727
728   X509_free (olc->srvcert);
729   EVP_PKEY_free (olc->pkey);
730
731   SSL_CTX_free (olc->ssl_ctx);
732   openssl_listen_ctx_free (olc);
733
734   return 0;
735 }
736
737 static int
738 openssl_ctx_init_server (tls_ctx_t * ctx)
739 {
740   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
741   u32 olc_index = ctx->tls_ssl_ctx;
742   openssl_listen_ctx_t *olc;
743   session_t *tls_session;
744   int rv, err;
745
746   /* Start a new connection */
747
748   olc = openssl_lctx_get (olc_index);
749   oc->ssl = SSL_new (olc->ssl_ctx);
750   if (oc->ssl == NULL)
751     {
752       TLS_DBG (1, "Couldn't initialize ssl struct");
753       return -1;
754     }
755
756   oc->rbio = BIO_new (BIO_s_mem ());
757   oc->wbio = BIO_new (BIO_s_mem ());
758
759   BIO_set_mem_eof_return (oc->rbio, -1);
760   BIO_set_mem_eof_return (oc->wbio, -1);
761
762   SSL_set_bio (oc->ssl, oc->wbio, oc->rbio);
763   SSL_set_accept_state (oc->ssl);
764
765   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
766            oc->openssl_ctx_index);
767
768   tls_session = session_get_from_handle (ctx->tls_session_handle);
769 #ifdef HAVE_OPENSSL_ASYNC
770   vpp_tls_async_init_event (ctx, openssl_ctx_handshake_rx, tls_session);
771 #endif
772   while (1)
773     {
774       rv = SSL_do_handshake (oc->ssl);
775       err = SSL_get_error (oc->ssl, rv);
776       openssl_try_handshake_write (oc, tls_session);
777 #ifdef HAVE_OPENSSL_ASYNC
778       if (err == SSL_ERROR_WANT_ASYNC)
779         {
780           openssl_check_async_status (ctx, openssl_ctx_handshake_rx,
781                                       tls_session);
782           break;
783         }
784 #endif
785       if (err != SSL_ERROR_WANT_WRITE)
786         break;
787     }
788
789   TLS_DBG (2, "tls state for [%u]%u is su", ctx->c_thread_index,
790            oc->openssl_ctx_index, SSL_state_string_long (oc->ssl));
791   return 0;
792 }
793
794 static u8
795 openssl_handshake_is_over (tls_ctx_t * ctx)
796 {
797   openssl_ctx_t *mc = (openssl_ctx_t *) ctx;
798   if (!mc->ssl)
799     return 0;
800   return SSL_is_init_finished (mc->ssl);
801 }
802
803 static int
804 openssl_transport_close (tls_ctx_t * ctx)
805 {
806 #ifdef HAVE_OPENSSL_ASYNC
807   if (vpp_openssl_is_inflight (ctx))
808     return 0;
809 #endif
810
811   if (!openssl_handshake_is_over (ctx))
812     {
813       openssl_handle_handshake_failure (ctx);
814       return 0;
815     }
816   session_transport_closing_notify (&ctx->connection);
817   return 0;
818 }
819
820 static int
821 openssl_app_close (tls_ctx_t * ctx)
822 {
823   openssl_ctx_t *oc = (openssl_ctx_t *) ctx;
824   session_t *app_session;
825
826   /* Wait for all data to be written to tcp */
827   app_session = session_get_from_handle (ctx->app_session_handle);
828   if (BIO_ctrl_pending (oc->rbio) <= 0
829       && !svm_fifo_max_dequeue_cons (app_session->tx_fifo))
830     openssl_confirm_app_close (ctx);
831   else
832     ctx->app_closed = 1;
833   return 0;
834 }
835
836 const static tls_engine_vft_t openssl_engine = {
837   .ctx_alloc = openssl_ctx_alloc,
838   .ctx_free = openssl_ctx_free,
839   .ctx_get = openssl_ctx_get,
840   .ctx_get_w_thread = openssl_ctx_get_w_thread,
841   .ctx_init_server = openssl_ctx_init_server,
842   .ctx_init_client = openssl_ctx_init_client,
843   .ctx_write = openssl_ctx_write,
844   .ctx_read = openssl_ctx_read,
845   .ctx_handshake_is_over = openssl_handshake_is_over,
846   .ctx_start_listen = openssl_start_listen,
847   .ctx_stop_listen = openssl_stop_listen,
848   .ctx_transport_close = openssl_transport_close,
849   .ctx_app_close = openssl_app_close,
850 };
851
852 int
853 tls_init_ca_chain (void)
854 {
855   openssl_main_t *om = &openssl_main;
856   tls_main_t *tm = vnet_tls_get_main ();
857   BIO *cert_bio;
858   X509 *testcert;
859   int rv;
860
861   if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
862     {
863       clib_warning ("Could not initialize TLS CA certificates");
864       return -1;
865     }
866
867   if (!(om->cert_store = X509_STORE_new ()))
868     {
869       clib_warning ("failed to create cert store");
870       return -1;
871     }
872
873 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
874   rv = X509_STORE_load_file (om->cert_store, tm->ca_cert_path);
875 #else
876   rv = X509_STORE_load_locations (om->cert_store, tm->ca_cert_path, 0);
877 #endif
878
879   if (rv < 0)
880     {
881       clib_warning ("failed to load ca certificate");
882     }
883
884   if (tm->use_test_cert_in_ca)
885     {
886       cert_bio = BIO_new (BIO_s_mem ());
887       BIO_write (cert_bio, test_srv_crt_rsa, test_srv_crt_rsa_len);
888       testcert = PEM_read_bio_X509 (cert_bio, NULL, NULL, NULL);
889       if (!testcert)
890         {
891           clib_warning ("unable to parse certificate");
892           return -1;
893         }
894       X509_STORE_add_cert (om->cert_store, testcert);
895       rv = 0;
896     }
897   return (rv < 0 ? -1 : 0);
898 }
899
900 int
901 tls_openssl_set_ciphers (char *ciphers)
902 {
903   openssl_main_t *om = &openssl_main;
904   int i;
905
906   if (!ciphers)
907     {
908       return -1;
909     }
910
911   vec_validate (om->ciphers, strlen (ciphers) - 1);
912   for (i = 0; i < vec_len (om->ciphers); i++)
913     {
914       om->ciphers[i] = toupper (ciphers[i]);
915     }
916
917   return 0;
918
919 }
920
921 static clib_error_t *
922 tls_openssl_init (vlib_main_t * vm)
923 {
924   vlib_thread_main_t *vtm = vlib_get_thread_main ();
925   openssl_main_t *om = &openssl_main;
926   clib_error_t *error = 0;
927   u32 num_threads;
928
929   error = tls_openssl_api_init (vm);
930   num_threads = 1 /* main thread */  + vtm->n_threads;
931
932   SSL_library_init ();
933   SSL_load_error_strings ();
934
935   if (tls_init_ca_chain ())
936     {
937       clib_warning ("failed to initialize TLS CA chain");
938       return 0;
939     }
940
941   vec_validate (om->ctx_pool, num_threads - 1);
942
943   tls_register_engine (&openssl_engine, CRYPTO_ENGINE_OPENSSL);
944
945   om->engine_init = 0;
946
947   /* default ciphers */
948   tls_openssl_set_ciphers
949     ("ALL:!ADH:!LOW:!EXP:!MD5:!RC4-SHA:!DES-CBC3-SHA:@STRENGTH");
950
951   return error;
952 }
953 /* *INDENT-OFF* */
954 VLIB_INIT_FUNCTION (tls_openssl_init) =
955 {
956   .runs_after = VLIB_INITS("tls_init"),
957 };
958 /* *INDENT-ON* */
959
960 #ifdef HAVE_OPENSSL_ASYNC
961 static clib_error_t *
962 tls_openssl_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
963                             vlib_cli_command_t * cmd)
964 {
965   openssl_main_t *om = &openssl_main;
966   char *engine_name = NULL;
967   char *engine_alg = NULL;
968   char *ciphers = NULL;
969   u8 engine_name_set = 0;
970   int i, async = 0;
971
972   /* By present, it is not allowed to configure engine again after running */
973   if (om->engine_init)
974     {
975       clib_warning ("engine has started!\n");
976       return clib_error_return
977         (0, "engine has started, and no config is accepted");
978     }
979
980   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
981     {
982       if (unformat (input, "engine %s", &engine_name))
983         {
984           engine_name_set = 1;
985         }
986       else if (unformat (input, "async"))
987         {
988           async = 1;
989         }
990       else if (unformat (input, "alg %s", &engine_alg))
991         {
992           for (i = 0; i < strnlen (engine_alg, MAX_CRYPTO_LEN); i++)
993             engine_alg[i] = toupper (engine_alg[i]);
994         }
995       else if (unformat (input, "ciphers %s", &ciphers))
996         {
997           tls_openssl_set_ciphers (ciphers);
998         }
999       else
1000         return clib_error_return (0, "failed: unknown input `%U'",
1001                                   format_unformat_error, input);
1002     }
1003
1004   /* reset parameters if engine is not configured */
1005   if (!engine_name_set)
1006     {
1007       clib_warning ("No engine provided! \n");
1008       async = 0;
1009     }
1010   else
1011     {
1012       vnet_session_enable_disable (vm, 1);
1013       if (openssl_engine_register (engine_name, engine_alg, async) < 0)
1014         {
1015           return clib_error_return (0, "Failed to register %s polling",
1016                                     engine_name);
1017         }
1018       else
1019         {
1020           vlib_cli_output (vm, "Successfully register engine %s\n",
1021                            engine_name);
1022         }
1023     }
1024   om->async = async;
1025
1026   return 0;
1027 }
1028
1029 /* *INDENT-OFF* */
1030 VLIB_CLI_COMMAND (tls_openssl_set_command, static) =
1031 {
1032   .path = "tls openssl set",
1033   .short_help = "tls openssl set [engine <engine name>] [alg [algorithm] [async]",
1034   .function = tls_openssl_set_command_fn,
1035 };
1036 /* *INDENT-ON* */
1037 #endif
1038
1039 /* *INDENT-OFF* */
1040 VLIB_PLUGIN_REGISTER () = {
1041     .version = VPP_BUILD_VER,
1042     .description = "Transport Layer Security (TLS) Engine, OpenSSL Based",
1043 };
1044 /* *INDENT-ON* */
1045
1046 /*
1047  * fd.io coding-style-patch-verification: ON
1048  *
1049  * Local Variables:
1050  * eval: (c-set-style "gnu")
1051  * End:
1052  */