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