tls: enforce certificate verification
[vpp.git] / src / vnet / session-apps / tls.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 <vnet/session/application_interface.h>
17 #include <vppinfra/lock.h>
18 #include <mbedtls/ssl.h>
19 #include <mbedtls/certs.h>
20 #include <mbedtls/entropy.h>
21 #include <mbedtls/ctr_drbg.h>
22 #include <mbedtls/timing.h>
23 #include <mbedtls/debug.h>
24
25 #define TLS_DEBUG               0
26 #define TLS_DEBUG_LEVEL_CLIENT  0
27 #define TLS_DEBUG_LEVEL_SERVER  0
28
29 #define TLS_CHUNK_SIZE          (1 << 14)
30 #define TLS_USE_OUR_MEM_FUNCS   0
31 #define TLS_CA_CERT_PATH        "/etc/ssl/certs/ca-certificates.crt"
32
33 #if TLS_DEBUG
34 #define TLS_DBG(_lvl, _fmt, _args...)                   \
35   if (_lvl <= TLS_DEBUG)                                \
36     clib_warning (_fmt, ##_args)
37 #else
38 #define TLS_DBG(_fmt, _args...)
39 #endif
40
41 #if TLS_USE_OUR_MEM_FUNCS
42 #include <mbedtls/platform.h>
43
44 void *
45 mbedtls_calloc_fn (size_t n, size_t size)
46 {
47   void *ptr;
48   ptr = clib_mem_alloc (n * size);
49   memset (ptr, 0, sizeof (*ptr));
50   return ptr;
51 }
52
53 void
54 mbedtls_free_fn (void *ptr)
55 {
56   if (ptr)
57     clib_mem_free (ptr);
58 }
59 #endif
60
61 /* *INDENT-OFF* */
62 typedef CLIB_PACKED (struct tls_cxt_id_
63 {
64   u32 parent_app_index;
65   session_handle_t app_session_handle;
66   session_handle_t tls_session_handle;
67   u32 listener_ctx_index;
68   u8 tcp_is_ip4;
69 }) tls_ctx_id_t;
70 /* *INDENT-ON* */
71
72 STATIC_ASSERT (sizeof (tls_ctx_id_t) <= 42, "ctx id must be less than 42");
73
74 typedef struct tls_ctx_
75 {
76   union
77   {
78     transport_connection_t connection;
79     tls_ctx_id_t c_tls_ctx_id;
80   };
81 #define parent_app_index c_tls_ctx_id.parent_app_index
82 #define app_session_handle c_tls_ctx_id.app_session_handle
83 #define tls_session_handle c_tls_ctx_id.tls_session_handle
84 #define listener_ctx_index c_tls_ctx_id.listener_ctx_index
85 #define tcp_is_ip4 c_tls_ctx_id.tcp_is_ip4
86 #define tls_ctx_idx c_c_index
87   /* Temporary storage for session open opaque. Overwritten once
88    * underlying tcp connection is established */
89 #define parent_app_api_context c_s_index
90
91   u8 is_passive_close;
92   u8 *srv_hostname;
93   mbedtls_ssl_context ssl;
94   mbedtls_ssl_config conf;
95   mbedtls_x509_crt srvcert;
96   mbedtls_pk_context pkey;
97 } tls_ctx_t;
98
99 typedef struct tls_main_
100 {
101   u32 app_index;
102   tls_ctx_t ***ctx_pool;
103   mbedtls_ctr_drbg_context *ctr_drbgs;
104   mbedtls_entropy_context *entropy_pools;
105   tls_ctx_t *listener_ctx_pool;
106   tls_ctx_t *half_open_ctx_pool;
107   clib_rwlock_t half_open_rwlock;
108   mbedtls_x509_crt cacert;
109
110   /*
111    * Config
112    */
113   u8 use_test_cert_in_ca;
114   char *ca_cert_path;
115 } tls_main_t;
116
117 static tls_main_t tls_main;
118
119 void tls_disconnect (u32 ctx_index, u32 thread_index);
120
121 static inline int
122 tls_add_vpp_q_evt (svm_fifo_t * f, u8 evt_type)
123 {
124   session_fifo_event_t evt;
125   svm_queue_t *q;
126
127   if (svm_fifo_set_event (f))
128     {
129       evt.fifo = f;
130       evt.event_type = evt_type;
131
132       q = session_manager_get_vpp_event_queue (f->master_thread_index);
133       if (PREDICT_TRUE (q->cursize < q->maxsize))
134         {
135           svm_queue_add (q, (u8 *) & evt, 0 /* do wait for mutex */ );
136         }
137       else
138         {
139           clib_warning ("vpp's evt q full");
140           return -1;
141         }
142     }
143   return 0;
144 }
145
146 static inline int
147 tls_add_app_q_evt (application_t * app, stream_session_t * app_session)
148 {
149   session_fifo_event_t evt;
150   svm_queue_t *q;
151
152   if (PREDICT_FALSE (app_session->session_state == SESSION_STATE_CLOSED))
153     {
154       /* Session is closed so app will never clean up. Flush rx fifo */
155       u32 to_dequeue = svm_fifo_max_dequeue (app_session->server_rx_fifo);
156       if (to_dequeue)
157         svm_fifo_dequeue_drop (app_session->server_rx_fifo, to_dequeue);
158       return 0;
159     }
160
161   if (app->cb_fns.builtin_app_rx_callback)
162     return app->cb_fns.builtin_app_rx_callback (app_session);
163
164   if (svm_fifo_set_event (app_session->server_rx_fifo))
165     {
166       evt.fifo = app_session->server_rx_fifo;
167       evt.event_type = FIFO_EVENT_APP_RX;
168       q = app->event_queue;
169
170       if (PREDICT_TRUE (q->cursize < q->maxsize))
171         {
172           svm_queue_add (q, (u8 *) & evt, 0 /* do wait for mutex */ );
173         }
174       else
175         {
176           clib_warning ("app evt q full");
177           return -1;
178         }
179     }
180   return 0;
181 }
182
183 u32
184 tls_ctx_alloc (void)
185 {
186   u8 thread_index = vlib_get_thread_index ();
187   tls_main_t *tm = &tls_main;
188   tls_ctx_t **ctx;
189
190   pool_get (tm->ctx_pool[thread_index], ctx);
191   if (!(*ctx))
192     *ctx = clib_mem_alloc (sizeof (tls_ctx_t));
193
194   memset (*ctx, 0, sizeof (tls_ctx_t));
195   (*ctx)->c_thread_index = thread_index;
196   return ctx - tm->ctx_pool[thread_index];
197 }
198
199 void
200 tls_ctx_free (tls_ctx_t * ctx)
201 {
202   vec_free (ctx->srv_hostname);
203   pool_put_index (tls_main.ctx_pool[vlib_get_thread_index ()],
204                   ctx->tls_ctx_idx);
205 }
206
207 tls_ctx_t *
208 tls_ctx_get (u32 ctx_index)
209 {
210   tls_ctx_t **ctx;
211   ctx = pool_elt_at_index (tls_main.ctx_pool[vlib_get_thread_index ()],
212                            ctx_index);
213   return (*ctx);
214 }
215
216 tls_ctx_t *
217 tls_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
218 {
219   tls_ctx_t **ctx;
220   ctx = pool_elt_at_index (tls_main.ctx_pool[thread_index], ctx_index);
221   return (*ctx);
222 }
223
224 u32
225 tls_listener_ctx_alloc (void)
226 {
227   tls_main_t *tm = &tls_main;
228   tls_ctx_t *ctx;
229
230   pool_get (tm->listener_ctx_pool, ctx);
231   memset (ctx, 0, sizeof (*ctx));
232   return ctx - tm->listener_ctx_pool;
233 }
234
235 void
236 tls_listener_ctx_free (tls_ctx_t * ctx)
237 {
238   pool_put (tls_main.listener_ctx_pool, ctx);
239 }
240
241 tls_ctx_t *
242 tls_listener_ctx_get (u32 ctx_index)
243 {
244   return pool_elt_at_index (tls_main.listener_ctx_pool, ctx_index);
245 }
246
247 u32
248 tls_listener_ctx_index (tls_ctx_t * ctx)
249 {
250   return (ctx - tls_main.listener_ctx_pool);
251 }
252
253 u32
254 tls_ctx_half_open_alloc (void)
255 {
256   tls_main_t *tm = &tls_main;
257   u8 will_expand = 0;
258   tls_ctx_t *ctx;
259   u32 ctx_index;
260
261   pool_get_aligned_will_expand (tm->half_open_ctx_pool, will_expand, 0);
262   if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
263     {
264       clib_rwlock_writer_lock (&tm->half_open_rwlock);
265       pool_get (tm->half_open_ctx_pool, ctx);
266       memset (ctx, 0, sizeof (*ctx));
267       ctx_index = ctx - tm->half_open_ctx_pool;
268       clib_rwlock_writer_unlock (&tm->half_open_rwlock);
269     }
270   else
271     {
272       pool_get (tm->half_open_ctx_pool, ctx);
273       memset (ctx, 0, sizeof (*ctx));
274       ctx_index = ctx - tm->half_open_ctx_pool;
275     }
276   return ctx_index;
277 }
278
279 void
280 tls_ctx_half_open_free (u32 ho_index)
281 {
282   tls_main_t *tm = &tls_main;
283   clib_rwlock_writer_lock (&tm->half_open_rwlock);
284   pool_put_index (tls_main.half_open_ctx_pool, ho_index);
285   clib_rwlock_writer_unlock (&tm->half_open_rwlock);
286 }
287
288 tls_ctx_t *
289 tls_ctx_half_open_get (u32 ctx_index)
290 {
291   tls_main_t *tm = &tls_main;
292   clib_rwlock_reader_lock (&tm->half_open_rwlock);
293   return pool_elt_at_index (tm->half_open_ctx_pool, ctx_index);
294 }
295
296 void
297 tls_ctx_half_open_reader_unlock ()
298 {
299   clib_rwlock_reader_unlock (&tls_main.half_open_rwlock);
300 }
301
302 u32
303 tls_ctx_half_open_index (tls_ctx_t * ctx)
304 {
305   return (ctx - tls_main.half_open_ctx_pool);
306 }
307
308 static int
309 tls_init_ctr_drbgs_and_entropy (u32 num_threads)
310 {
311   tls_main_t *tm = &tls_main;
312   int i;
313
314   vec_validate (tm->ctr_drbgs, num_threads - 1);
315   vec_validate (tm->entropy_pools, num_threads - 1);
316   for (i = 0; i < num_threads; i++)
317     tls_main.ctr_drbgs[i].f_entropy = 0;
318
319   return 0;
320 }
321
322 static int
323 tls_init_ctr_seed_drbgs (void)
324 {
325   u32 thread_index = vlib_get_thread_index ();
326   tls_main_t *tm = &tls_main;
327   u8 *pers;
328   int rv;
329   pers = format (0, "vpp thread %u", thread_index);
330
331   mbedtls_entropy_init (&tm->entropy_pools[thread_index]);
332   mbedtls_ctr_drbg_init (&tls_main.ctr_drbgs[thread_index]);
333   if ((rv = mbedtls_ctr_drbg_seed (&tm->ctr_drbgs[thread_index],
334                                    mbedtls_entropy_func,
335                                    &tm->entropy_pools[thread_index],
336                                    (const unsigned char *) pers,
337                                    vec_len (pers))) != 0)
338     {
339       vec_free (pers);
340       TLS_DBG (1, " failed\n  ! mbedtls_ctr_drbg_seed returned %d\n", rv);
341       return -1;
342     }
343   vec_free (pers);
344   return 0;
345 }
346
347 mbedtls_ctr_drbg_context *
348 tls_get_ctr_drbg ()
349 {
350   u8 thread_index = vlib_get_thread_index ();
351   if (PREDICT_FALSE (!tls_main.ctr_drbgs[thread_index].f_entropy))
352     tls_init_ctr_seed_drbgs ();
353   return &tls_main.ctr_drbgs[thread_index];
354 }
355
356 static int
357 tls_net_send (void *ctx_indexp, const unsigned char *buf, size_t len)
358 {
359   stream_session_t *tls_session;
360   uword ctx_index;
361   tls_ctx_t *ctx;
362   int rv;
363
364   ctx_index = pointer_to_uword (ctx_indexp);
365   ctx = tls_ctx_get (ctx_index);
366   tls_session = session_get_from_handle (ctx->tls_session_handle);
367   rv = svm_fifo_enqueue_nowait (tls_session->server_tx_fifo, len, buf);
368   if (rv < 0)
369     return MBEDTLS_ERR_SSL_WANT_WRITE;
370   tls_add_vpp_q_evt (tls_session->server_tx_fifo, FIFO_EVENT_APP_TX);
371   return rv;
372 }
373
374 static int
375 tls_net_recv (void *ctx_indexp, unsigned char *buf, size_t len)
376 {
377   stream_session_t *tls_session;
378   uword ctx_index;
379   tls_ctx_t *ctx;
380   int rv;
381
382   ctx_index = pointer_to_uword (ctx_indexp);
383   ctx = tls_ctx_get (ctx_index);
384   tls_session = session_get_from_handle (ctx->tls_session_handle);
385   rv = svm_fifo_dequeue_nowait (tls_session->server_rx_fifo, len, buf);
386   return (rv < 0) ? 0 : rv;
387 }
388
389 static void
390 mbedtls_debug (void *ctx, int level, const char *file, int line,
391                const char *str)
392 {
393   ((void) level);
394   fprintf ((FILE *) ctx, "%s:%04d: %s", file, line, str);
395   fflush ((FILE *) ctx);
396 }
397
398 static int
399 tls_ctx_init_client (tls_ctx_t * ctx)
400 {
401   tls_main_t *tm = &tls_main;
402   void *ctx_ptr;
403   int rv;
404
405   /*
406    * 1. Setup SSL
407    */
408   mbedtls_ssl_init (&ctx->ssl);
409   mbedtls_ssl_config_init (&ctx->conf);
410   if ((rv = mbedtls_ssl_config_defaults (&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
411                                          MBEDTLS_SSL_TRANSPORT_STREAM,
412                                          MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
413     {
414       TLS_DBG (1, "failed\n  ! mbedtls_ssl_config_defaults returned %d\n\n",
415                rv);
416       return -1;
417     }
418
419   mbedtls_ssl_conf_authmode (&ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
420   mbedtls_ssl_conf_ca_chain (&ctx->conf, &tm->cacert, NULL);
421   mbedtls_ssl_conf_rng (&ctx->conf, mbedtls_ctr_drbg_random,
422                         tls_get_ctr_drbg ());
423   mbedtls_ssl_conf_dbg (&ctx->conf, mbedtls_debug, stdout);
424
425   if ((rv = mbedtls_ssl_setup (&ctx->ssl, &ctx->conf)) != 0)
426     {
427       TLS_DBG (1, "failed\n  ! mbedtls_ssl_setup returned %d\n", rv);
428       return -1;
429     }
430
431   if ((rv = mbedtls_ssl_set_hostname (&ctx->ssl,
432                                       (const char *) ctx->srv_hostname)) != 0)
433     {
434       TLS_DBG (1, "failed\n  ! mbedtls_ssl_set_hostname returned %d\n", rv);
435       return -1;
436     }
437
438   ctx_ptr = uword_to_pointer (ctx->tls_ctx_idx, void *);
439   mbedtls_ssl_set_bio (&ctx->ssl, ctx_ptr, tls_net_send, tls_net_recv, NULL);
440   mbedtls_debug_set_threshold (TLS_DEBUG_LEVEL_CLIENT);
441
442   /*
443    * 2. Do the first 2 steps in the handshake.
444    */
445   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
446            ctx->tls_ctx_idx);
447   while (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
448     {
449       rv = mbedtls_ssl_handshake_step (&ctx->ssl);
450       if (rv != 0)
451         break;
452     }
453   TLS_DBG (2, "tls state for [%u]%u is %u", ctx->c_thread_index,
454            ctx->tls_ctx_idx, ctx->ssl.state);
455   return 0;
456 }
457
458 static int
459 tls_ctx_init_server (tls_ctx_t * ctx)
460 {
461   tls_main_t *tm = &tls_main;
462   application_t *app;
463   void *ctx_ptr;
464   int rv;
465
466   mbedtls_ssl_init (&ctx->ssl);
467   mbedtls_ssl_config_init (&ctx->conf);
468   mbedtls_x509_crt_init (&ctx->srvcert);
469   mbedtls_pk_init (&ctx->pkey);
470
471   /*
472    * 1. Cert
473    */
474   app = application_get (ctx->parent_app_index);
475   if (!app->tls_cert || !app->tls_key)
476     {
477       TLS_DBG (1, " failed\n  ! tls cert and/or key not configured %d",
478                ctx->parent_app_index);
479       return -1;
480     }
481
482   rv = mbedtls_x509_crt_parse (&ctx->srvcert,
483                                (const unsigned char *) app->tls_cert,
484                                vec_len (app->tls_cert));
485   if (rv != 0)
486     {
487       TLS_DBG (1, " failed\n  !  mbedtls_x509_crt_parse returned %d", rv);
488       goto exit;
489     }
490
491   rv = mbedtls_pk_parse_key (&ctx->pkey,
492                              (const unsigned char *) app->tls_key,
493                              vec_len (app->tls_key), NULL, 0);
494   if (rv != 0)
495     {
496       TLS_DBG (1, " failed\n  !  mbedtls_pk_parse_key returned %d", rv);
497       goto exit;
498     }
499
500   /*
501    * 2. SSL context config
502    */
503   if ((rv = mbedtls_ssl_config_defaults (&ctx->conf, MBEDTLS_SSL_IS_SERVER,
504                                          MBEDTLS_SSL_TRANSPORT_STREAM,
505                                          MBEDTLS_SSL_PRESET_DEFAULT)) != 0)
506     {
507       TLS_DBG (1, " failed\n  ! mbedtls_ssl_config_defaults returned %d", rv);
508       goto exit;
509     }
510
511   mbedtls_ssl_conf_rng (&ctx->conf, mbedtls_ctr_drbg_random,
512                         tls_get_ctr_drbg ());
513   mbedtls_ssl_conf_dbg (&ctx->conf, mbedtls_debug, stdout);
514
515   /* TODO CACHE
516      mbedtls_ssl_conf_session_cache( &ctx->conf, &cache,
517      mbedtls_ssl_cache_get,
518      mbedtls_ssl_cache_set );
519    */
520
521   mbedtls_ssl_conf_ca_chain (&ctx->conf, &tm->cacert, NULL);
522   if ((rv = mbedtls_ssl_conf_own_cert (&ctx->conf, &ctx->srvcert, &ctx->pkey))
523       != 0)
524     {
525       TLS_DBG (1, " failed\n  ! mbedtls_ssl_conf_own_cert returned %d", rv);
526       goto exit;
527     }
528
529   if ((rv = mbedtls_ssl_setup (&ctx->ssl, &ctx->conf)) != 0)
530     {
531       TLS_DBG (1, " failed\n  ! mbedtls_ssl_setup returned %d", rv);
532       goto exit;
533     }
534
535   mbedtls_ssl_session_reset (&ctx->ssl);
536   ctx_ptr = uword_to_pointer (ctx->tls_ctx_idx, void *);
537   mbedtls_ssl_set_bio (&ctx->ssl, ctx_ptr, tls_net_send, tls_net_recv, NULL);
538
539   mbedtls_debug_set_threshold (TLS_DEBUG_LEVEL_SERVER);
540
541   /*
542    * 3. Start handshake state machine
543    */
544   TLS_DBG (1, "Initiating handshake for [%u]%u", ctx->c_thread_index,
545            ctx->tls_ctx_idx);
546   while (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
547     {
548       rv = mbedtls_ssl_handshake_step (&ctx->ssl);
549       if (rv != 0)
550         break;
551     }
552
553   TLS_DBG (2, "tls state for [%u]%u is %u", ctx->c_thread_index,
554            ctx->tls_ctx_idx, ctx->ssl.state);
555   return 0;
556
557 exit:
558   return -1;
559 }
560
561 static int
562 tls_notify_app_accept (tls_ctx_t * ctx)
563 {
564   stream_session_t *app_listener, *app_session;
565   segment_manager_t *sm;
566   application_t *app;
567   tls_ctx_t *lctx;
568   int rv;
569
570   app = application_get (ctx->parent_app_index);
571   lctx = tls_listener_ctx_get (ctx->listener_ctx_index);
572   app_listener = listen_session_get_from_handle (lctx->app_session_handle);
573   sm = application_get_listen_segment_manager (app, app_listener);
574
575   app_session = session_alloc (vlib_get_thread_index ());
576   app_session->app_index = ctx->parent_app_index;
577   app_session->connection_index = ctx->tls_ctx_idx;
578   app_session->session_type = app_listener->session_type;
579   app_session->listener_index = app_listener->session_index;
580   if ((rv = session_alloc_fifos (sm, app_session)))
581     {
582       TLS_DBG (1, "failed to allocate fifos");
583       return rv;
584     }
585   ctx->c_s_index = app_session->session_index;
586   ctx->app_session_handle = session_handle (app_session);
587   return app->cb_fns.session_accept_callback (app_session);
588 }
589
590 static int
591 tls_notify_app_connected (tls_ctx_t * ctx, u8 is_failed)
592 {
593   int (*cb_fn) (u32, u32, stream_session_t *, u8);
594   stream_session_t *app_session;
595   segment_manager_t *sm;
596   application_t *app;
597
598   app = application_get (ctx->parent_app_index);
599   cb_fn = app->cb_fns.session_connected_callback;
600
601   if (is_failed)
602     goto failed;
603
604   sm = application_get_connect_segment_manager (app);
605   app_session = session_alloc (vlib_get_thread_index ());
606   app_session->app_index = ctx->parent_app_index;
607   app_session->connection_index = ctx->tls_ctx_idx;
608   app_session->session_type =
609     session_type_from_proto_and_ip (TRANSPORT_PROTO_TLS, ctx->tcp_is_ip4);
610   if (session_alloc_fifos (sm, app_session))
611     goto failed;
612
613   ctx->app_session_handle = session_handle (app_session);
614   ctx->c_s_index = app_session->session_index;
615   app_session->session_state = SESSION_STATE_READY;
616   if (cb_fn (ctx->parent_app_index, ctx->parent_app_api_context,
617              app_session, 0 /* not failed */ ))
618     {
619       TLS_DBG (1, "failed to notify app");
620       tls_disconnect (ctx->tls_ctx_idx, vlib_get_thread_index ());
621     }
622
623   return 0;
624
625 failed:
626   return cb_fn (ctx->parent_app_index, ctx->parent_app_api_context, 0,
627                 1 /* failed */ );
628 }
629
630 static int
631 tls_handshake_rx (tls_ctx_t * ctx)
632 {
633   u32 flags;
634   int rv;
635   while (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
636     {
637       rv = mbedtls_ssl_handshake_step (&ctx->ssl);
638       if (rv != 0)
639         break;
640     }
641   TLS_DBG (2, "tls state for %u is %u", ctx->tls_ctx_idx, ctx->ssl.state);
642
643   if (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
644     return 0;
645
646   /*
647    * Handshake complete
648    */
649   if (ctx->ssl.conf->endpoint == MBEDTLS_SSL_IS_CLIENT)
650     {
651       /*
652        * Verify server certificate
653        */
654       if ((flags = mbedtls_ssl_get_verify_result (&ctx->ssl)) != 0)
655         {
656           char buf[512];
657           TLS_DBG (1, " failed\n");
658           mbedtls_x509_crt_verify_info (buf, sizeof (buf), "  ! ", flags);
659           TLS_DBG (1, "%s\n", buf);
660
661           /*
662            * Presence of hostname enforces strict certificate verification
663            */
664           if (ctx->srv_hostname)
665             {
666               tls_disconnect (ctx->tls_ctx_idx, vlib_get_thread_index ());
667               tls_notify_app_connected (ctx, /* is failed */ 1);
668               return -1;
669             }
670         }
671       tls_notify_app_connected (ctx, /* is failed */ 0);
672     }
673   else
674     {
675       tls_notify_app_accept (ctx);
676     }
677
678   TLS_DBG (1, "Handshake for %u complete. TLS cipher is %x",
679            ctx->tls_ctx_idx, ctx->ssl.session->ciphersuite);
680   return 0;
681 }
682
683 void
684 tls_session_reset_callback (stream_session_t * s)
685 {
686   clib_warning ("called...");
687 }
688
689 int
690 tls_add_segment_callback (u32 client_index, const ssvm_private_t * fs)
691 {
692   /* No-op for builtin */
693   return 0;
694 }
695
696 int
697 tls_del_segment_callback (u32 client_index, const ssvm_private_t * fs)
698 {
699   return 0;
700 }
701
702 void
703 tls_session_disconnect_callback (stream_session_t * tls_session)
704 {
705   stream_session_t *app_session;
706   tls_ctx_t *ctx;
707   application_t *app;
708
709   ctx = tls_ctx_get (tls_session->opaque);
710   if (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
711     {
712       stream_session_disconnect (tls_session);
713       return;
714     }
715   ctx->is_passive_close = 1;
716   app = application_get (ctx->parent_app_index);
717   app_session = session_get_from_handle (ctx->app_session_handle);
718   app->cb_fns.session_disconnect_callback (app_session);
719 }
720
721 int
722 tls_session_accept_callback (stream_session_t * tls_session)
723 {
724   stream_session_t *tls_listener;
725   tls_ctx_t *lctx, *ctx;
726   u32 ctx_index;
727
728   tls_listener = listen_session_get (tls_session->session_type,
729                                      tls_session->listener_index);
730   lctx = tls_listener_ctx_get (tls_listener->opaque);
731   ctx_index = tls_ctx_alloc ();
732   ctx = tls_ctx_get (ctx_index);
733   memcpy (ctx, lctx, sizeof (*lctx));
734   ctx->c_thread_index = vlib_get_thread_index ();
735   ctx->tls_ctx_idx = ctx_index;
736   tls_session->session_state = SESSION_STATE_READY;
737   tls_session->opaque = ctx_index;
738   ctx->tls_session_handle = session_handle (tls_session);
739   ctx->listener_ctx_index = tls_listener->opaque;
740
741   TLS_DBG (1, "Accept on listener %u new connection [%u]%u",
742            tls_listener->opaque, vlib_get_thread_index (), ctx_index);
743
744   return tls_ctx_init_server (ctx);
745 }
746
747 int
748 tls_app_tx_callback (stream_session_t * app_session)
749 {
750   stream_session_t *tls_session;
751   tls_ctx_t *ctx;
752   static u8 *tmp_buf;
753   u32 enq_max, deq_max, deq_now;
754   int wrote;
755
756   ctx = tls_ctx_get (app_session->connection_index);
757   if (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
758     tls_add_vpp_q_evt (app_session->server_tx_fifo, FIFO_EVENT_APP_TX);
759
760   deq_max = svm_fifo_max_dequeue (app_session->server_tx_fifo);
761   if (!deq_max)
762     return 0;
763
764   tls_session = session_get_from_handle (ctx->tls_session_handle);
765   enq_max = svm_fifo_max_enqueue (tls_session->server_tx_fifo);
766   deq_now = clib_min (deq_max, TLS_CHUNK_SIZE);
767
768   if (PREDICT_FALSE (enq_max == 0))
769     {
770       tls_add_vpp_q_evt (app_session->server_tx_fifo, FIFO_EVENT_APP_TX);
771       return 0;
772     }
773
774   vec_validate (tmp_buf, deq_now);
775   svm_fifo_peek (app_session->server_tx_fifo, 0, deq_now, tmp_buf);
776   wrote = mbedtls_ssl_write (&ctx->ssl, tmp_buf, deq_now);
777   if (wrote <= 0)
778     {
779       tls_add_vpp_q_evt (app_session->server_tx_fifo, FIFO_EVENT_APP_TX);
780       return 0;
781     }
782
783   svm_fifo_dequeue_drop (app_session->server_tx_fifo, wrote);
784   vec_reset_length (tmp_buf);
785
786   tls_add_vpp_q_evt (tls_session->server_tx_fifo, FIFO_EVENT_APP_TX);
787
788   if (deq_now < deq_max)
789     tls_add_vpp_q_evt (app_session->server_tx_fifo, FIFO_EVENT_APP_TX);
790
791   return 0;
792 }
793
794 int
795 tls_app_rx_callback (stream_session_t * tls_session)
796 {
797   stream_session_t *app_session;
798   u32 deq_max, enq_max, enq_now;
799   application_t *app;
800   static u8 *tmp_buf;
801   tls_ctx_t *ctx;
802   int read, enq;
803
804   ctx = tls_ctx_get (tls_session->opaque);
805   if (ctx->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER)
806     return tls_handshake_rx (ctx);
807
808   deq_max = svm_fifo_max_dequeue (tls_session->server_rx_fifo);
809   if (!deq_max)
810     return 0;
811
812   app_session = session_get_from_handle (ctx->app_session_handle);
813   enq_max = svm_fifo_max_enqueue (app_session->server_rx_fifo);
814   enq_now = clib_min (enq_max, TLS_CHUNK_SIZE);
815
816   if (PREDICT_FALSE (enq_now == 0))
817     {
818       tls_add_vpp_q_evt (tls_session->server_rx_fifo, FIFO_EVENT_BUILTIN_RX);
819       return 0;
820     }
821
822   vec_validate (tmp_buf, enq_now);
823   read = mbedtls_ssl_read (&ctx->ssl, tmp_buf, enq_now);
824   if (read <= 0)
825     {
826       tls_add_vpp_q_evt (tls_session->server_rx_fifo, FIFO_EVENT_BUILTIN_RX);
827       return 0;
828     }
829
830   enq = svm_fifo_enqueue_nowait (app_session->server_rx_fifo, read, tmp_buf);
831   ASSERT (enq == read);
832   vec_reset_length (tmp_buf);
833
834   if (svm_fifo_max_dequeue (tls_session->server_rx_fifo))
835     tls_add_vpp_q_evt (tls_session->server_rx_fifo, FIFO_EVENT_BUILTIN_RX);
836
837   app = application_get_if_valid (app_session->app_index);
838   return tls_add_app_q_evt (app, app_session);
839 }
840
841 int
842 tls_session_connected_callback (u32 tls_app_index, u32 ho_ctx_index,
843                                 stream_session_t * tls_session, u8 is_fail)
844 {
845   int (*cb_fn) (u32, u32, stream_session_t *, u8);
846   application_t *app;
847   tls_ctx_t *ho_ctx, *ctx;
848   u32 ctx_index;
849
850   ho_ctx = tls_ctx_half_open_get (ho_ctx_index);
851   app = application_get (ho_ctx->parent_app_index);
852   cb_fn = app->cb_fns.session_connected_callback;
853
854   if (is_fail)
855     {
856       tls_ctx_half_open_reader_unlock ();
857       tls_ctx_half_open_free (ho_ctx_index);
858       return cb_fn (ho_ctx->parent_app_index, ho_ctx->c_s_index, 0,
859                     1 /* failed */ );
860     }
861
862   ctx_index = tls_ctx_alloc ();
863   ctx = tls_ctx_get (ctx_index);
864   clib_memcpy (ctx, ho_ctx, sizeof (*ctx));
865   tls_ctx_half_open_reader_unlock ();
866   tls_ctx_half_open_free (ho_ctx_index);
867
868   ctx->c_thread_index = vlib_get_thread_index ();
869   ctx->tls_ctx_idx = ctx_index;
870
871   TLS_DBG (1, "TCP connect for %u returned %u. New connection [%u]%u",
872            ho_ctx_index, is_fail, vlib_get_thread_index (),
873            (ctx) ? ctx_index : ~0);
874
875   ctx->tls_session_handle = session_handle (tls_session);
876   tls_session->opaque = ctx_index;
877   tls_session->session_state = SESSION_STATE_READY;
878
879   return tls_ctx_init_client (ctx);
880 }
881
882 /* *INDENT-OFF* */
883 static session_cb_vft_t tls_app_cb_vft = {
884   .session_accept_callback = tls_session_accept_callback,
885   .session_disconnect_callback = tls_session_disconnect_callback,
886   .session_connected_callback = tls_session_connected_callback,
887   .session_reset_callback = tls_session_reset_callback,
888   .add_segment_callback = tls_add_segment_callback,
889   .del_segment_callback = tls_del_segment_callback,
890   .builtin_app_rx_callback = tls_app_rx_callback,
891   .builtin_app_tx_callback = tls_app_tx_callback,
892 };
893 /* *INDENT-ON* */
894
895 int
896 tls_connect (transport_endpoint_t * tep)
897 {
898   session_endpoint_extended_t *sep;
899   session_endpoint_t tls_sep;
900   tls_main_t *tm = &tls_main;
901   application_t *app;
902   tls_ctx_t *ctx;
903   u32 ctx_index;
904   int rv;
905
906   sep = (session_endpoint_extended_t *) tep;
907
908   ctx_index = tls_ctx_half_open_alloc ();
909   ctx = tls_ctx_half_open_get (ctx_index);
910   ctx->parent_app_index = sep->app_index;
911   ctx->parent_app_api_context = sep->opaque;
912   ctx->tcp_is_ip4 = sep->is_ip4;
913   if (sep->hostname)
914     {
915       ctx->srv_hostname = format (0, "%v", sep->hostname);
916       vec_terminate_c_string (ctx->srv_hostname);
917     }
918   tls_ctx_half_open_reader_unlock ();
919
920   app = application_get (sep->app_index);
921   application_alloc_connects_segment_manager (app);
922
923   clib_memcpy (&tls_sep, sep, sizeof (tls_sep));
924   tls_sep.transport_proto = TRANSPORT_PROTO_TCP;
925   if ((rv = application_connect (tm->app_index, ctx_index, &tls_sep)))
926     return rv;
927
928   TLS_DBG (1, "New connect request %u", ctx_index);
929   return 0;
930 }
931
932 void
933 tls_disconnect (u32 ctx_index, u32 thread_index)
934 {
935   stream_session_t *tls_session, *app_session;
936   tls_ctx_t *ctx;
937
938   TLS_DBG (1, "Disconnecting %u", ctx_index);
939
940   ctx = tls_ctx_get (ctx_index);
941   if (ctx->ssl.state == MBEDTLS_SSL_HANDSHAKE_OVER && !ctx->is_passive_close)
942     mbedtls_ssl_close_notify (&ctx->ssl);
943
944   tls_session = session_get_from_handle (ctx->tls_session_handle);
945   stream_session_disconnect (tls_session);
946
947   app_session = session_get_from_handle_if_valid (ctx->app_session_handle);
948   if (app_session)
949     {
950       segment_manager_dealloc_fifos (app_session->svm_segment_index,
951                                      app_session->server_rx_fifo,
952                                      app_session->server_tx_fifo);
953       session_free (app_session);
954     }
955   if (ctx->ssl.conf->endpoint == MBEDTLS_SSL_IS_SERVER)
956     {
957       mbedtls_x509_crt_free (&ctx->srvcert);
958       mbedtls_pk_free (&ctx->pkey);
959     }
960   mbedtls_ssl_free (&ctx->ssl);
961   mbedtls_ssl_config_free (&ctx->conf);
962   tls_ctx_free (ctx);
963 }
964
965 u32
966 tls_start_listen (u32 app_listener_index, transport_endpoint_t * tep)
967 {
968   tls_main_t *tm = &tls_main;
969   application_t *tls_app;
970   session_handle_t tls_handle;
971   session_endpoint_extended_t *sep;
972   stream_session_t *tls_listener;
973   tls_ctx_t *lctx;
974   u32 lctx_index;
975   session_type_t st;
976   stream_session_t *app_listener;
977
978   sep = (session_endpoint_extended_t *) tep;
979   lctx_index = tls_listener_ctx_alloc ();
980   lctx = tls_listener_ctx_get (lctx_index);
981   st = session_type_from_proto_and_ip (sep->transport_proto, sep->is_ip4);
982   app_listener = listen_session_get (st, app_listener_index);
983
984   tls_app = application_get (tm->app_index);
985   sep->transport_proto = TRANSPORT_PROTO_TCP;
986   if (application_start_listen (tls_app, (session_endpoint_t *) sep,
987                                 &tls_handle))
988     return ~0;
989
990   tls_listener = listen_session_get_from_handle (tls_handle);
991   tls_listener->opaque = lctx_index;
992   lctx->parent_app_index = sep->app_index;
993   lctx->tls_session_handle = tls_handle;
994   lctx->app_session_handle = listen_session_get_handle (app_listener);
995   lctx->tcp_is_ip4 = sep->is_ip4;
996   return lctx_index;
997 }
998
999 u32
1000 tls_stop_listen (u32 lctx_index)
1001 {
1002   tls_main_t *tm = &tls_main;
1003   application_t *tls_app;
1004   tls_ctx_t *lctx;
1005   lctx = tls_listener_ctx_get (lctx_index);
1006   tls_app = application_get (tm->app_index);
1007   application_stop_listen (tls_app, lctx->tls_session_handle);
1008   tls_listener_ctx_free (lctx);
1009   return 0;
1010 }
1011
1012 transport_connection_t *
1013 tls_connection_get (u32 ctx_index, u32 thread_index)
1014 {
1015   tls_ctx_t *ctx;
1016   ctx = tls_ctx_get_w_thread (ctx_index, thread_index);
1017   return &ctx->connection;
1018 }
1019
1020 transport_connection_t *
1021 tls_listener_get (u32 listener_index)
1022 {
1023   tls_ctx_t *ctx;
1024   ctx = tls_listener_ctx_get (listener_index);
1025   return &ctx->connection;
1026 }
1027
1028 u8 *
1029 format_tls_ctx (u8 * s, va_list * args)
1030 {
1031   tls_ctx_t *ctx = va_arg (*args, tls_ctx_t *);
1032   u32 thread_index = va_arg (*args, u32);
1033   u32 child_si, child_ti;
1034
1035   session_parse_handle (ctx->tls_session_handle, &child_si, &child_ti);
1036   if (thread_index != child_ti)
1037     clib_warning ("app and tls sessions are on different threads!");
1038
1039   s = format (s, "[#%d][TLS] app %u child %u", child_ti,
1040               ctx->parent_app_index, child_si);
1041   return s;
1042 }
1043
1044 u8 *
1045 format_tls_connection (u8 * s, va_list * args)
1046 {
1047   u32 ctx_index = va_arg (*args, u32);
1048   u32 thread_index = va_arg (*args, u32);
1049   u32 verbose = va_arg (*args, u32);
1050   tls_ctx_t *ctx;
1051
1052   ctx = tls_ctx_get_w_thread (ctx_index, thread_index);
1053   if (!ctx)
1054     return s;
1055
1056   s = format (s, "%-50U", format_tls_ctx, ctx, thread_index);
1057   if (verbose)
1058     {
1059       s = format (s, "%-15s", "state");
1060       if (verbose > 1)
1061         s = format (s, "\n");
1062     }
1063   return s;
1064 }
1065
1066 u8 *
1067 format_tls_listener (u8 * s, va_list * args)
1068 {
1069   u32 tc_index = va_arg (*args, u32);
1070   tls_ctx_t *ctx = tls_listener_ctx_get (tc_index);
1071   u32 listener_index, type;
1072
1073   listen_session_parse_handle (ctx->tls_session_handle, &type,
1074                                &listener_index);
1075   return format (s, "[TLS] listener app %u child %u", ctx->parent_app_index,
1076                  listener_index);
1077 }
1078
1079 u8 *
1080 format_tls_half_open (u8 * s, va_list * args)
1081 {
1082   u32 tc_index = va_arg (*args, u32);
1083   tls_ctx_t *ctx = tls_ctx_half_open_get (tc_index);
1084   s = format (s, "[TLS] half-open app %u", ctx->parent_app_index);
1085   tls_ctx_half_open_reader_unlock ();
1086   return s;
1087 }
1088
1089 /* *INDENT-OFF* */
1090 const static transport_proto_vft_t tls_proto = {
1091   .open = tls_connect,
1092   .close = tls_disconnect,
1093   .bind = tls_start_listen,
1094   .get_connection = tls_connection_get,
1095   .get_listener = tls_listener_get,
1096   .unbind = tls_stop_listen,
1097   .tx_type = TRANSPORT_TX_INTERNAL,
1098   .service_type = TRANSPORT_SERVICE_APP,
1099   .format_connection = format_tls_connection,
1100   .format_half_open = format_tls_half_open,
1101   .format_listener = format_tls_listener,
1102 };
1103 /* *INDENT-ON* */
1104
1105 int
1106 tls_init_mem (void)
1107 {
1108 #if TLS_USE_OUR_MEM_FUNCS
1109   mbedtls_platform_set_calloc_free (mbedtls_calloc_fn, mbedtls_free_fn);
1110 #endif
1111   return 0;
1112 }
1113
1114 int
1115 tls_init_ca_chain (void)
1116 {
1117   tls_main_t *tm = &tls_main;
1118   int rv;
1119
1120   if (!tm->ca_cert_path)
1121     tm->ca_cert_path = TLS_CA_CERT_PATH;
1122
1123   if (access (tm->ca_cert_path, F_OK | R_OK) == -1)
1124     {
1125       clib_warning ("Could not initialize TLS CA certificates");
1126       return -1;
1127     }
1128
1129   mbedtls_x509_crt_init (&tm->cacert);
1130   rv = mbedtls_x509_crt_parse_file (&tm->cacert, tm->ca_cert_path);
1131   if (rv < 0)
1132     {
1133       clib_warning ("Couldn't parse system CA certificates: -0x%x", -rv);
1134     }
1135   if (tm->use_test_cert_in_ca)
1136     {
1137       rv = mbedtls_x509_crt_parse (&tm->cacert,
1138                                    (const unsigned char *) test_srv_crt_rsa,
1139                                    test_srv_crt_rsa_len);
1140       if (rv < 0)
1141         {
1142           clib_warning ("Couldn't parse test certificate: -0x%x", -rv);
1143           return -1;
1144         }
1145     }
1146   return (rv < 0 ? -1 : 0);
1147 }
1148
1149 clib_error_t *
1150 tls_init (vlib_main_t * vm)
1151 {
1152   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1153   u32 fifo_size = 64 << 10, num_threads;
1154   vnet_app_attach_args_t _a, *a = &_a;
1155   u64 options[APP_OPTIONS_N_OPTIONS];
1156   u32 segment_size = 512 << 20;
1157   tls_main_t *tm = &tls_main;
1158
1159   num_threads = 1 /* main thread */  + vtm->n_threads;
1160
1161   if (tls_init_mem ())
1162     {
1163       clib_warning ("failed to initialize mem");
1164       return clib_error_return (0, "failed to initalize mem");
1165     }
1166   if (tls_init_ca_chain ())
1167     {
1168       clib_warning ("failed to initialize TLS CA chain");
1169       return clib_error_return (0, "failed to initalize TLS CA chain");
1170     }
1171   if (tls_init_ctr_drbgs_and_entropy (num_threads))
1172     {
1173       clib_warning ("failed to initialize entropy and random generators");
1174       return clib_error_return (0, "failed to initialize entropy and random "
1175                                 "generators");
1176     }
1177
1178   memset (a, 0, sizeof (*a));
1179   memset (options, 0, sizeof (options));
1180
1181   a->session_cb_vft = &tls_app_cb_vft;
1182   a->api_client_index = (1 << 24) + 1;
1183   a->options = options;
1184   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
1185   a->options[APP_OPTIONS_RX_FIFO_SIZE] = fifo_size;
1186   a->options[APP_OPTIONS_TX_FIFO_SIZE] = fifo_size;
1187   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1188   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1189
1190   if (vnet_application_attach (a))
1191     {
1192       clib_warning ("failed to attach tls app");
1193       return clib_error_return (0, "failed to attach tls app");
1194     }
1195
1196   tm->app_index = a->app_index;
1197   vec_validate (tm->ctx_pool, num_threads - 1);
1198   clib_rwlock_init (&tm->half_open_rwlock);
1199
1200   transport_register_protocol (TRANSPORT_PROTO_TLS, &tls_proto,
1201                                FIB_PROTOCOL_IP4, ~0);
1202   transport_register_protocol (TRANSPORT_PROTO_TLS, &tls_proto,
1203                                FIB_PROTOCOL_IP6, ~0);
1204
1205   return 0;
1206 }
1207
1208 VLIB_INIT_FUNCTION (tls_init);
1209
1210 static clib_error_t *
1211 tls_config_fn (vlib_main_t * vm, unformat_input_t * input)
1212 {
1213   tls_main_t *tm = &tls_main;
1214   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1215     {
1216       if (unformat (input, "use-test-cert-in-ca"))
1217         tm->use_test_cert_in_ca = 1;
1218       else if (unformat (input, "ca-cert-path %s", &tm->ca_cert_path))
1219         ;
1220       else
1221         return clib_error_return (0, "unknown input `%U'",
1222                                   format_unformat_error, input);
1223     }
1224   return 0;
1225 }
1226
1227 VLIB_EARLY_CONFIG_FUNCTION (tls_config_fn, "tls");
1228 /*
1229  * fd.io coding-style-patch-verification: ON
1230  *
1231  * Local Variables:
1232  * eval: (c-set-style "gnu")
1233  * End:
1234  */