tls: cleanup dtls migrated context
[vpp.git] / src / vnet / tls / tls.c
1 /*
2  * Copyright (c) 2018-2019 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 <vnet/tls/tls.h>
19
20 static tls_main_t tls_main;
21 static tls_engine_vft_t *tls_vfts;
22
23 #define TLS_INVALID_HANDLE      ~0
24 #define TLS_IDX_MASK            0x00FFFFFF
25 #define TLS_ENGINE_TYPE_SHIFT   29
26
27 void tls_disconnect (u32 ctx_handle, u32 thread_index);
28
29 void
30 tls_disconnect_transport (tls_ctx_t * ctx)
31 {
32   vnet_disconnect_args_t a = {
33     .handle = ctx->tls_session_handle,
34     .app_index = tls_main.app_index,
35   };
36
37   if (vnet_disconnect_session (&a))
38     clib_warning ("disconnect returned");
39 }
40
41 crypto_engine_type_t
42 tls_get_available_engine (void)
43 {
44   int i;
45   for (i = 0; i < vec_len (tls_vfts); i++)
46     {
47       if (tls_vfts[i].ctx_alloc)
48         return i;
49     }
50   return CRYPTO_ENGINE_NONE;
51 }
52
53 int
54 tls_add_vpp_q_rx_evt (session_t * s)
55 {
56   if (svm_fifo_set_event (s->rx_fifo))
57     session_send_io_evt_to_thread (s->rx_fifo, SESSION_IO_EVT_RX);
58   return 0;
59 }
60
61 int
62 tls_add_vpp_q_builtin_rx_evt (session_t * s)
63 {
64   if (svm_fifo_set_event (s->rx_fifo))
65     session_send_io_evt_to_thread (s->rx_fifo, SESSION_IO_EVT_BUILTIN_RX);
66   return 0;
67 }
68
69 int
70 tls_add_vpp_q_tx_evt (session_t * s)
71 {
72   if (svm_fifo_set_event (s->tx_fifo))
73     session_send_io_evt_to_thread (s->tx_fifo, SESSION_IO_EVT_TX);
74   return 0;
75 }
76
77 static inline int
78 tls_add_app_q_evt (app_worker_t * app, session_t * app_session)
79 {
80   return app_worker_lock_and_send_event (app, app_session, SESSION_IO_EVT_RX);
81 }
82
83 u32
84 tls_listener_ctx_alloc (void)
85 {
86   tls_main_t *tm = &tls_main;
87   tls_ctx_t *ctx;
88
89   pool_get (tm->listener_ctx_pool, ctx);
90   clib_memset (ctx, 0, sizeof (*ctx));
91   return ctx - tm->listener_ctx_pool;
92 }
93
94 void
95 tls_listener_ctx_free (tls_ctx_t * ctx)
96 {
97   if (CLIB_DEBUG)
98     memset (ctx, 0xfb, sizeof (*ctx));
99   pool_put (tls_main.listener_ctx_pool, ctx);
100 }
101
102 tls_ctx_t *
103 tls_listener_ctx_get (u32 ctx_index)
104 {
105   return pool_elt_at_index (tls_main.listener_ctx_pool, ctx_index);
106 }
107
108 u32
109 tls_listener_ctx_index (tls_ctx_t * ctx)
110 {
111   return (ctx - tls_main.listener_ctx_pool);
112 }
113
114 u32
115 tls_ctx_half_open_alloc (void)
116 {
117   tls_main_t *tm = &tls_main;
118   u8 will_expand = 0;
119   tls_ctx_t *ctx;
120   u32 ctx_index;
121
122   pool_get_aligned_will_expand (tm->half_open_ctx_pool, will_expand, 0);
123   if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
124     {
125       clib_rwlock_writer_lock (&tm->half_open_rwlock);
126       pool_get (tm->half_open_ctx_pool, ctx);
127       ctx_index = ctx - tm->half_open_ctx_pool;
128       clib_rwlock_writer_unlock (&tm->half_open_rwlock);
129     }
130   else
131     {
132       /* reader lock assumption: only main thread will call pool_get */
133       clib_rwlock_reader_lock (&tm->half_open_rwlock);
134       pool_get (tm->half_open_ctx_pool, ctx);
135       ctx_index = ctx - tm->half_open_ctx_pool;
136       clib_rwlock_reader_unlock (&tm->half_open_rwlock);
137     }
138   clib_memset (ctx, 0, sizeof (*ctx));
139   return ctx_index;
140 }
141
142 void
143 tls_ctx_half_open_free (u32 ho_index)
144 {
145   tls_main_t *tm = &tls_main;
146   clib_rwlock_writer_lock (&tm->half_open_rwlock);
147   pool_put_index (tls_main.half_open_ctx_pool, ho_index);
148   clib_rwlock_writer_unlock (&tm->half_open_rwlock);
149 }
150
151 tls_ctx_t *
152 tls_ctx_half_open_get (u32 ctx_index)
153 {
154   tls_main_t *tm = &tls_main;
155   clib_rwlock_reader_lock (&tm->half_open_rwlock);
156   return pool_elt_at_index (tm->half_open_ctx_pool, ctx_index);
157 }
158
159 void
160 tls_ctx_half_open_reader_unlock ()
161 {
162   clib_rwlock_reader_unlock (&tls_main.half_open_rwlock);
163 }
164
165 u32
166 tls_ctx_half_open_index (tls_ctx_t * ctx)
167 {
168   return (ctx - tls_main.half_open_ctx_pool);
169 }
170
171 void
172 tls_notify_app_enqueue (tls_ctx_t * ctx, session_t * app_session)
173 {
174   app_worker_t *app_wrk;
175   app_wrk = app_worker_get_if_valid (app_session->app_wrk_index);
176   if (PREDICT_TRUE (app_wrk != 0))
177     tls_add_app_q_evt (app_wrk, app_session);
178 }
179
180 int
181 tls_notify_app_accept (tls_ctx_t * ctx)
182 {
183   session_t *app_listener, *app_session;
184   app_worker_t *app_wrk;
185   tls_ctx_t *lctx;
186   int rv;
187
188   lctx = tls_listener_ctx_get (ctx->listener_ctx_index);
189   app_listener = listen_session_get_from_handle (lctx->app_session_handle);
190
191   app_session = session_get (ctx->c_s_index, ctx->c_thread_index);
192   app_session->app_wrk_index = ctx->parent_app_wrk_index;
193   app_session->connection_index = ctx->tls_ctx_handle;
194   app_session->session_type = app_listener->session_type;
195   app_session->listener_handle = listen_session_get_handle (app_listener);
196   app_session->session_state = SESSION_STATE_ACCEPTING;
197
198   if ((rv = app_worker_init_accepted (app_session)))
199     {
200       TLS_DBG (1, "failed to allocate fifos");
201       session_free (app_session);
202       return rv;
203     }
204   ctx->app_session_handle = session_handle (app_session);
205   ctx->parent_app_wrk_index = app_session->app_wrk_index;
206   app_wrk = app_worker_get (app_session->app_wrk_index);
207   return app_worker_accept_notify (app_wrk, app_session);
208 }
209
210 int
211 tls_notify_app_connected (tls_ctx_t * ctx, session_error_t err)
212 {
213   session_t *app_session;
214   app_worker_t *app_wrk;
215
216   app_wrk = app_worker_get_if_valid (ctx->parent_app_wrk_index);
217   if (!app_wrk)
218     {
219       tls_disconnect_transport (ctx);
220       return -1;
221     }
222
223   if (err)
224     {
225       /* Free app session pre-allocated when transport was established */
226       if (ctx->tls_type == TRANSPORT_PROTO_TLS)
227         session_free (session_get (ctx->c_s_index, ctx->c_thread_index));
228       goto failed;
229     }
230
231   /* For DTLS the app session is not preallocated because the underlying udp
232    * session might migrate to a different worker during the handshake */
233   if (ctx->tls_type == TRANSPORT_PROTO_DTLS)
234     {
235       session_type_t st;
236       app_session = session_alloc (ctx->c_thread_index);
237       app_session->session_state = SESSION_STATE_CREATED;
238       ctx->c_s_index = app_session->session_index;
239       st =
240         session_type_from_proto_and_ip (TRANSPORT_PROTO_DTLS, ctx->tcp_is_ip4);
241       app_session->session_type = st;
242       app_session->connection_index = ctx->tls_ctx_handle;
243     }
244   else
245     {
246       app_session = session_get (ctx->c_s_index, ctx->c_thread_index);
247     }
248
249   app_session->app_wrk_index = ctx->parent_app_wrk_index;
250
251   if ((err = app_worker_init_connected (app_wrk, app_session)))
252     goto failed;
253
254   app_session->session_state = SESSION_STATE_READY;
255   if (app_worker_connect_notify (app_wrk, app_session,
256                                  SESSION_E_NONE, ctx->parent_app_api_context))
257     {
258       TLS_DBG (1, "failed to notify app");
259       app_session->session_state = SESSION_STATE_CONNECTING;
260       tls_disconnect (ctx->tls_ctx_handle, vlib_get_thread_index ());
261       return -1;
262     }
263
264   ctx->app_session_handle = session_handle (app_session);
265
266   return 0;
267
268 failed:
269   ctx->no_app_session = 1;
270   tls_disconnect (ctx->tls_ctx_handle, vlib_get_thread_index ());
271   return app_worker_connect_notify (app_wrk, 0, err,
272                                     ctx->parent_app_api_context);
273 }
274
275 static inline void
276 tls_ctx_parse_handle (u32 ctx_handle, u32 * ctx_index, u32 * engine_type)
277 {
278   *ctx_index = ctx_handle & TLS_IDX_MASK;
279   *engine_type = ctx_handle >> TLS_ENGINE_TYPE_SHIFT;
280 }
281
282 static inline crypto_engine_type_t
283 tls_get_engine_type (crypto_engine_type_t requested,
284                      crypto_engine_type_t preferred)
285 {
286   if (requested != CRYPTO_ENGINE_NONE)
287     {
288       if (tls_vfts[requested].ctx_alloc)
289         return requested;
290       return CRYPTO_ENGINE_NONE;
291     }
292   if (!tls_vfts[preferred].ctx_alloc)
293     return tls_get_available_engine ();
294   return preferred;
295 }
296
297 static inline u32
298 tls_ctx_alloc (crypto_engine_type_t engine_type)
299 {
300   u32 ctx_index;
301   ctx_index = tls_vfts[engine_type].ctx_alloc ();
302   return (((u32) engine_type << TLS_ENGINE_TYPE_SHIFT) | ctx_index);
303 }
304
305 static inline u32
306 tls_ctx_alloc_w_thread (crypto_engine_type_t engine_type, u32 thread_index)
307 {
308   u32 ctx_index;
309   ctx_index = tls_vfts[engine_type].ctx_alloc_w_thread (thread_index);
310   return (((u32) engine_type << TLS_ENGINE_TYPE_SHIFT) | ctx_index);
311 }
312
313 static inline u32
314 tls_ctx_attach (crypto_engine_type_t engine_type, u32 thread_index, void *ctx)
315 {
316   u32 ctx_index;
317   ctx_index = tls_vfts[engine_type].ctx_attach (thread_index, ctx);
318   return (((u32) engine_type << TLS_ENGINE_TYPE_SHIFT) | ctx_index);
319 }
320
321 static inline void *
322 tls_ctx_detach (tls_ctx_t *ctx)
323 {
324   return tls_vfts[ctx->tls_ctx_engine].ctx_detach (ctx);
325 }
326
327 static inline tls_ctx_t *
328 tls_ctx_get (u32 ctx_handle)
329 {
330   u32 ctx_index, engine_type;
331   tls_ctx_parse_handle (ctx_handle, &ctx_index, &engine_type);
332   return tls_vfts[engine_type].ctx_get (ctx_index);
333 }
334
335 static inline tls_ctx_t *
336 tls_ctx_get_w_thread (u32 ctx_handle, u8 thread_index)
337 {
338   u32 ctx_index, engine_type;
339   tls_ctx_parse_handle (ctx_handle, &ctx_index, &engine_type);
340   return tls_vfts[engine_type].ctx_get_w_thread (ctx_index, thread_index);
341 }
342
343 static inline int
344 tls_ctx_init_server (tls_ctx_t * ctx)
345 {
346   return tls_vfts[ctx->tls_ctx_engine].ctx_init_server (ctx);
347 }
348
349 static inline int
350 tls_ctx_init_client (tls_ctx_t * ctx)
351 {
352   return tls_vfts[ctx->tls_ctx_engine].ctx_init_client (ctx);
353 }
354
355 static inline int
356 tls_ctx_write (tls_ctx_t * ctx, session_t * app_session,
357                transport_send_params_t * sp)
358 {
359   u32 n_wrote;
360
361   sp->max_burst_size = sp->max_burst_size * TRANSPORT_PACER_MIN_MSS;
362   n_wrote = tls_vfts[ctx->tls_ctx_engine].ctx_write (ctx, app_session, sp);
363   sp->max_burst_size = n_wrote;
364   return n_wrote > 0 ? clib_max (n_wrote / TRANSPORT_PACER_MIN_MSS, 1) : 0;
365 }
366
367 static inline int
368 tls_ctx_read (tls_ctx_t * ctx, session_t * tls_session)
369 {
370   return tls_vfts[ctx->tls_ctx_engine].ctx_read (ctx, tls_session);
371 }
372
373 static inline int
374 tls_ctx_transport_close (tls_ctx_t * ctx)
375 {
376   return tls_vfts[ctx->tls_ctx_engine].ctx_transport_close (ctx);
377 }
378
379 static inline int
380 tls_ctx_app_close (tls_ctx_t * ctx)
381 {
382   return tls_vfts[ctx->tls_ctx_engine].ctx_app_close (ctx);
383 }
384
385 void
386 tls_ctx_free (tls_ctx_t * ctx)
387 {
388   tls_vfts[ctx->tls_ctx_engine].ctx_free (ctx);
389 }
390
391 u8
392 tls_ctx_handshake_is_over (tls_ctx_t * ctx)
393 {
394   return tls_vfts[ctx->tls_ctx_engine].ctx_handshake_is_over (ctx);
395 }
396
397 void
398 tls_session_reset_callback (session_t * s)
399 {
400   tls_ctx_t *ctx;
401   transport_connection_t *tc;
402   session_t *app_session;
403
404   ctx = tls_ctx_get (s->opaque);
405   ctx->is_passive_close = 1;
406   tc = &ctx->connection;
407   if (tls_ctx_handshake_is_over (ctx))
408     {
409       session_transport_reset_notify (tc);
410       session_transport_closed_notify (tc);
411       tls_disconnect_transport (ctx);
412     }
413   else
414     if ((app_session =
415          session_get_if_valid (ctx->c_s_index, ctx->c_thread_index)))
416     {
417       session_free (app_session);
418       ctx->c_s_index = SESSION_INVALID_INDEX;
419       tls_disconnect_transport (ctx);
420     }
421 }
422
423 int
424 tls_add_segment_callback (u32 client_index, u64 segment_handle)
425 {
426   /* No-op for builtin */
427   return 0;
428 }
429
430 int
431 tls_del_segment_callback (u32 client_index, u64 segment_handle)
432 {
433   return 0;
434 }
435
436 void
437 tls_session_disconnect_callback (session_t * tls_session)
438 {
439   tls_ctx_t *ctx;
440
441   TLS_DBG (1, "TCP disconnecting handle %x session %u", tls_session->opaque,
442            tls_session->session_index);
443
444   ASSERT (tls_session->thread_index == vlib_get_thread_index ()
445           || vlib_thread_is_main_w_barrier ());
446
447   ctx = tls_ctx_get_w_thread (tls_session->opaque, tls_session->thread_index);
448   ctx->is_passive_close = 1;
449   tls_ctx_transport_close (ctx);
450 }
451
452 int
453 tls_session_accept_callback (session_t * tls_session)
454 {
455   session_t *tls_listener, *app_session;
456   tls_ctx_t *lctx, *ctx;
457   u32 ctx_handle;
458
459   tls_listener =
460     listen_session_get_from_handle (tls_session->listener_handle);
461   lctx = tls_listener_ctx_get (tls_listener->opaque);
462
463   ctx_handle = tls_ctx_alloc (lctx->tls_ctx_engine);
464   ctx = tls_ctx_get (ctx_handle);
465   memcpy (ctx, lctx, sizeof (*lctx));
466   ctx->c_thread_index = vlib_get_thread_index ();
467   ctx->tls_ctx_handle = ctx_handle;
468   tls_session->session_state = SESSION_STATE_READY;
469   tls_session->opaque = ctx_handle;
470   ctx->tls_session_handle = session_handle (tls_session);
471   ctx->listener_ctx_index = tls_listener->opaque;
472   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
473   ctx->ckpair_index = lctx->ckpair_index;
474
475   /* Preallocate app session. Avoids allocating a session post handshake
476    * on tls_session rx and potentially invalidating the session pool */
477   app_session = session_alloc (ctx->c_thread_index);
478   app_session->session_state = SESSION_STATE_CREATED;
479   ctx->c_s_index = app_session->session_index;
480
481   TLS_DBG (1, "Accept on listener %u new connection [%u]%x",
482            tls_listener->opaque, vlib_get_thread_index (), ctx_handle);
483
484   return tls_ctx_init_server (ctx);
485 }
486
487 int
488 tls_app_rx_callback (session_t * tls_session)
489 {
490   tls_ctx_t *ctx;
491
492   /* DTLS session migrating, wait for next notification */
493   if (PREDICT_FALSE (tls_session->flags & SESSION_F_IS_MIGRATING))
494     return 0;
495
496   ctx = tls_ctx_get (tls_session->opaque);
497   tls_ctx_read (ctx, tls_session);
498   return 0;
499 }
500
501 int
502 tls_app_tx_callback (session_t * tls_session)
503 {
504   tls_ctx_t *ctx;
505
506   ctx = tls_ctx_get (tls_session->opaque);
507   transport_connection_reschedule (&ctx->connection);
508
509   return 0;
510 }
511
512 int
513 tls_session_connected_cb (u32 tls_app_index, u32 ho_ctx_index,
514                           session_t *tls_session, session_error_t err)
515 {
516   session_t *app_session;
517   tls_ctx_t *ho_ctx, *ctx;
518   session_type_t st;
519   u32 ctx_handle;
520
521   ho_ctx = tls_ctx_half_open_get (ho_ctx_index);
522
523   if (err)
524     {
525       app_worker_t *app_wrk;
526       u32 api_context;
527       int rv = 0;
528
529       app_wrk = app_worker_get_if_valid (ho_ctx->parent_app_wrk_index);
530       if (app_wrk)
531         {
532           api_context = ho_ctx->parent_app_api_context;
533           app_worker_connect_notify (app_wrk, 0, err, api_context);
534         }
535       tls_ctx_half_open_reader_unlock ();
536       tls_ctx_half_open_free (ho_ctx_index);
537       return rv;
538     }
539
540   ctx_handle = tls_ctx_alloc (ho_ctx->tls_ctx_engine);
541   ctx = tls_ctx_get (ctx_handle);
542   clib_memcpy_fast (ctx, ho_ctx, sizeof (*ctx));
543   tls_ctx_half_open_reader_unlock ();
544   tls_ctx_half_open_free (ho_ctx_index);
545
546   ctx->c_thread_index = vlib_get_thread_index ();
547   ctx->tls_ctx_handle = ctx_handle;
548   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
549
550   TLS_DBG (1, "TCP connect for %u returned %u. New connection [%u]%x",
551            ho_ctx_index, err, vlib_get_thread_index (),
552            (ctx) ? ctx_handle : ~0);
553
554   ctx->tls_session_handle = session_handle (tls_session);
555   tls_session->opaque = ctx_handle;
556   tls_session->session_state = SESSION_STATE_READY;
557
558   /* Preallocate app session. Avoids allocating a session post handshake
559    * on tls_session rx and potentially invalidating the session pool */
560   app_session = session_alloc (ctx->c_thread_index);
561   app_session->session_state = SESSION_STATE_CREATED;
562   ctx->c_s_index = app_session->session_index;
563   st = session_type_from_proto_and_ip (TRANSPORT_PROTO_TLS, ctx->tcp_is_ip4);
564   app_session->session_type = st;
565   app_session->connection_index = ctx->tls_ctx_handle;
566
567   return tls_ctx_init_client (ctx);
568 }
569
570 int
571 dtls_session_connected_cb (u32 app_wrk_index, u32 ctx_handle, session_t *us,
572                            session_error_t err)
573 {
574   tls_ctx_t *ctx;
575
576   ctx = tls_ctx_get_w_thread (ctx_handle, 1 /* udp allocs on thread 1 */);
577
578   ctx->tls_session_handle = session_handle (us);
579   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
580   us->opaque = ctx_handle;
581
582   /* We don't preallocate the app session because the udp session might
583    * actually migrate to a different worker at the end of the handshake */
584
585   return tls_ctx_init_client (ctx);
586 }
587
588 int
589 tls_session_connected_callback (u32 tls_app_index, u32 ho_ctx_index,
590                                 session_t *tls_session, session_error_t err)
591 {
592   if (session_get_transport_proto (tls_session) == TRANSPORT_PROTO_TCP)
593     return tls_session_connected_cb (tls_app_index, ho_ctx_index, tls_session,
594                                      err);
595   else
596     return dtls_session_connected_cb (tls_app_index, ho_ctx_index, tls_session,
597                                       err);
598 }
599
600 static void
601 tls_app_session_cleanup (session_t * s, session_cleanup_ntf_t ntf)
602 {
603   tls_ctx_t *ctx;
604
605   if (ntf == SESSION_CLEANUP_TRANSPORT)
606     {
607       /* Allow cleanup of tcp session */
608       if (s->session_state == SESSION_STATE_TRANSPORT_DELETED)
609         session_close (s);
610       return;
611     }
612
613   ctx = tls_ctx_get (s->opaque);
614   if (!ctx->no_app_session)
615     session_transport_delete_notify (&ctx->connection);
616   tls_ctx_free (ctx);
617 }
618
619 static void
620 dtls_migrate_ctx (void *arg)
621 {
622   tls_ctx_t *ctx = (tls_ctx_t *) arg;
623   u32 ctx_handle, thread_index;
624   session_t *us;
625
626   thread_index = session_thread_from_handle (ctx->tls_session_handle);
627   ASSERT (thread_index == vlib_get_thread_index ());
628
629   ctx_handle = tls_ctx_attach (ctx->tls_ctx_engine, thread_index, ctx);
630   ctx = tls_ctx_get_w_thread (ctx_handle, thread_index);
631   ctx->tls_ctx_handle = ctx_handle;
632
633   us = session_get_from_handle (ctx->tls_session_handle);
634   us->opaque = ctx_handle;
635   us->flags &= ~SESSION_F_IS_MIGRATING;
636   if (svm_fifo_max_dequeue (us->tx_fifo))
637     session_send_io_evt_to_thread (us->tx_fifo, SESSION_IO_EVT_TX);
638 }
639
640 static void
641 dtls_session_migrate_callback (session_t *us, session_handle_t new_sh)
642 {
643   u32 new_thread = session_thread_from_handle (new_sh);
644   tls_ctx_t *ctx, *cloned_ctx;
645
646   /* Migrate dtls context to new thread */
647   ctx = tls_ctx_get_w_thread (us->opaque, us->thread_index);
648   ctx->tls_session_handle = new_sh;
649   cloned_ctx = tls_ctx_detach (ctx);
650   ctx->is_migrated = 1;
651
652   session_send_rpc_evt_to_thread (new_thread, dtls_migrate_ctx,
653                                   (void *) cloned_ctx);
654
655   tls_ctx_free (ctx);
656 }
657
658 static session_cb_vft_t tls_app_cb_vft = {
659   .session_accept_callback = tls_session_accept_callback,
660   .session_disconnect_callback = tls_session_disconnect_callback,
661   .session_connected_callback = tls_session_connected_callback,
662   .session_reset_callback = tls_session_reset_callback,
663   .add_segment_callback = tls_add_segment_callback,
664   .del_segment_callback = tls_del_segment_callback,
665   .builtin_app_rx_callback = tls_app_rx_callback,
666   .builtin_app_tx_callback = tls_app_tx_callback,
667   .session_migrate_callback = dtls_session_migrate_callback,
668   .session_cleanup_callback = tls_app_session_cleanup,
669 };
670
671 int
672 tls_connect (transport_endpoint_cfg_t * tep)
673 {
674   vnet_connect_args_t _cargs = { {}, }, *cargs = &_cargs;
675   transport_endpt_crypto_cfg_t *ccfg;
676   crypto_engine_type_t engine_type;
677   session_endpoint_cfg_t *sep;
678   tls_main_t *tm = &tls_main;
679   app_worker_t *app_wrk;
680   application_t *app;
681   tls_ctx_t *ctx;
682   u32 ctx_index;
683   int rv;
684
685   sep = (session_endpoint_cfg_t *) tep;
686   if (!sep->ext_cfg)
687     return SESSION_E_NOEXTCFG;
688
689   app_wrk = app_worker_get (sep->app_wrk_index);
690   app = application_get (app_wrk->app_index);
691
692   ccfg = &sep->ext_cfg->crypto;
693   engine_type = tls_get_engine_type (ccfg->crypto_engine, app->tls_engine);
694   if (engine_type == CRYPTO_ENGINE_NONE)
695     {
696       clib_warning ("No tls engine_type available");
697       return SESSION_E_NOCRYPTOENG;
698     }
699
700   ctx_index = tls_ctx_half_open_alloc ();
701   ctx = tls_ctx_half_open_get (ctx_index);
702   ctx->parent_app_wrk_index = sep->app_wrk_index;
703   ctx->parent_app_api_context = sep->opaque;
704   ctx->tcp_is_ip4 = sep->is_ip4;
705   ctx->tls_type = sep->transport_proto;
706   ctx->ckpair_index = ccfg->ckpair_index;
707   if (ccfg->hostname[0])
708     {
709       ctx->srv_hostname = format (0, "%s", ccfg->hostname);
710       vec_terminate_c_string (ctx->srv_hostname);
711     }
712   tls_ctx_half_open_reader_unlock ();
713
714   app_worker_alloc_connects_segment_manager (app_wrk);
715   ctx->tls_ctx_engine = engine_type;
716
717   clib_memcpy_fast (&cargs->sep, sep, sizeof (session_endpoint_t));
718   cargs->sep.transport_proto = TRANSPORT_PROTO_TCP;
719   cargs->app_index = tm->app_index;
720   cargs->api_context = ctx_index;
721   cargs->sep_ext.ns_index = app->ns_index;
722   if ((rv = vnet_connect (cargs)))
723     return rv;
724
725   TLS_DBG (1, "New connect request %u engine %d", ctx_index, engine_type);
726   return 0;
727 }
728
729 void
730 tls_disconnect (u32 ctx_handle, u32 thread_index)
731 {
732   tls_ctx_t *ctx;
733
734   TLS_DBG (1, "Disconnecting %x", ctx_handle);
735
736   ctx = tls_ctx_get (ctx_handle);
737   tls_ctx_app_close (ctx);
738 }
739
740 u32
741 tls_start_listen (u32 app_listener_index, transport_endpoint_t * tep)
742 {
743   vnet_listen_args_t _bargs, *args = &_bargs;
744   transport_endpt_crypto_cfg_t *ccfg;
745   app_worker_t *app_wrk;
746   tls_main_t *tm = &tls_main;
747   session_handle_t tls_al_handle;
748   session_endpoint_cfg_t *sep;
749   session_t *tls_listener;
750   session_t *app_listener;
751   crypto_engine_type_t engine_type;
752   application_t *app;
753   app_listener_t *al;
754   tls_ctx_t *lctx;
755   u32 lctx_index;
756   int rv;
757
758   sep = (session_endpoint_cfg_t *) tep;
759   if (!sep->ext_cfg)
760     return SESSION_E_NOEXTCFG;
761
762   app_wrk = app_worker_get (sep->app_wrk_index);
763   app = application_get (app_wrk->app_index);
764
765   ccfg = &sep->ext_cfg->crypto;
766   engine_type = tls_get_engine_type (ccfg->crypto_engine, app->tls_engine);
767   if (engine_type == CRYPTO_ENGINE_NONE)
768     {
769       clib_warning ("No tls engine_type available");
770       return SESSION_E_NOCRYPTOENG;
771     }
772
773   clib_memset (args, 0, sizeof (*args));
774   args->app_index = tm->app_index;
775   args->sep_ext = *sep;
776   args->sep_ext.ns_index = app->ns_index;
777   args->sep_ext.transport_proto = TRANSPORT_PROTO_TCP;
778   if (sep->transport_proto == TRANSPORT_PROTO_DTLS)
779     {
780       args->sep_ext.transport_proto = TRANSPORT_PROTO_UDP;
781       args->sep_ext.transport_flags = TRANSPORT_CFG_F_CONNECTED;
782     }
783   if ((rv = vnet_listen (args)))
784     return rv;
785
786   lctx_index = tls_listener_ctx_alloc ();
787   tls_al_handle = args->handle;
788   al = app_listener_get_w_handle (tls_al_handle);
789   tls_listener = app_listener_get_session (al);
790   tls_listener->opaque = lctx_index;
791
792   app_listener = listen_session_get (app_listener_index);
793
794   lctx = tls_listener_ctx_get (lctx_index);
795   lctx->parent_app_wrk_index = sep->app_wrk_index;
796   lctx->tls_session_handle = tls_al_handle;
797   lctx->app_session_handle = listen_session_get_handle (app_listener);
798   lctx->tcp_is_ip4 = sep->is_ip4;
799   lctx->tls_ctx_engine = engine_type;
800   lctx->tls_type = sep->transport_proto;
801   lctx->ckpair_index = ccfg->ckpair_index;
802
803   if (tls_vfts[engine_type].ctx_start_listen (lctx))
804     {
805       vnet_unlisten_args_t a = {
806         .handle = lctx->tls_session_handle,
807         .app_index = tls_main.app_index,
808         .wrk_map_index = 0
809       };
810       if ((vnet_unlisten (&a)))
811         clib_warning ("unlisten returned");
812       tls_listener_ctx_free (lctx);
813       lctx_index = SESSION_INVALID_INDEX;
814     }
815
816   TLS_DBG (1, "Started listening %d, engine type %d", lctx_index,
817            engine_type);
818   return lctx_index;
819 }
820
821 u32
822 tls_stop_listen (u32 lctx_index)
823 {
824   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
825   crypto_engine_type_t engine_type;
826   transport_connection_t *lc;
827   tls_ctx_t *lctx;
828   session_t *ls;
829   int rv;
830
831   lctx = tls_listener_ctx_get (lctx_index);
832
833   /* Cleanup listener from session lookup table */
834   ls = session_get_from_handle (lctx->tls_session_handle);
835   lc = session_get_transport (ls);
836
837   sep.fib_index = lc->fib_index;
838   sep.port = lc->lcl_port;
839   sep.is_ip4 = lc->is_ip4;
840   sep.transport_proto = lctx->tls_type;
841   clib_memcpy (&sep.ip, &lc->lcl_ip, sizeof (lc->lcl_ip));
842   session_lookup_del_session_endpoint2 (&sep);
843
844   vnet_unlisten_args_t a = {
845     .handle = lctx->tls_session_handle,
846     .app_index = tls_main.app_index,
847     .wrk_map_index = 0          /* default wrk */
848   };
849   if ((rv = vnet_unlisten (&a)))
850     clib_warning ("unlisten returned %d", rv);
851
852   engine_type = lctx->tls_ctx_engine;
853   tls_vfts[engine_type].ctx_stop_listen (lctx);
854
855   tls_listener_ctx_free (lctx);
856   return 0;
857 }
858
859 transport_connection_t *
860 tls_connection_get (u32 ctx_index, u32 thread_index)
861 {
862   tls_ctx_t *ctx;
863   ctx = tls_ctx_get_w_thread (ctx_index, thread_index);
864   return &ctx->connection;
865 }
866
867 transport_connection_t *
868 tls_listener_get (u32 listener_index)
869 {
870   tls_ctx_t *ctx;
871   ctx = tls_listener_ctx_get (listener_index);
872   return &ctx->connection;
873 }
874
875 int
876 tls_custom_tx_callback (void *session, transport_send_params_t * sp)
877 {
878   session_t *app_session = (session_t *) session;
879   tls_ctx_t *ctx;
880
881   if (PREDICT_FALSE (app_session->session_state
882                      >= SESSION_STATE_TRANSPORT_CLOSED))
883     return 0;
884
885   sp->flags = 0;
886   ctx = tls_ctx_get (app_session->connection_index);
887   return tls_ctx_write (ctx, app_session, sp);
888 }
889
890 u8 *
891 format_tls_ctx (u8 * s, va_list * args)
892 {
893   u32 tcp_si, tcp_ti, ctx_index, ctx_engine;
894   tls_ctx_t *ctx = va_arg (*args, tls_ctx_t *);
895   char *proto;
896
897   proto = ctx->tls_type == TRANSPORT_PROTO_TLS ? "TLS" : "DTLS";
898   session_parse_handle (ctx->tls_session_handle, &tcp_si, &tcp_ti);
899   tls_ctx_parse_handle (ctx->tls_ctx_handle, &ctx_index, &ctx_engine);
900   s =
901     format (s, "[%d:%d][%s] app_wrk %u index %u engine %u ts %d:%d",
902             ctx->c_thread_index, ctx->c_s_index, proto,
903             ctx->parent_app_wrk_index, ctx_index, ctx_engine, tcp_ti, tcp_si);
904
905   return s;
906 }
907
908 static u8 *
909 format_tls_listener_ctx (u8 * s, va_list * args)
910 {
911   session_t *tls_listener;
912   app_listener_t *al;
913   tls_ctx_t *ctx;
914   char *proto;
915
916   ctx = va_arg (*args, tls_ctx_t *);
917
918   proto = ctx->tls_type == TRANSPORT_PROTO_TLS ? "TLS" : "DTLS";
919   al = app_listener_get_w_handle (ctx->tls_session_handle);
920   tls_listener = app_listener_get_session (al);
921   s = format (s, "[%d:%d][%s] app_wrk %u engine %u ts %d:%d",
922               ctx->c_thread_index, ctx->c_s_index, proto,
923               ctx->parent_app_wrk_index, ctx->tls_ctx_engine,
924               tls_listener->thread_index, tls_listener->session_index);
925
926   return s;
927 }
928
929 static u8 *
930 format_tls_ctx_state (u8 * s, va_list * args)
931 {
932   tls_ctx_t *ctx;
933   session_t *ts;
934
935   ctx = va_arg (*args, tls_ctx_t *);
936   ts = session_get (ctx->c_s_index, ctx->c_thread_index);
937   if (ts->session_state == SESSION_STATE_LISTENING)
938     s = format (s, "%s", "LISTEN");
939   else
940     {
941       if (ts->session_state >= SESSION_STATE_TRANSPORT_CLOSED)
942         s = format (s, "%s", "CLOSED");
943       else if (ts->session_state == SESSION_STATE_APP_CLOSED)
944         s = format (s, "%s", "APP-CLOSED");
945       else if (ts->session_state >= SESSION_STATE_TRANSPORT_CLOSING)
946         s = format (s, "%s", "CLOSING");
947       else if (tls_ctx_handshake_is_over (ctx))
948         s = format (s, "%s", "ESTABLISHED");
949       else
950         s = format (s, "%s", "HANDSHAKE");
951     }
952
953   return s;
954 }
955
956 u8 *
957 format_tls_connection (u8 * s, va_list * args)
958 {
959   u32 ctx_index = va_arg (*args, u32);
960   u32 thread_index = va_arg (*args, u32);
961   u32 verbose = va_arg (*args, u32);
962   tls_ctx_t *ctx;
963
964   ctx = tls_ctx_get_w_thread (ctx_index, thread_index);
965   if (!ctx)
966     return s;
967
968   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_tls_ctx, ctx);
969   if (verbose)
970     {
971       s = format (s, "%-" SESSION_CLI_STATE_LEN "U", format_tls_ctx_state,
972                   ctx);
973       if (verbose > 1)
974         s = format (s, "\n");
975     }
976   return s;
977 }
978
979 u8 *
980 format_tls_listener (u8 * s, va_list * args)
981 {
982   u32 tc_index = va_arg (*args, u32);
983   u32 __clib_unused thread_index = va_arg (*args, u32);
984   u32 verbose = va_arg (*args, u32);
985   tls_ctx_t *ctx = tls_listener_ctx_get (tc_index);
986
987   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_tls_listener_ctx, ctx);
988   if (verbose)
989     s = format (s, "%-" SESSION_CLI_STATE_LEN "U", format_tls_ctx_state, ctx);
990   return s;
991 }
992
993 u8 *
994 format_tls_half_open (u8 * s, va_list * args)
995 {
996   u32 tc_index = va_arg (*args, u32);
997   u32 __clib_unused thread_index = va_arg (*args, u32);
998   tls_ctx_t *ctx = tls_ctx_half_open_get (tc_index);
999   s = format (s, "[TLS] half-open app %u", ctx->parent_app_wrk_index);
1000   tls_ctx_half_open_reader_unlock ();
1001   return s;
1002 }
1003
1004 static void
1005 tls_transport_endpoint_get (u32 ctx_handle, u32 thread_index,
1006                             transport_endpoint_t * tep, u8 is_lcl)
1007 {
1008   tls_ctx_t *ctx = tls_ctx_get_w_thread (ctx_handle, thread_index);
1009   session_t *tcp_session;
1010
1011   tcp_session = session_get_from_handle (ctx->tls_session_handle);
1012   session_get_endpoint (tcp_session, tep, is_lcl);
1013 }
1014
1015 static void
1016 tls_transport_listener_endpoint_get (u32 ctx_handle,
1017                                      transport_endpoint_t * tep, u8 is_lcl)
1018 {
1019   session_t *tls_listener;
1020   app_listener_t *al;
1021   tls_ctx_t *ctx = tls_listener_ctx_get (ctx_handle);
1022
1023   al = app_listener_get_w_handle (ctx->tls_session_handle);
1024   tls_listener = app_listener_get_session (al);
1025   session_get_endpoint (tls_listener, tep, is_lcl);
1026 }
1027
1028 static clib_error_t *
1029 tls_enable (vlib_main_t * vm, u8 is_en)
1030 {
1031   u32 add_segment_size = 256 << 20, first_seg_size = 32 << 20;
1032   vnet_app_detach_args_t _da, *da = &_da;
1033   vnet_app_attach_args_t _a, *a = &_a;
1034   u64 options[APP_OPTIONS_N_OPTIONS];
1035   tls_main_t *tm = &tls_main;
1036   u32 fifo_size = 128 << 12;
1037
1038   if (!is_en)
1039     {
1040       da->app_index = tm->app_index;
1041       da->api_client_index = APP_INVALID_INDEX;
1042       vnet_application_detach (da);
1043       return 0;
1044     }
1045
1046   first_seg_size = tm->first_seg_size ? tm->first_seg_size : first_seg_size;
1047   fifo_size = tm->fifo_size ? tm->fifo_size : fifo_size;
1048
1049   clib_memset (a, 0, sizeof (*a));
1050   clib_memset (options, 0, sizeof (options));
1051
1052   a->session_cb_vft = &tls_app_cb_vft;
1053   a->api_client_index = APP_INVALID_INDEX;
1054   a->options = options;
1055   a->name = format (0, "tls");
1056   a->options[APP_OPTIONS_SEGMENT_SIZE] = first_seg_size;
1057   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = add_segment_size;
1058   a->options[APP_OPTIONS_RX_FIFO_SIZE] = fifo_size;
1059   a->options[APP_OPTIONS_TX_FIFO_SIZE] = fifo_size;
1060   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1061   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1062   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
1063
1064   if (vnet_application_attach (a))
1065     {
1066       clib_warning ("failed to attach tls app");
1067       return clib_error_return (0, "failed to attach tls app");
1068     }
1069
1070   tm->app_index = a->app_index;
1071   vec_free (a->name);
1072
1073   return 0;
1074 }
1075
1076 static const transport_proto_vft_t tls_proto = {
1077   .enable = tls_enable,
1078   .connect = tls_connect,
1079   .close = tls_disconnect,
1080   .start_listen = tls_start_listen,
1081   .stop_listen = tls_stop_listen,
1082   .get_connection = tls_connection_get,
1083   .get_listener = tls_listener_get,
1084   .custom_tx = tls_custom_tx_callback,
1085   .format_connection = format_tls_connection,
1086   .format_half_open = format_tls_half_open,
1087   .format_listener = format_tls_listener,
1088   .get_transport_endpoint = tls_transport_endpoint_get,
1089   .get_transport_listener_endpoint = tls_transport_listener_endpoint_get,
1090   .transport_options = {
1091     .name = "tls",
1092     .short_name = "J",
1093     .tx_type = TRANSPORT_TX_INTERNAL,
1094     .service_type = TRANSPORT_SERVICE_APP,
1095   },
1096 };
1097
1098 int
1099 dtls_connect (transport_endpoint_cfg_t *tep)
1100 {
1101   vnet_connect_args_t _cargs = { {}, }, *cargs = &_cargs;
1102   transport_endpt_crypto_cfg_t *ccfg;
1103   crypto_engine_type_t engine_type;
1104   session_endpoint_cfg_t *sep;
1105   tls_main_t *tm = &tls_main;
1106   app_worker_t *app_wrk;
1107   application_t *app;
1108   tls_ctx_t *ctx;
1109   u32 ctx_handle;
1110   int rv;
1111
1112   sep = (session_endpoint_cfg_t *) tep;
1113   if (!sep->ext_cfg)
1114     return -1;
1115
1116   app_wrk = app_worker_get (sep->app_wrk_index);
1117   app = application_get (app_wrk->app_index);
1118
1119   ccfg = &sep->ext_cfg->crypto;
1120   engine_type = tls_get_engine_type (ccfg->crypto_engine, app->tls_engine);
1121   if (engine_type == CRYPTO_ENGINE_NONE)
1122     {
1123       clib_warning ("No tls engine_type available");
1124       return -1;
1125     }
1126
1127   ctx_handle = tls_ctx_alloc_w_thread (engine_type, 1 /* because of udp */);
1128   ctx = tls_ctx_get_w_thread (ctx_handle, 1);
1129   ctx->parent_app_wrk_index = sep->app_wrk_index;
1130   ctx->parent_app_api_context = sep->opaque;
1131   ctx->tcp_is_ip4 = sep->is_ip4;
1132   ctx->ckpair_index = ccfg->ckpair_index;
1133   ctx->tls_type = sep->transport_proto;
1134   ctx->tls_ctx_handle = ctx_handle;
1135   if (ccfg->hostname[0])
1136     {
1137       ctx->srv_hostname = format (0, "%s", ccfg->hostname);
1138       vec_terminate_c_string (ctx->srv_hostname);
1139     }
1140
1141   app_worker_alloc_connects_segment_manager (app_wrk);
1142   ctx->tls_ctx_engine = engine_type;
1143
1144   clib_memcpy_fast (&cargs->sep, sep, sizeof (session_endpoint_t));
1145   cargs->sep.transport_proto = TRANSPORT_PROTO_UDP;
1146   cargs->app_index = tm->app_index;
1147   cargs->api_context = ctx_handle;
1148   cargs->sep_ext.ns_index = app->ns_index;
1149   cargs->sep_ext.transport_flags = TRANSPORT_CFG_F_CONNECTED;
1150   if ((rv = vnet_connect (cargs)))
1151     return rv;
1152
1153   TLS_DBG (1, "New DTLS connect request %x engine %d", ctx_handle,
1154            engine_type);
1155   return 0;
1156 }
1157
1158 static void
1159 dtls_cleanup_callback (u32 ctx_index, u32 thread_index)
1160 {
1161   /* No op */
1162 }
1163
1164 static const transport_proto_vft_t dtls_proto = {
1165   .enable = 0,
1166   .connect = dtls_connect,
1167   .close = tls_disconnect,
1168   .start_listen = tls_start_listen,
1169   .stop_listen = tls_stop_listen,
1170   .get_connection = tls_connection_get,
1171   .get_listener = tls_listener_get,
1172   .custom_tx = tls_custom_tx_callback,
1173   .cleanup = dtls_cleanup_callback,
1174   .format_connection = format_tls_connection,
1175   .format_half_open = format_tls_half_open,
1176   .format_listener = format_tls_listener,
1177   .get_transport_endpoint = tls_transport_endpoint_get,
1178   .get_transport_listener_endpoint = tls_transport_listener_endpoint_get,
1179   .transport_options = {
1180     .name = "dtls",
1181     .short_name = "D",
1182     .tx_type = TRANSPORT_TX_INTERNAL,
1183     .service_type = TRANSPORT_SERVICE_APP,
1184   },
1185 };
1186
1187 void
1188 tls_register_engine (const tls_engine_vft_t * vft, crypto_engine_type_t type)
1189 {
1190   vec_validate (tls_vfts, type);
1191   tls_vfts[type] = *vft;
1192 }
1193
1194 static clib_error_t *
1195 tls_init (vlib_main_t * vm)
1196 {
1197   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1198   tls_main_t *tm = &tls_main;
1199   u32 num_threads;
1200
1201   num_threads = 1 /* main thread */  + vtm->n_threads;
1202
1203   if (!tm->ca_cert_path)
1204     tm->ca_cert_path = TLS_CA_CERT_PATH;
1205
1206   clib_rwlock_init (&tm->half_open_rwlock);
1207
1208   vec_validate (tm->rx_bufs, num_threads - 1);
1209   vec_validate (tm->tx_bufs, num_threads - 1);
1210
1211   transport_register_protocol (TRANSPORT_PROTO_TLS, &tls_proto,
1212                                FIB_PROTOCOL_IP4, ~0);
1213   transport_register_protocol (TRANSPORT_PROTO_TLS, &tls_proto,
1214                                FIB_PROTOCOL_IP6, ~0);
1215
1216   transport_register_protocol (TRANSPORT_PROTO_DTLS, &dtls_proto,
1217                                FIB_PROTOCOL_IP4, ~0);
1218   transport_register_protocol (TRANSPORT_PROTO_DTLS, &dtls_proto,
1219                                FIB_PROTOCOL_IP6, ~0);
1220   return 0;
1221 }
1222
1223 VLIB_INIT_FUNCTION (tls_init);
1224
1225 static clib_error_t *
1226 tls_config_fn (vlib_main_t * vm, unformat_input_t * input)
1227 {
1228   tls_main_t *tm = &tls_main;
1229   uword tmp;
1230   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1231     {
1232       if (unformat (input, "use-test-cert-in-ca"))
1233         tm->use_test_cert_in_ca = 1;
1234       else if (unformat (input, "ca-cert-path %s", &tm->ca_cert_path))
1235         ;
1236       else if (unformat (input, "first-segment-size %U", unformat_memory_size,
1237                          &tm->first_seg_size))
1238         ;
1239       else if (unformat (input, "fifo-size %U", unformat_memory_size, &tmp))
1240         {
1241           if (tmp >= 0x100000000ULL)
1242             {
1243               return clib_error_return
1244                 (0, "fifo-size %llu (0x%llx) too large", tmp, tmp);
1245             }
1246           tm->fifo_size = tmp;
1247         }
1248       else
1249         return clib_error_return (0, "unknown input `%U'",
1250                                   format_unformat_error, input);
1251     }
1252   return 0;
1253 }
1254
1255 VLIB_EARLY_CONFIG_FUNCTION (tls_config_fn, "tls");
1256
1257 tls_main_t *
1258 vnet_tls_get_main (void)
1259 {
1260   return &tls_main;
1261 }
1262
1263 /*
1264  * fd.io coding-style-patch-verification: ON
1265  *
1266  * Local Variables:
1267  * eval: (c-set-style "gnu")
1268  * End:
1269  */