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