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