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