a0448e933385967f887fa0874fbd296128020b03
[vpp.git] / src / plugins / tlspicotls / tls_picotls.c
1 #include <math.h>
2
3 #include <tlspicotls/certs.h>
4 #include <tlspicotls/tls_picotls.h>
5 #include <tlspicotls/pico_vpp_crypto.h>
6
7 picotls_main_t picotls_main;
8
9 #define MAX_QUEUE 12000
10 #define PTLS_MAX_PLAINTEXT_RECORD_SIZE 16384
11
12 static ptls_key_exchange_algorithm_t *default_key_exchange[] = {
13 #ifdef PTLS_OPENSSL_HAVE_X25519
14   &ptls_openssl_x25519,
15 #endif
16 #ifdef PTLS_OPENSSL_HAVE_SECP256R1
17   &ptls_openssl_secp256r1,
18 #endif
19 #ifdef PTLS_OPENSSL_HAVE_SECP384R1
20   &ptls_openssl_secp384r1,
21 #endif
22 #ifdef PTLS_OPENSSL_HAVE_SECP521R1
23   &ptls_openssl_secp521r1
24 #endif
25 };
26
27 static u32
28 picotls_ctx_alloc (void)
29 {
30   u8 thread_id = vlib_get_thread_index ();
31   picotls_main_t *pm = &picotls_main;
32   picotls_ctx_t **ctx;
33
34   pool_get (pm->ctx_pool[thread_id], ctx);
35   if (!(*ctx))
36     *ctx = clib_mem_alloc (sizeof (picotls_ctx_t));
37
38   clib_memset (*ctx, 0, sizeof (picotls_ctx_t));
39   (*ctx)->ctx.c_thread_index = thread_id;
40   (*ctx)->ctx.tls_ctx_engine = CRYPTO_ENGINE_PICOTLS;
41   (*ctx)->ctx.app_session_handle = SESSION_INVALID_HANDLE;
42   (*ctx)->ptls_ctx_idx = ctx - pm->ctx_pool[thread_id];
43   return (*ctx)->ptls_ctx_idx;
44 }
45
46 static void
47 picotls_ctx_free (tls_ctx_t * ctx)
48 {
49   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
50   vec_free (ptls_ctx->rx_content);
51   vec_free (ptls_ctx->write_content);
52   pool_put_index (picotls_main.ctx_pool[ctx->c_thread_index],
53                   ptls_ctx->ptls_ctx_idx);
54 }
55
56 static u32
57 picotls_listen_ctx_alloc (void)
58 {
59   picotls_main_t *pm = &picotls_main;
60   picotls_listen_ctx_t *ptls_lctx;
61
62   pool_get (pm->lctx_pool, ptls_lctx);
63
64   clib_memset (ptls_lctx, 0, sizeof (picotls_listen_ctx_t));
65   ptls_lctx->ptls_lctx_index = ptls_lctx - pm->lctx_pool;
66   return ptls_lctx->ptls_lctx_index;
67 }
68
69 static void
70 picotls_listen_ctx_free (picotls_listen_ctx_t * lctx)
71 {
72   pool_put_index (picotls_main.lctx_pool, lctx->ptls_lctx_index);
73 }
74
75 tls_ctx_t *
76 picotls_ctx_get (u32 ctx_index)
77 {
78   picotls_ctx_t **ctx;
79   ctx =
80     pool_elt_at_index (picotls_main.ctx_pool[vlib_get_thread_index ()],
81                        ctx_index);
82   return &(*ctx)->ctx;
83 }
84
85 picotls_listen_ctx_t *
86 picotls_lctx_get (u32 lctx_index)
87 {
88   return pool_elt_at_index (picotls_main.lctx_pool, lctx_index);
89 }
90
91 static u8
92 picotls_handshake_is_over (tls_ctx_t * ctx)
93 {
94   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
95   assert (ptls_ctx->tls);
96   return ptls_handshake_is_complete (ptls_ctx->tls);
97 }
98
99 static int
100 picotls_try_handshake_write (picotls_ctx_t * ptls_ctx,
101                              session_t * tls_session, ptls_buffer_t * buf)
102 {
103   u32 enq_max, enq_now;
104   svm_fifo_t *f;
105   int write, buf_left;
106
107   if (buf->off <= 0)
108     return 0;
109
110   f = tls_session->tx_fifo;
111   buf_left = buf->off;
112   enq_max = svm_fifo_max_enqueue_prod (f);
113   if (!enq_max)
114     return 0;
115
116   enq_now = clib_min (svm_fifo_max_write_chunk (f), enq_max);
117   enq_now = clib_min (enq_now, buf_left);
118   write = svm_fifo_enqueue (f, enq_now, buf->base);
119   buf_left -= write;
120   tls_add_vpp_q_tx_evt (tls_session);
121   return write;
122 }
123
124 static int
125 picotls_start_listen (tls_ctx_t * lctx)
126 {
127   picotls_listen_ctx_t *ptls_lctx;
128   ptls_context_t *ptls_ctx;
129   u32 ptls_lctx_idx;
130   app_cert_key_pair_t *ckpair;
131
132   ckpair = app_cert_key_pair_get_if_valid (lctx->ckpair_index);
133   if (!ckpair || !ckpair->cert || !ckpair->key)
134     {
135       TLS_DBG (1, "tls cert and/or key not configured %d",
136                lctx->parent_app_wrk_index);
137       return -1;
138     }
139
140   ptls_lctx_idx = picotls_listen_ctx_alloc ();
141   ptls_lctx = picotls_lctx_get (ptls_lctx_idx);
142   ptls_ctx = malloc (sizeof (ptls_context_t));
143   ptls_lctx->ptls_ctx = ptls_ctx;
144
145   memset (ptls_ctx, 0, sizeof (ptls_context_t));
146   ptls_ctx->update_open_count = NULL;
147
148   /*
149    * Process certificate & private key.
150    */
151   load_bio_certificate_chain (ptls_ctx, (char *) ckpair->cert);
152   load_bio_private_key (ptls_ctx, (char *) ckpair->key);
153
154   /* setup protocol related functions */
155   ptls_ctx->key_exchanges = default_key_exchange;
156   ptls_ctx->random_bytes = ptls_openssl_random_bytes;
157   ptls_ctx->cipher_suites = ptls_vpp_crypto_cipher_suites;
158   ptls_ctx->get_time = &ptls_get_time;
159
160   lctx->tls_ssl_ctx = ptls_lctx_idx;
161
162   return 0;
163 }
164
165 static int
166 picotls_stop_listen (tls_ctx_t * lctx)
167 {
168   u32 ptls_lctx_index;
169   picotls_listen_ctx_t *ptls_lctx;
170
171   ptls_lctx_index = lctx->tls_ssl_ctx;
172   ptls_lctx = picotls_lctx_get (ptls_lctx_index);
173
174   picotls_listen_ctx_free (ptls_lctx);
175
176   return 0;
177 }
178
179 static void
180 picotls_handle_handshake_failure (tls_ctx_t * ctx)
181 {
182   session_free (session_get (ctx->c_s_index, ctx->c_thread_index));
183   ctx->no_app_session = 1;
184   ctx->c_s_index = SESSION_INVALID_INDEX;
185   tls_disconnect_transport (ctx);
186 }
187
188 static void
189 picotls_confirm_app_close (tls_ctx_t * ctx)
190 {
191   tls_disconnect_transport (ctx);
192   session_transport_closed_notify (&ctx->connection);
193 }
194
195 static int
196 picotls_transport_close (tls_ctx_t * ctx)
197 {
198   if (!picotls_handshake_is_over (ctx))
199     {
200       picotls_handle_handshake_failure (ctx);
201       return 0;
202     }
203   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
204   ptls_free (ptls_ctx->tls);
205   session_transport_closing_notify (&ctx->connection);
206   return 0;
207 }
208
209 static int
210 picotls_app_close (tls_ctx_t * ctx)
211 {
212   session_t *app_session;
213
214   app_session = session_get_from_handle (ctx->app_session_handle);
215   if (!svm_fifo_max_dequeue_cons (app_session->tx_fifo))
216     picotls_confirm_app_close (ctx);
217   else
218     ctx->app_closed = 1;
219
220   return 0;
221 }
222
223 static inline int
224 picotls_do_handshake (picotls_ctx_t *ptls_ctx, session_t *tcp_session)
225 {
226   int rv = PTLS_ERROR_IN_PROGRESS, write = 0, i = 0, read = 0, len;
227   svm_fifo_t *tcp_rx_fifo = tcp_session->rx_fifo;
228   ptls_buffer_t *buf = &ptls_ctx->read_buffer;
229   const int n_segs = 2, max_len = 16384;
230   ptls_t *tls = ptls_ctx->tls;
231   svm_fifo_seg_t fs[n_segs];
232   uword deq_now;
233
234   ptls_buffer_init (buf, "", 0);
235
236   len = svm_fifo_segments (tcp_rx_fifo, 0, fs, n_segs, max_len);
237   if (len <= 0)
238     return 0;
239
240   while (read < len && i < n_segs)
241     {
242       deq_now = fs[i].len;
243       rv = ptls_handshake (tls, buf, fs[i].data, &deq_now, NULL);
244
245       write += picotls_try_handshake_write (ptls_ctx, tcp_session, buf);
246       read += deq_now;
247
248       if (!(rv == 0 || rv == PTLS_ERROR_IN_PROGRESS))
249         {
250           clib_error ("unexpected error %u", rv);
251           break;
252         }
253
254       if (!rv)
255         break;
256
257       if (deq_now < fs[i].len)
258         {
259           fs[i].data += deq_now;
260           fs[i].len -= deq_now;
261         }
262       else
263         i++;
264     }
265
266   if (read)
267     svm_fifo_dequeue_drop (tcp_rx_fifo, read);
268
269   ptls_buffer_dispose (buf);
270
271   return write;
272 }
273
274 static inline int
275 picotls_ctx_read (tls_ctx_t *ctx, session_t *tcp_session)
276 {
277   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
278   ptls_buffer_t *buf = &ptls_ctx->read_buffer;
279   int off = 0, ret, i = 0, read = 0, len;
280   const int n_segs = 4, max_len = 32768;
281   svm_fifo_t *tcp_rx_fifo, *app_rx_fifo;
282   svm_fifo_seg_t fs[n_segs];
283   session_t *app_session;
284   uword deq_now;
285
286   if (PREDICT_FALSE (!ptls_handshake_is_complete (ptls_ctx->tls)))
287     {
288       picotls_do_handshake (ptls_ctx, tcp_session);
289       if (picotls_handshake_is_over (ctx))
290         {
291           if (ptls_is_server (ptls_ctx->tls))
292             {
293               if (tls_notify_app_accept (ctx))
294                 {
295                   ctx->c_s_index = SESSION_INVALID_INDEX;
296                   tls_disconnect_transport (ctx);
297                   return -1;
298                 }
299             }
300           else
301             {
302               tls_notify_app_connected (ctx, SESSION_E_NONE);
303             }
304         }
305
306       if (!svm_fifo_max_dequeue (tcp_session->rx_fifo))
307         return 0;
308     }
309
310   tcp_rx_fifo = tcp_session->rx_fifo;
311   app_session = session_get_from_handle (ctx->app_session_handle);
312   app_rx_fifo = app_session->rx_fifo;
313
314   if (TLS_READ_IS_LEFT (ptls_ctx))
315     goto do_enq;
316
317   len = svm_fifo_segments (tcp_rx_fifo, 0, fs, n_segs, max_len);
318   if (len <= 0)
319     goto final_checks;
320
321   ptls_buffer_init (buf, "", 0);
322   ptls_ctx->read_buffer_offset = 0;
323
324   while (read < len && i < n_segs)
325     {
326       deq_now = fs[i].len;
327       ret = ptls_receive (ptls_ctx->tls, buf, fs[i].data, &deq_now);
328       ASSERT (ret == 0 || ret == PTLS_ERROR_IN_PROGRESS);
329       read += deq_now;
330       if (deq_now < fs[i].len)
331         {
332           fs[i].data += deq_now;
333           fs[i].len -= deq_now;
334         }
335       else
336         i++;
337     }
338
339   if (read)
340     svm_fifo_dequeue_drop (tcp_rx_fifo, read);
341
342   if (!TLS_READ_LEFT_LEN (ptls_ctx))
343     {
344       ptls_buffer_dispose (buf);
345       goto final_checks;
346     }
347
348 do_enq:
349
350   len = TLS_READ_LEFT_LEN (ptls_ctx);
351   off = svm_fifo_enqueue (app_rx_fifo, len, TLS_READ_OFFSET (ptls_ctx));
352   if (off != len)
353     {
354       if (off < 0)
355         {
356           off = 0;
357           goto final_checks;
358         }
359       ptls_ctx->read_buffer_offset += off;
360     }
361   else
362     {
363       ptls_buffer_dispose (buf);
364     }
365
366   if (app_session->session_state >= SESSION_STATE_READY)
367     tls_notify_app_enqueue (ctx, app_session);
368
369 final_checks:
370
371   if (TLS_READ_IS_LEFT (ptls_ctx) || svm_fifo_max_dequeue (tcp_rx_fifo))
372     tls_add_vpp_q_builtin_rx_evt (tcp_session);
373
374   return off;
375 }
376
377 static inline int
378 picotls_content_process (picotls_ctx_t * ptls_ctx, svm_fifo_t * src_fifo,
379                          svm_fifo_t * dst_fifo, int content_len,
380                          int total_record_overhead, int is_no_copy)
381 {
382   ptls_buffer_t *buf = &ptls_ctx->write_buffer;
383   int total_length = content_len + total_record_overhead;
384   int to_dst_len;
385   if (is_no_copy)
386     {
387       ptls_buffer_init (buf, svm_fifo_tail (dst_fifo), total_length);
388       ptls_send (ptls_ctx->tls, buf, svm_fifo_head (src_fifo), content_len);
389
390       assert (!buf->is_allocated);
391       assert (buf->base == svm_fifo_tail (dst_fifo));
392
393       svm_fifo_dequeue_drop (src_fifo, content_len);
394       svm_fifo_enqueue_nocopy (dst_fifo, buf->off);
395       to_dst_len = buf->off;
396     }
397   else
398     {
399       assert (!TLS_WRITE_IS_LEFT (ptls_ctx));
400       vec_validate (ptls_ctx->write_content, total_length);
401       ptls_buffer_init (buf, ptls_ctx->write_content, total_length);
402
403       ptls_send (ptls_ctx->tls, buf, svm_fifo_head (src_fifo), content_len);
404       svm_fifo_dequeue_drop (src_fifo, content_len);
405
406       to_dst_len = svm_fifo_enqueue (dst_fifo, buf->off, buf->base);
407     }
408   ptls_ctx->write_buffer_offset += to_dst_len;
409   return to_dst_len;
410 }
411
412 static inline int
413 picotls_ctx_write (tls_ctx_t * ctx, session_t * app_session,
414                    transport_send_params_t * sp)
415 {
416   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
417   u32 deq_max, deq_now;
418   u32 enq_max, enq_now;
419   int from_app_len = 0, to_tls_len = 0, is_nocopy = 0;
420   svm_fifo_t *tls_tx_fifo, *app_tx_fifo;
421   session_t *tls_session;
422
423   int record_overhead = ptls_get_record_overhead (ptls_ctx->tls);
424   int num_records, total_overhead;
425
426   tls_session = session_get_from_handle (ctx->tls_session_handle);
427   tls_tx_fifo = tls_session->tx_fifo;
428   app_tx_fifo = app_session->tx_fifo;
429
430   if (PREDICT_FALSE (TLS_WRITE_IS_LEFT (ptls_ctx)))
431     {
432       enq_max = svm_fifo_max_enqueue_prod (tls_tx_fifo);
433       int to_write = clib_min (enq_max,
434                                ptls_ctx->write_buffer.off -
435                                ptls_ctx->write_buffer_offset);
436       to_tls_len =
437         svm_fifo_enqueue (tls_tx_fifo, to_write, TLS_WRITE_OFFSET (ptls_ctx));
438       if (to_tls_len < 0)
439         {
440           app_session->flags |= SESSION_F_CUSTOM_TX;
441           return 0;
442         }
443       ptls_ctx->write_buffer_offset += to_tls_len;
444
445       if (TLS_WRITE_IS_LEFT (ptls_ctx))
446         {
447           app_session->flags |= SESSION_F_CUSTOM_TX;
448           return to_tls_len;
449         }
450       else
451         {
452           ptls_buffer_init (&ptls_ctx->write_buffer, "", 0);
453           ptls_ctx->write_buffer_offset = 0;
454         }
455     }
456
457   deq_max = svm_fifo_max_dequeue_cons (app_tx_fifo);
458   if (!deq_max)
459     return deq_max;
460
461   deq_now = clib_min (deq_max, sp->max_burst_size);
462   deq_now = clib_min (deq_now, svm_fifo_max_read_chunk (app_tx_fifo));
463
464   enq_max = svm_fifo_max_enqueue_prod (tls_tx_fifo);
465     /** There is no engough enqueue space for one record **/
466   if (enq_max <= record_overhead)
467     {
468       app_session->flags |= SESSION_F_CUSTOM_TX;
469       return 0;
470     }
471
472   enq_now = clib_min (enq_max, svm_fifo_max_write_chunk (tls_tx_fifo));
473
474     /** Allowed to execute no-copy crypto operation **/
475   if (enq_now > record_overhead)
476     {
477       is_nocopy = 1;
478       from_app_len = clib_min (deq_now, enq_now);
479       num_records =
480         ceil ((f64) from_app_len / PTLS_MAX_PLAINTEXT_RECORD_SIZE);
481       total_overhead = num_records * record_overhead;
482       if (from_app_len + total_overhead > enq_now)
483         from_app_len = enq_now - total_overhead;
484     }
485   else
486     {
487       from_app_len = clib_min (deq_now, enq_max);
488       num_records =
489         ceil ((f64) from_app_len / PTLS_MAX_PLAINTEXT_RECORD_SIZE);
490       total_overhead = num_records * record_overhead;
491       if (from_app_len + total_overhead > enq_max)
492         from_app_len = enq_max - total_overhead;
493     }
494
495   to_tls_len =
496     picotls_content_process (ptls_ctx, app_tx_fifo, tls_tx_fifo,
497                              from_app_len, total_overhead, is_nocopy);
498   if (!TLS_WRITE_IS_LEFT (ptls_ctx))
499     {
500       ptls_ctx->write_buffer_offset = 0;
501       ptls_buffer_init (&ptls_ctx->write_buffer, "", 0);
502     }
503
504   if (svm_fifo_needs_deq_ntf (app_tx_fifo, from_app_len))
505     session_dequeue_notify (app_session);
506
507   if (to_tls_len)
508     tls_add_vpp_q_tx_evt (tls_session);
509
510   if (from_app_len < deq_max || TLS_WRITE_IS_LEFT (ptls_ctx))
511     app_session->flags |= SESSION_F_CUSTOM_TX;
512
513   if (ctx->app_closed)
514     picotls_app_close (ctx);
515
516   return to_tls_len;
517 }
518
519 static int
520 picotls_ctx_init_server (tls_ctx_t * ctx)
521 {
522   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
523   u32 ptls_lctx_idx = ctx->tls_ssl_ctx;
524   picotls_listen_ctx_t *ptls_lctx;
525
526   ptls_lctx = picotls_lctx_get (ptls_lctx_idx);
527   ptls_ctx->tls = ptls_new (ptls_lctx->ptls_ctx, 1);
528   if (ptls_ctx->tls == NULL)
529     {
530       TLS_DBG (1, "Failed to initialize ptls_ssl structure");
531       return -1;
532     }
533
534   ptls_ctx->rx_len = 0;
535   ptls_ctx->rx_offset = 0;
536
537   ptls_ctx->write_buffer_offset = 0;
538   return 0;
539 }
540
541 static int
542 picotls_ctx_init_client (tls_ctx_t *ctx)
543 {
544   picotls_ctx_t *ptls_ctx = (picotls_ctx_t *) ctx;
545   picotls_main_t *pm = &picotls_main;
546   ptls_context_t *client_ptls_ctx = pm->client_ptls_ctx;
547   ptls_handshake_properties_t hsprop = { { { { NULL } } } };
548
549   session_t *tls_session = session_get_from_handle (ctx->tls_session_handle);
550   ptls_buffer_t hs_buf;
551
552   ptls_ctx->tls = ptls_new (client_ptls_ctx, 0);
553   if (ptls_ctx->tls == NULL)
554     {
555       TLS_DBG (1, "Failed to initialize ptls_ssl structure");
556       return -1;
557     }
558
559   ptls_ctx->rx_len = 0;
560   ptls_ctx->rx_offset = 0;
561   ptls_ctx->write_buffer_offset = 0;
562
563   ptls_buffer_init (&hs_buf, "", 0);
564   if (ptls_handshake (ptls_ctx->tls, &hs_buf, NULL, NULL, &hsprop) !=
565       PTLS_ERROR_IN_PROGRESS)
566     {
567       TLS_DBG (1, "Failed to initialize tls connection");
568     }
569
570   picotls_try_handshake_write (ptls_ctx, tls_session, &hs_buf);
571
572   ptls_buffer_dispose (&hs_buf);
573
574   return 0;
575 }
576
577 tls_ctx_t *
578 picotls_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
579 {
580   picotls_ctx_t **ctx;
581   ctx = pool_elt_at_index (picotls_main.ctx_pool[thread_index], ctx_index);
582   return &(*ctx)->ctx;
583 }
584
585 int
586 picotls_init_client_ptls_ctx (ptls_context_t **client_ptls_ctx)
587 {
588   *client_ptls_ctx = clib_mem_alloc (sizeof (ptls_context_t));
589   memset (*client_ptls_ctx, 0, sizeof (ptls_context_t));
590
591   (*client_ptls_ctx)->update_open_count = NULL;
592   (*client_ptls_ctx)->key_exchanges = default_key_exchange;
593   (*client_ptls_ctx)->random_bytes = ptls_openssl_random_bytes;
594   (*client_ptls_ctx)->cipher_suites = ptls_vpp_crypto_cipher_suites;
595   (*client_ptls_ctx)->get_time = &ptls_get_time;
596
597   return 0;
598 }
599
600 const static tls_engine_vft_t picotls_engine = {
601   .ctx_alloc = picotls_ctx_alloc,
602   .ctx_free = picotls_ctx_free,
603   .ctx_get = picotls_ctx_get,
604   .ctx_get_w_thread = picotls_ctx_get_w_thread,
605   .ctx_handshake_is_over = picotls_handshake_is_over,
606   .ctx_start_listen = picotls_start_listen,
607   .ctx_stop_listen = picotls_stop_listen,
608   .ctx_init_server = picotls_ctx_init_server,
609   .ctx_init_client = picotls_ctx_init_client,
610   .ctx_read = picotls_ctx_read,
611   .ctx_write = picotls_ctx_write,
612   .ctx_transport_close = picotls_transport_close,
613   .ctx_app_close = picotls_app_close,
614 };
615
616 static clib_error_t *
617 tls_picotls_init (vlib_main_t * vm)
618 {
619   vlib_thread_main_t *vtm = vlib_get_thread_main ();
620   picotls_main_t *pm = &picotls_main;
621   clib_error_t *error = 0;
622   u32 num_threads;
623
624   num_threads = 1 + vtm->n_threads;
625
626   vec_validate (pm->ctx_pool, num_threads - 1);
627
628   clib_rwlock_init (&picotls_main.crypto_keys_rw_lock);
629
630   tls_register_engine (&picotls_engine, CRYPTO_ENGINE_PICOTLS);
631
632   picotls_init_client_ptls_ctx (&pm->client_ptls_ctx);
633
634   return error;
635 }
636
637 /* *INDENT-OFF* */
638 VLIB_INIT_FUNCTION (tls_picotls_init) = {
639   .runs_after = VLIB_INITS ("tls_init"),
640 };
641 /* *INDENT-ON* */
642
643 /* *INDENT-OFF* */
644 VLIB_PLUGIN_REGISTER () = {
645   .version = VPP_BUILD_VER,
646   .description = "Transport Layer Security (TLS) Engine, Picotls Based",
647 };
648 /* *INDENT-ON* */
649
650 /*
651  * fd.io coding-style-patch-verification: ON
652  *
653  * Local Variables:
654  * eval: (c-set-style "gnu")
655  * End:
656  */