wireguard: add support for chained buffers
[vpp.git] / src / plugins / wireguard / wireguard_output_tun.c
1 /*
2  * Copyright (c) 2020 Doc.ai and/or its affiliates.
3  * Copyright (c) 2020 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <vlib/vlib.h>
18 #include <vnet/vnet.h>
19 #include <vppinfra/error.h>
20
21 #include <wireguard/wireguard.h>
22 #include <wireguard/wireguard_send.h>
23
24 #define foreach_wg_output_error                                               \
25   _ (NONE, "No error")                                                        \
26   _ (PEER, "Peer error")                                                      \
27   _ (KEYPAIR, "Keypair error")                                                \
28   _ (NO_BUFFERS, "No buffers")                                                \
29   _ (CRYPTO_ENGINE_ERROR, "crypto engine error (packet dropped)")
30
31 typedef enum
32 {
33 #define _(sym,str) WG_OUTPUT_ERROR_##sym,
34   foreach_wg_output_error
35 #undef _
36     WG_OUTPUT_N_ERROR,
37 } wg_output_error_t;
38
39 static char *wg_output_error_strings[] = {
40 #define _(sym,string) string,
41   foreach_wg_output_error
42 #undef _
43 };
44
45 typedef enum
46 {
47   WG_OUTPUT_NEXT_ERROR,
48   WG_OUTPUT_NEXT_HANDOFF,
49   WG_OUTPUT_NEXT_INTERFACE_OUTPUT,
50   WG_OUTPUT_N_NEXT,
51 } wg_output_next_t;
52
53 typedef struct
54 {
55   index_t peer;
56   u8 header[sizeof (ip6_udp_header_t)];
57   u8 is_ip4;
58 } wg_output_tun_trace_t;
59
60 typedef struct
61 {
62   index_t peer;
63   u32 next_index;
64 } wg_output_tun_post_trace_t;
65
66 u8 *
67 format_ip4_udp_header (u8 * s, va_list * args)
68 {
69   ip4_udp_header_t *hdr4 = va_arg (*args, ip4_udp_header_t *);
70
71   s = format (s, "%U:$U", format_ip4_header, &hdr4->ip4, format_udp_header,
72               &hdr4->udp);
73   return (s);
74 }
75
76 u8 *
77 format_ip6_udp_header (u8 *s, va_list *args)
78 {
79   ip6_udp_header_t *hdr6 = va_arg (*args, ip6_udp_header_t *);
80
81   s = format (s, "%U:$U", format_ip6_header, &hdr6->ip6, format_udp_header,
82               &hdr6->udp);
83   return (s);
84 }
85
86 /* packet trace format function */
87 static u8 *
88 format_wg_output_tun_trace (u8 * s, va_list * args)
89 {
90   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
91   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
92
93   wg_output_tun_trace_t *t = va_arg (*args, wg_output_tun_trace_t *);
94
95   s = format (s, "peer: %d\n", t->peer);
96   s = format (s, "  Encrypted packet: ");
97
98   s = t->is_ip4 ? format (s, "%U", format_ip4_udp_header, t->header) :
99                   format (s, "%U", format_ip6_udp_header, t->header);
100   return s;
101 }
102
103 /* post node - packet trace format function */
104 static u8 *
105 format_wg_output_tun_post_trace (u8 *s, va_list *args)
106 {
107   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
108   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
109
110   wg_output_tun_post_trace_t *t = va_arg (*args, wg_output_tun_post_trace_t *);
111
112   s = format (s, "peer: %d\n", t->peer);
113   s = format (s, "  wg-post: next node index %u", t->next_index);
114   return s;
115 }
116
117 static_always_inline void
118 wg_output_chain_crypto (vlib_main_t *vm, wg_per_thread_data_t *ptd,
119                         vlib_buffer_t *b, vlib_buffer_t *lb, u8 *start,
120                         u32 start_len, u16 *n_ch)
121 {
122   vnet_crypto_op_chunk_t *ch;
123   vlib_buffer_t *cb = b;
124   u32 n_chunks = 1;
125
126   vec_add2 (ptd->chunks, ch, 1);
127   ch->len = start_len;
128   ch->src = ch->dst = start;
129   cb = vlib_get_buffer (vm, cb->next_buffer);
130
131   while (1)
132     {
133       vec_add2 (ptd->chunks, ch, 1);
134       n_chunks += 1;
135       if (lb == cb)
136         ch->len = cb->current_length - NOISE_AUTHTAG_LEN;
137       else
138         ch->len = cb->current_length;
139
140       ch->src = ch->dst = vlib_buffer_get_current (cb);
141
142       if (!(cb->flags & VLIB_BUFFER_NEXT_PRESENT))
143         break;
144
145       cb = vlib_get_buffer (vm, cb->next_buffer);
146     }
147
148   if (n_ch)
149     *n_ch = n_chunks;
150 }
151
152 static_always_inline void
153 wg_prepare_sync_enc_op (vlib_main_t *vm, wg_per_thread_data_t *ptd,
154                         vlib_buffer_t *b, vlib_buffer_t *lb,
155                         vnet_crypto_op_t **crypto_ops, u8 *src, u32 src_len,
156                         u8 *dst, u8 *aad, u32 aad_len, u64 nonce,
157                         vnet_crypto_key_index_t key_index, u32 bi, u8 *iv)
158 {
159   vnet_crypto_op_t _op, *op = &_op;
160   u8 src_[] = {};
161
162   clib_memset (iv, 0, 4);
163   clib_memcpy (iv + 4, &nonce, sizeof (nonce));
164
165   vec_add2_aligned (crypto_ops[0], op, 1, CLIB_CACHE_LINE_BYTES);
166   vnet_crypto_op_init (op, VNET_CRYPTO_OP_CHACHA20_POLY1305_ENC);
167
168   op->tag_len = NOISE_AUTHTAG_LEN;
169   op->tag = vlib_buffer_get_tail (lb) - NOISE_AUTHTAG_LEN;
170   op->key_index = key_index;
171   op->aad = aad;
172   op->aad_len = aad_len;
173   op->iv = iv;
174   op->user_data = bi;
175
176   if (b != lb)
177     {
178       /* Chained buffers */
179       op->flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
180       op->chunk_index = vec_len (ptd->chunks);
181       wg_output_chain_crypto (vm, ptd, b, lb, src, src_len, &op->n_chunks);
182     }
183   else
184     {
185       op->src = !src ? src_ : src;
186       op->len = src_len;
187       op->dst = dst;
188     }
189 }
190
191 static_always_inline void
192 wg_output_process_chained_ops (vlib_main_t *vm, vlib_node_runtime_t *node,
193                                vnet_crypto_op_t *ops, vlib_buffer_t *b[],
194                                u16 *nexts, vnet_crypto_op_chunk_t *chunks,
195                                u16 drop_next)
196 {
197   u32 n_fail, n_ops = vec_len (ops);
198   vnet_crypto_op_t *op = ops;
199
200   if (n_ops == 0)
201     return;
202
203   n_fail = n_ops - vnet_crypto_process_chained_ops (vm, op, chunks, n_ops);
204
205   while (n_fail)
206     {
207       ASSERT (op - ops < n_ops);
208
209       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
210         {
211           u32 bi = op->user_data;
212           b[bi]->error = node->errors[WG_OUTPUT_ERROR_CRYPTO_ENGINE_ERROR];
213           nexts[bi] = drop_next;
214           n_fail--;
215         }
216       op++;
217     }
218 }
219
220 static_always_inline void
221 wg_output_process_ops (vlib_main_t *vm, vlib_node_runtime_t *node,
222                        vnet_crypto_op_t *ops, vlib_buffer_t *b[], u16 *nexts,
223                        u16 drop_next)
224 {
225   u32 n_fail, n_ops = vec_len (ops);
226   vnet_crypto_op_t *op = ops;
227
228   if (n_ops == 0)
229     return;
230
231   n_fail = n_ops - vnet_crypto_process_ops (vm, op, n_ops);
232
233   while (n_fail)
234     {
235       ASSERT (op - ops < n_ops);
236
237       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
238         {
239           u32 bi = op->user_data;
240           b[bi]->error = node->errors[WG_OUTPUT_ERROR_CRYPTO_ENGINE_ERROR];
241           nexts[bi] = drop_next;
242           n_fail--;
243         }
244       op++;
245     }
246 }
247
248 static_always_inline void
249 wg_output_tun_add_to_frame (vlib_main_t *vm, vnet_crypto_async_frame_t *f,
250                             u32 key_index, u32 crypto_len,
251                             i16 crypto_start_offset, u32 buffer_index,
252                             u16 next_node, u8 *iv, u8 *tag, u8 flags)
253 {
254   vnet_crypto_async_frame_elt_t *fe;
255   u16 index;
256
257   ASSERT (f->n_elts < VNET_CRYPTO_FRAME_SIZE);
258
259   index = f->n_elts;
260   fe = &f->elts[index];
261   f->n_elts++;
262   fe->key_index = key_index;
263   fe->crypto_total_length = crypto_len;
264   fe->crypto_start_offset = crypto_start_offset;
265   fe->iv = iv;
266   fe->tag = tag;
267   fe->flags = flags;
268   f->buffer_indices[index] = buffer_index;
269   f->next_node_index[index] = next_node;
270 }
271
272 static_always_inline enum noise_state_crypt
273 wg_output_tun_process (vlib_main_t *vm, wg_per_thread_data_t *ptd,
274                        vlib_buffer_t *b, vlib_buffer_t *lb,
275                        vnet_crypto_op_t **crypto_ops, noise_remote_t *r,
276                        uint32_t *r_idx, uint64_t *nonce, uint8_t *src,
277                        size_t srclen, uint8_t *dst, u32 bi, u8 *iv, f64 time)
278 {
279   noise_keypair_t *kp;
280   enum noise_state_crypt ret = SC_FAILED;
281
282   if ((kp = r->r_current) == NULL)
283     goto error;
284
285   /* We confirm that our values are within our tolerances. We want:
286    *  - a valid keypair
287    *  - our keypair to be less than REJECT_AFTER_TIME seconds old
288    *  - our receive counter to be less than REJECT_AFTER_MESSAGES
289    *  - our send counter to be less than REJECT_AFTER_MESSAGES
290    */
291   if (!kp->kp_valid ||
292       wg_birthdate_has_expired_opt (kp->kp_birthdate, REJECT_AFTER_TIME,
293                                     time) ||
294       kp->kp_ctr.c_recv >= REJECT_AFTER_MESSAGES ||
295       ((*nonce = noise_counter_send (&kp->kp_ctr)) > REJECT_AFTER_MESSAGES))
296     goto error;
297
298   /* We encrypt into the same buffer, so the caller must ensure that buf
299    * has NOISE_AUTHTAG_LEN bytes to store the MAC. The nonce and index
300    * are passed back out to the caller through the provided data pointer. */
301   *r_idx = kp->kp_remote_index;
302
303   wg_prepare_sync_enc_op (vm, ptd, b, lb, crypto_ops, src, srclen, dst, NULL,
304                           0, *nonce, kp->kp_send_index, bi, iv);
305
306   /* If our values are still within tolerances, but we are approaching
307    * the tolerances, we notify the caller with ESTALE that they should
308    * establish a new keypair. The current keypair can continue to be used
309    * until the tolerances are hit. We notify if:
310    *  - our send counter is valid and not less than REKEY_AFTER_MESSAGES
311    *  - we're the initiator and our keypair is older than
312    *    REKEY_AFTER_TIME seconds */
313   ret = SC_KEEP_KEY_FRESH;
314   if ((kp->kp_valid && *nonce >= REKEY_AFTER_MESSAGES) ||
315       (kp->kp_is_initiator && wg_birthdate_has_expired_opt (
316                                 kp->kp_birthdate, REKEY_AFTER_TIME, time)))
317     goto error;
318
319   ret = SC_OK;
320 error:
321   return ret;
322 }
323
324 static_always_inline enum noise_state_crypt
325 wg_add_to_async_frame (vlib_main_t *vm, wg_per_thread_data_t *ptd,
326                        vnet_crypto_async_frame_t **async_frame,
327                        vlib_buffer_t *b, vlib_buffer_t *lb, u8 *payload,
328                        u32 payload_len, u32 bi, u16 next, u16 async_next,
329                        noise_remote_t *r, uint32_t *r_idx, uint64_t *nonce,
330                        u8 *iv, f64 time)
331 {
332   wg_post_data_t *post = wg_post_data (b);
333   u8 flag = 0;
334   u8 *tag;
335   noise_keypair_t *kp;
336
337   post->next_index = next;
338
339   /* crypto */
340   enum noise_state_crypt ret = SC_FAILED;
341
342   if ((kp = r->r_current) == NULL)
343     goto error;
344
345   /* We confirm that our values are within our tolerances. We want:
346    *  - a valid keypair
347    *  - our keypair to be less than REJECT_AFTER_TIME seconds old
348    *  - our receive counter to be less than REJECT_AFTER_MESSAGES
349    *  - our send counter to be less than REJECT_AFTER_MESSAGES
350    */
351   if (!kp->kp_valid ||
352       wg_birthdate_has_expired_opt (kp->kp_birthdate, REJECT_AFTER_TIME,
353                                     time) ||
354       kp->kp_ctr.c_recv >= REJECT_AFTER_MESSAGES ||
355       ((*nonce = noise_counter_send (&kp->kp_ctr)) > REJECT_AFTER_MESSAGES))
356     goto error;
357
358   /* We encrypt into the same buffer, so the caller must ensure that buf
359    * has NOISE_AUTHTAG_LEN bytes to store the MAC. The nonce and index
360    * are passed back out to the caller through the provided data pointer. */
361   *r_idx = kp->kp_remote_index;
362
363   clib_memset (iv, 0, 4);
364   clib_memcpy (iv + 4, nonce, sizeof (*nonce));
365
366   /* get a frame for this op if we don't yet have one or it's full  */
367   if (NULL == *async_frame || vnet_crypto_async_frame_is_full (*async_frame))
368     {
369       *async_frame = vnet_crypto_async_get_frame (
370         vm, VNET_CRYPTO_OP_CHACHA20_POLY1305_TAG16_AAD0_ENC);
371       /* Save the frame to the list we'll submit at the end */
372       vec_add1 (ptd->async_frames, *async_frame);
373     }
374
375   if (b != lb)
376     flag |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
377
378   tag = vlib_buffer_get_tail (lb) - NOISE_AUTHTAG_LEN;
379
380   /* this always succeeds because we know the frame is not full */
381   wg_output_tun_add_to_frame (vm, *async_frame, kp->kp_send_index, payload_len,
382                               payload - b->data, bi, async_next, iv, tag,
383                               flag);
384
385   /* If our values are still within tolerances, but we are approaching
386    * the tolerances, we notify the caller with ESTALE that they should
387    * establish a new keypair. The current keypair can continue to be used
388    * until the tolerances are hit. We notify if:
389    *  - our send counter is valid and not less than REKEY_AFTER_MESSAGES
390    *  - we're the initiator and our keypair is older than
391    *    REKEY_AFTER_TIME seconds */
392   ret = SC_KEEP_KEY_FRESH;
393   if ((kp->kp_valid && *nonce >= REKEY_AFTER_MESSAGES) ||
394       (kp->kp_is_initiator && wg_birthdate_has_expired_opt (
395                                 kp->kp_birthdate, REKEY_AFTER_TIME, time)))
396     goto error;
397
398   ret = SC_OK;
399 error:
400   return ret;
401 }
402
403 static_always_inline void
404 wg_calc_checksum (vlib_main_t *vm, vlib_buffer_t *b)
405 {
406   int bogus = 0;
407   u8 ip_ver_out = (*((u8 *) vlib_buffer_get_current (b)) >> 4);
408
409   /* IPv6 UDP checksum is mandatory */
410   if (ip_ver_out == 6)
411     {
412       ip6_header_t *ip6 =
413         (ip6_header_t *) ((u8 *) vlib_buffer_get_current (b));
414       udp_header_t *udp = ip6_next_header (ip6);
415       udp->checksum = ip6_tcp_udp_icmp_compute_checksum (vm, b, ip6, &bogus);
416     }
417 }
418
419 /* is_ip4 - inner header flag */
420 always_inline uword
421 wg_output_tun_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
422                       vlib_frame_t *frame, u8 is_ip4, u16 async_next_node)
423 {
424   wg_main_t *wmp = &wg_main;
425   wg_per_thread_data_t *ptd =
426     vec_elt_at_index (wmp->per_thread_data, vm->thread_index);
427   u32 *from = vlib_frame_vector_args (frame);
428   u32 n_left_from = frame->n_vectors;
429   ip4_udp_wg_header_t *hdr4_out = NULL;
430   ip6_udp_wg_header_t *hdr6_out = NULL;
431   message_data_t *message_data_wg = NULL;
432   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
433   vlib_buffer_t *lb;
434   vnet_crypto_op_t **crypto_ops;
435   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
436   vlib_buffer_t *sync_bufs[VLIB_FRAME_SIZE];
437   u32 thread_index = vm->thread_index;
438   u16 n_sync = 0;
439   const u16 drop_next = WG_OUTPUT_NEXT_ERROR;
440   const u8 is_async = wg_op_mode_is_set_ASYNC ();
441   vnet_crypto_async_frame_t *async_frame = NULL;
442   u16 n_async = 0;
443   u16 noop_nexts[VLIB_FRAME_SIZE], *noop_next = noop_nexts, n_noop = 0;
444   u16 err = !0;
445   u32 sync_bi[VLIB_FRAME_SIZE];
446   u32 noop_bi[VLIB_FRAME_SIZE];
447
448   vlib_get_buffers (vm, from, bufs, n_left_from);
449   vec_reset_length (ptd->crypto_ops);
450   vec_reset_length (ptd->chained_crypto_ops);
451   vec_reset_length (ptd->chunks);
452   vec_reset_length (ptd->async_frames);
453
454   wg_peer_t *peer = NULL;
455   u32 adj_index = 0;
456   u32 last_adj_index = ~0;
457   index_t peeri = INDEX_INVALID;
458
459   f64 time = clib_time_now (&vm->clib_time) + vm->time_offset;
460
461   while (n_left_from > 0)
462     {
463       u8 iph_offset = 0;
464       u8 is_ip4_out = 1;
465       u8 *plain_data;
466       u16 plain_data_len;
467       u16 plain_data_len_total;
468       u16 n_bufs;
469       u16 b_space_left_at_beginning;
470       u32 bi = from[b - bufs];
471
472       if (n_left_from > 2)
473         {
474           u8 *p;
475           vlib_prefetch_buffer_header (b[2], LOAD);
476           p = vlib_buffer_get_current (b[1]);
477           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
478           CLIB_PREFETCH (vlib_buffer_get_tail (b[1]), CLIB_CACHE_LINE_BYTES,
479                          LOAD);
480         }
481
482       noop_next[0] = WG_OUTPUT_NEXT_ERROR;
483       err = WG_OUTPUT_NEXT_ERROR;
484
485       adj_index = vnet_buffer (b[0])->ip.adj_index[VLIB_TX];
486
487       if (PREDICT_FALSE (last_adj_index != adj_index))
488         {
489           peeri = wg_peer_get_by_adj_index (adj_index);
490           if (peeri == INDEX_INVALID)
491             {
492               b[0]->error = node->errors[WG_OUTPUT_ERROR_PEER];
493               goto out;
494             }
495           peer = wg_peer_get (peeri);
496         }
497
498       if (!peer || wg_peer_is_dead (peer))
499         {
500           b[0]->error = node->errors[WG_OUTPUT_ERROR_PEER];
501           goto out;
502         }
503       if (PREDICT_FALSE (~0 == peer->output_thread_index))
504         {
505           /* this is the first packet to use this peer, claim the peer
506            * for this thread.
507            */
508           clib_atomic_cmp_and_swap (&peer->output_thread_index, ~0,
509                                     wg_peer_assign_thread (thread_index));
510         }
511
512       if (PREDICT_FALSE (thread_index != peer->output_thread_index))
513         {
514           noop_next[0] = WG_OUTPUT_NEXT_HANDOFF;
515           err = WG_OUTPUT_NEXT_HANDOFF;
516           goto next;
517         }
518
519       if (PREDICT_FALSE (!peer->remote.r_current))
520         {
521           wg_send_handshake_from_mt (peeri, false);
522           b[0]->error = node->errors[WG_OUTPUT_ERROR_KEYPAIR];
523           goto out;
524         }
525
526       lb = b[0];
527       n_bufs = vlib_buffer_chain_linearize (vm, b[0]);
528       if (n_bufs == 0)
529         {
530           b[0]->error = node->errors[WG_OUTPUT_ERROR_NO_BUFFERS];
531           goto out;
532         }
533
534       if (n_bufs > 1)
535         {
536           /* Find last buffer in the chain */
537           while (lb->flags & VLIB_BUFFER_NEXT_PRESENT)
538             lb = vlib_get_buffer (vm, lb->next_buffer);
539         }
540
541       /* Ensure there is enough free space at the beginning of the first buffer
542        * to write ethernet header (e.g. IPv6 VxLAN over IPv6 Wireguard will
543        * trigger this)
544        */
545       ASSERT ((signed) b[0]->current_data >=
546               (signed) -VLIB_BUFFER_PRE_DATA_SIZE);
547       b_space_left_at_beginning =
548         b[0]->current_data + VLIB_BUFFER_PRE_DATA_SIZE;
549       if (PREDICT_FALSE (b_space_left_at_beginning <
550                          sizeof (ethernet_header_t)))
551         {
552           u32 size_diff =
553             sizeof (ethernet_header_t) - b_space_left_at_beginning;
554
555           /* Can only move buffer when it's single and has enough free space*/
556           if (lb == b[0] &&
557               vlib_buffer_space_left_at_end (vm, b[0]) >= size_diff)
558             {
559               vlib_buffer_move (vm, b[0],
560                                 b[0]->current_data + (signed) size_diff);
561             }
562           else
563             {
564               b[0]->error = node->errors[WG_OUTPUT_ERROR_NO_BUFFERS];
565               goto out;
566             }
567         }
568
569       /*
570        * Ensure there is enough free space at the end of the last buffer to
571        * write auth tag */
572       if (PREDICT_FALSE (vlib_buffer_space_left_at_end (vm, lb) <
573                          NOISE_AUTHTAG_LEN))
574         {
575           u32 tmp_bi = 0;
576           if (vlib_buffer_alloc (vm, &tmp_bi, 1) != 1)
577             {
578               b[0]->error = node->errors[WG_OUTPUT_ERROR_NO_BUFFERS];
579               goto out;
580             }
581           lb = vlib_buffer_chain_buffer (vm, lb, tmp_bi);
582         }
583
584       iph_offset = vnet_buffer (b[0])->ip.save_rewrite_length;
585       plain_data = vlib_buffer_get_current (b[0]) + iph_offset;
586       plain_data_len = b[0]->current_length - iph_offset;
587       plain_data_len_total =
588         vlib_buffer_length_in_chain (vm, b[0]) - iph_offset;
589       size_t encrypted_packet_len = message_data_len (plain_data_len_total);
590       vlib_buffer_chain_increase_length (b[0], lb, NOISE_AUTHTAG_LEN);
591       u8 *iv_data = b[0]->pre_data;
592
593       is_ip4_out = ip46_address_is_ip4 (&peer->src.addr);
594       if (is_ip4_out)
595         {
596           hdr4_out = vlib_buffer_get_current (b[0]);
597           message_data_wg = &hdr4_out->wg;
598         }
599       else
600         {
601           hdr6_out = vlib_buffer_get_current (b[0]);
602           message_data_wg = &hdr6_out->wg;
603         }
604
605       if (PREDICT_FALSE (last_adj_index != adj_index))
606         {
607           wg_timers_any_authenticated_packet_sent_opt (peer, time);
608           wg_timers_data_sent_opt (peer, time);
609           wg_timers_any_authenticated_packet_traversal (peer);
610           last_adj_index = adj_index;
611         }
612
613       /* Here we are sure that can send packet to next node */
614       next[0] = WG_OUTPUT_NEXT_INTERFACE_OUTPUT;
615
616       if (lb != b[0])
617         crypto_ops = &ptd->chained_crypto_ops;
618       else
619         crypto_ops = &ptd->crypto_ops;
620
621       enum noise_state_crypt state;
622
623       if (is_async)
624         {
625           state = wg_add_to_async_frame (
626             vm, ptd, &async_frame, b[0], lb, plain_data, plain_data_len_total,
627             bi, next[0], async_next_node, &peer->remote,
628             &message_data_wg->receiver_index, &message_data_wg->counter,
629             iv_data, time);
630         }
631       else
632         {
633           state = wg_output_tun_process (
634             vm, ptd, b[0], lb, crypto_ops, &peer->remote,
635             &message_data_wg->receiver_index, &message_data_wg->counter,
636             plain_data, plain_data_len, plain_data, n_sync, iv_data, time);
637         }
638
639       if (PREDICT_FALSE (state == SC_KEEP_KEY_FRESH))
640         {
641           wg_send_handshake_from_mt (peeri, false);
642         }
643       else if (PREDICT_FALSE (state == SC_FAILED))
644         {
645           // TODO: Maybe wrong
646           wg_send_handshake_from_mt (peeri, false);
647           wg_peer_update_flags (peeri, WG_PEER_ESTABLISHED, false);
648           noop_next[0] = WG_OUTPUT_NEXT_ERROR;
649           goto out;
650         }
651
652       err = WG_OUTPUT_NEXT_INTERFACE_OUTPUT;
653
654       if (is_ip4_out)
655         {
656           hdr4_out->wg.header.type = MESSAGE_DATA;
657           hdr4_out->udp.length = clib_host_to_net_u16 (encrypted_packet_len +
658                                                        sizeof (udp_header_t));
659           ip4_header_set_len_w_chksum (
660             &hdr4_out->ip4, clib_host_to_net_u16 (encrypted_packet_len +
661                                                   sizeof (ip4_udp_header_t)));
662         }
663       else
664         {
665           hdr6_out->wg.header.type = MESSAGE_DATA;
666           hdr6_out->ip6.payload_length = hdr6_out->udp.length =
667             clib_host_to_net_u16 (encrypted_packet_len +
668                                   sizeof (udp_header_t));
669         }
670
671     out:
672       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
673                          && (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
674         {
675           wg_output_tun_trace_t *t =
676             vlib_add_trace (vm, node, b[0], sizeof (*t));
677
678           t->peer = peeri;
679           t->is_ip4 = is_ip4_out;
680           if (hdr4_out)
681             clib_memcpy (t->header, hdr4_out, sizeof (ip4_udp_header_t));
682           else if (hdr6_out)
683             clib_memcpy (t->header, hdr6_out, sizeof (ip6_udp_header_t));
684         }
685
686     next:
687       if (PREDICT_FALSE (err != WG_OUTPUT_NEXT_INTERFACE_OUTPUT))
688         {
689           noop_bi[n_noop] = bi;
690           n_noop++;
691           noop_next++;
692           goto next_left;
693         }
694       if (!is_async)
695         {
696           sync_bi[n_sync] = bi;
697           sync_bufs[n_sync] = b[0];
698           n_sync += 1;
699           next += 1;
700         }
701       else
702         {
703           n_async++;
704         }
705     next_left:
706       n_left_from -= 1;
707       b += 1;
708     }
709
710   if (n_sync)
711     {
712       /* wg-output-process-ops */
713       wg_output_process_ops (vm, node, ptd->crypto_ops, sync_bufs, nexts,
714                              drop_next);
715       wg_output_process_chained_ops (vm, node, ptd->chained_crypto_ops,
716                                      sync_bufs, nexts, ptd->chunks, drop_next);
717
718       int n_left_from_sync_bufs = n_sync;
719       while (n_left_from_sync_bufs > 0)
720         {
721           n_left_from_sync_bufs--;
722           wg_calc_checksum (vm, sync_bufs[n_left_from_sync_bufs]);
723         }
724
725       vlib_buffer_enqueue_to_next (vm, node, sync_bi, nexts, n_sync);
726     }
727   if (n_async)
728     {
729       /* submit all of the open frames */
730       vnet_crypto_async_frame_t **async_frame;
731
732       vec_foreach (async_frame, ptd->async_frames)
733         {
734           if (PREDICT_FALSE (
735                 vnet_crypto_async_submit_open_frame (vm, *async_frame) < 0))
736             {
737               u32 n_drop = (*async_frame)->n_elts;
738               u32 *bi = (*async_frame)->buffer_indices;
739               u16 index = n_noop;
740               while (n_drop--)
741                 {
742                   noop_bi[index] = bi[0];
743                   vlib_buffer_t *b = vlib_get_buffer (vm, bi[0]);
744                   noop_nexts[index] = drop_next;
745                   b->error = node->errors[WG_OUTPUT_ERROR_CRYPTO_ENGINE_ERROR];
746                   bi++;
747                   index++;
748                 }
749               n_noop += (*async_frame)->n_elts;
750
751               vnet_crypto_async_reset_frame (*async_frame);
752               vnet_crypto_async_free_frame (vm, *async_frame);
753             }
754         }
755     }
756   if (n_noop)
757     {
758       vlib_buffer_enqueue_to_next (vm, node, noop_bi, noop_nexts, n_noop);
759     }
760
761   return frame->n_vectors;
762 }
763
764 always_inline uword
765 wg_output_tun_post (vlib_main_t *vm, vlib_node_runtime_t *node,
766                     vlib_frame_t *frame)
767 {
768   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
769   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
770   u32 *from = vlib_frame_vector_args (frame);
771   u32 n_left = frame->n_vectors;
772
773   index_t peeri = ~0;
774
775   vlib_get_buffers (vm, from, b, n_left);
776
777   if (n_left >= 4)
778     {
779       vlib_prefetch_buffer_header (b[0], LOAD);
780       vlib_prefetch_buffer_header (b[1], LOAD);
781       vlib_prefetch_buffer_header (b[2], LOAD);
782       vlib_prefetch_buffer_header (b[3], LOAD);
783     }
784
785   while (n_left > 8)
786     {
787       vlib_prefetch_buffer_header (b[4], LOAD);
788       vlib_prefetch_buffer_header (b[5], LOAD);
789       vlib_prefetch_buffer_header (b[6], LOAD);
790       vlib_prefetch_buffer_header (b[7], LOAD);
791
792       next[0] = (wg_post_data (b[0]))->next_index;
793       next[1] = (wg_post_data (b[1]))->next_index;
794       next[2] = (wg_post_data (b[2]))->next_index;
795       next[3] = (wg_post_data (b[3]))->next_index;
796
797       wg_calc_checksum (vm, b[0]);
798       wg_calc_checksum (vm, b[1]);
799       wg_calc_checksum (vm, b[2]);
800       wg_calc_checksum (vm, b[3]);
801
802       if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE))
803         {
804           if (b[0]->flags & VLIB_BUFFER_IS_TRACED)
805             {
806               wg_output_tun_post_trace_t *tr =
807                 vlib_add_trace (vm, node, b[0], sizeof (*tr));
808               peeri = wg_peer_get_by_adj_index (
809                 vnet_buffer (b[0])->ip.adj_index[VLIB_TX]);
810               tr->peer = peeri;
811               tr->next_index = next[0];
812             }
813           if (b[1]->flags & VLIB_BUFFER_IS_TRACED)
814             {
815               wg_output_tun_post_trace_t *tr =
816                 vlib_add_trace (vm, node, b[1], sizeof (*tr));
817               peeri = wg_peer_get_by_adj_index (
818                 vnet_buffer (b[1])->ip.adj_index[VLIB_TX]);
819               tr->next_index = next[1];
820             }
821           if (b[2]->flags & VLIB_BUFFER_IS_TRACED)
822             {
823               wg_output_tun_post_trace_t *tr =
824                 vlib_add_trace (vm, node, b[2], sizeof (*tr));
825               peeri = wg_peer_get_by_adj_index (
826                 vnet_buffer (b[2])->ip.adj_index[VLIB_TX]);
827               tr->next_index = next[2];
828             }
829           if (b[3]->flags & VLIB_BUFFER_IS_TRACED)
830             {
831               wg_output_tun_post_trace_t *tr =
832                 vlib_add_trace (vm, node, b[3], sizeof (*tr));
833               peeri = wg_peer_get_by_adj_index (
834                 vnet_buffer (b[3])->ip.adj_index[VLIB_TX]);
835               tr->next_index = next[3];
836             }
837         }
838
839       b += 4;
840       next += 4;
841       n_left -= 4;
842     }
843
844   while (n_left > 0)
845     {
846       wg_calc_checksum (vm, b[0]);
847
848       next[0] = (wg_post_data (b[0]))->next_index;
849       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
850                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
851         {
852           wg_output_tun_post_trace_t *tr =
853             vlib_add_trace (vm, node, b[0], sizeof (*tr));
854           peeri = wg_peer_get_by_adj_index (
855             vnet_buffer (b[0])->ip.adj_index[VLIB_TX]);
856           tr->next_index = next[0];
857         }
858
859       b += 1;
860       next += 1;
861       n_left -= 1;
862     }
863
864   vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors);
865   return frame->n_vectors;
866 }
867
868 VLIB_REGISTER_NODE (wg4_output_tun_post_node) = {
869   .name = "wg4-output-tun-post-node",
870   .vector_size = sizeof (u32),
871   .format_trace = format_wg_output_tun_post_trace,
872   .type = VLIB_NODE_TYPE_INTERNAL,
873   .sibling_of = "wg4-output-tun",
874   .n_errors = ARRAY_LEN (wg_output_error_strings),
875   .error_strings = wg_output_error_strings,
876 };
877
878 VLIB_REGISTER_NODE (wg6_output_tun_post_node) = {
879   .name = "wg6-output-tun-post-node",
880   .vector_size = sizeof (u32),
881   .format_trace = format_wg_output_tun_post_trace,
882   .type = VLIB_NODE_TYPE_INTERNAL,
883   .sibling_of = "wg6-output-tun",
884   .n_errors = ARRAY_LEN (wg_output_error_strings),
885   .error_strings = wg_output_error_strings,
886 };
887
888 VLIB_NODE_FN (wg4_output_tun_post_node)
889 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *from_frame)
890 {
891   return wg_output_tun_post (vm, node, from_frame);
892 }
893
894 VLIB_NODE_FN (wg6_output_tun_post_node)
895 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *from_frame)
896 {
897   return wg_output_tun_post (vm, node, from_frame);
898 }
899
900 VLIB_NODE_FN (wg4_output_tun_node)
901 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
902 {
903   return wg_output_tun_inline (vm, node, frame, /* is_ip4 */ 1,
904                                wg_encrypt_async_next.wg4_post_next);
905 }
906
907 VLIB_NODE_FN (wg6_output_tun_node)
908 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
909 {
910   return wg_output_tun_inline (vm, node, frame, /* is_ip4 */ 0,
911                                wg_encrypt_async_next.wg6_post_next);
912 }
913
914 /* *INDENT-OFF* */
915 VLIB_REGISTER_NODE (wg4_output_tun_node) =
916 {
917   .name = "wg4-output-tun",
918   .vector_size = sizeof (u32),
919   .format_trace = format_wg_output_tun_trace,
920   .type = VLIB_NODE_TYPE_INTERNAL,
921   .n_errors = ARRAY_LEN (wg_output_error_strings),
922   .error_strings = wg_output_error_strings,
923   .n_next_nodes = WG_OUTPUT_N_NEXT,
924   .next_nodes = {
925         [WG_OUTPUT_NEXT_HANDOFF] = "wg4-output-tun-handoff",
926         [WG_OUTPUT_NEXT_INTERFACE_OUTPUT] = "adj-midchain-tx",
927         [WG_OUTPUT_NEXT_ERROR] = "error-drop",
928   },
929 };
930
931 VLIB_REGISTER_NODE (wg6_output_tun_node) =
932 {
933   .name = "wg6-output-tun",
934   .vector_size = sizeof (u32),
935   .format_trace = format_wg_output_tun_trace,
936   .type = VLIB_NODE_TYPE_INTERNAL,
937   .n_errors = ARRAY_LEN (wg_output_error_strings),
938   .error_strings = wg_output_error_strings,
939   .n_next_nodes = WG_OUTPUT_N_NEXT,
940   .next_nodes = {
941         [WG_OUTPUT_NEXT_HANDOFF] = "wg6-output-tun-handoff",
942         [WG_OUTPUT_NEXT_INTERFACE_OUTPUT] = "adj-midchain-tx",
943         [WG_OUTPUT_NEXT_ERROR] = "error-drop",
944   },
945 };
946 /* *INDENT-ON* */
947
948 /*
949  * fd.io coding-style-patch-verification: ON
950  *
951  * Local Variables:
952  * eval: (c-set-style "gnu")
953  * End:
954  */