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