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