wireguard: add processing of received cookie messages
[vpp.git] / src / plugins / wireguard / wireguard_input.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 #include <wireguard/wireguard.h>
21
22 #include <wireguard/wireguard_send.h>
23 #include <wireguard/wireguard_if.h>
24
25 #define foreach_wg_input_error                                                \
26   _ (NONE, "No error")                                                        \
27   _ (HANDSHAKE_MAC, "Invalid MAC handshake")                                  \
28   _ (PEER, "Peer error")                                                      \
29   _ (INTERFACE, "Interface error")                                            \
30   _ (DECRYPTION, "Failed during decryption")                                  \
31   _ (KEEPALIVE_SEND, "Failed while sending Keepalive")                        \
32   _ (HANDSHAKE_SEND, "Failed while sending Handshake")                        \
33   _ (HANDSHAKE_RECEIVE, "Failed while receiving Handshake")                   \
34   _ (COOKIE_DECRYPTION, "Failed during Cookie decryption")                    \
35   _ (TOO_BIG, "Packet too big")                                               \
36   _ (UNDEFINED, "Undefined error")                                            \
37   _ (CRYPTO_ENGINE_ERROR, "crypto engine error (packet dropped)")
38
39 typedef enum
40 {
41 #define _(sym,str) WG_INPUT_ERROR_##sym,
42   foreach_wg_input_error
43 #undef _
44     WG_INPUT_N_ERROR,
45 } wg_input_error_t;
46
47 static char *wg_input_error_strings[] = {
48 #define _(sym,string) string,
49   foreach_wg_input_error
50 #undef _
51 };
52
53 typedef struct
54 {
55   message_type_t type;
56   u16 current_length;
57   bool is_keepalive;
58   index_t peer;
59 } wg_input_trace_t;
60
61 typedef struct
62 {
63   index_t peer;
64   u16 next;
65 } wg_input_post_trace_t;
66
67 u8 *
68 format_wg_message_type (u8 * s, va_list * args)
69 {
70   message_type_t type = va_arg (*args, message_type_t);
71
72   switch (type)
73     {
74 #define _(v,a) case MESSAGE_##v: return (format (s, "%s", a));
75       foreach_wg_message_type
76 #undef _
77     }
78   return (format (s, "unknown"));
79 }
80
81 /* packet trace format function */
82 static u8 *
83 format_wg_input_trace (u8 * s, va_list * args)
84 {
85   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
86   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
87
88   wg_input_trace_t *t = va_arg (*args, wg_input_trace_t *);
89
90   s = format (s, "Wireguard input: \n");
91   s = format (s, "    Type: %U\n", format_wg_message_type, t->type);
92   s = format (s, "    Peer: %d\n", t->peer);
93   s = format (s, "    Length: %d\n", t->current_length);
94   s = format (s, "    Keepalive: %s", t->is_keepalive ? "true" : "false");
95
96   return s;
97 }
98
99 /* post-node packet trace format function */
100 static u8 *
101 format_wg_input_post_trace (u8 *s, va_list *args)
102 {
103   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
104   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
105
106   wg_input_post_trace_t *t = va_arg (*args, wg_input_post_trace_t *);
107
108   s = format (s, "WG input post: \n");
109   s = format (s, "  peer: %u\n", t->peer);
110   s = format (s, "  next: %u\n", t->next);
111
112   return s;
113 }
114
115 typedef enum
116 {
117   WG_INPUT_NEXT_HANDOFF_HANDSHAKE,
118   WG_INPUT_NEXT_HANDOFF_DATA,
119   WG_INPUT_NEXT_IP4_INPUT,
120   WG_INPUT_NEXT_IP6_INPUT,
121   WG_INPUT_NEXT_PUNT,
122   WG_INPUT_NEXT_ERROR,
123   WG_INPUT_N_NEXT,
124 } wg_input_next_t;
125
126 /* static void */
127 /* set_peer_address (wg_peer_t * peer, ip4_address_t ip4, u16 udp_port) */
128 /* { */
129 /*   if (peer) */
130 /*     { */
131 /*       ip46_address_set_ip4 (&peer->dst.addr, &ip4); */
132 /*       peer->dst.port = udp_port; */
133 /*     } */
134 /* } */
135
136 static u8
137 is_ip4_header (u8 *data)
138 {
139   return (data[0] >> 4) == 0x4;
140 }
141
142 static wg_input_error_t
143 wg_handshake_process (vlib_main_t *vm, wg_main_t *wmp, vlib_buffer_t *b,
144                       u32 node_idx, u8 is_ip4)
145 {
146   ASSERT (vm->thread_index == 0);
147
148   enum cookie_mac_state mac_state;
149   bool packet_needs_cookie;
150   bool under_load;
151   index_t *wg_ifs;
152   wg_if_t *wg_if;
153   wg_peer_t *peer = NULL;
154
155   void *current_b_data = vlib_buffer_get_current (b);
156
157   ip46_address_t src_ip;
158   if (is_ip4)
159     {
160       ip4_header_t *iph4 =
161         current_b_data - sizeof (udp_header_t) - sizeof (ip4_header_t);
162       ip46_address_set_ip4 (&src_ip, &iph4->src_address);
163     }
164   else
165     {
166       ip6_header_t *iph6 =
167         current_b_data - sizeof (udp_header_t) - sizeof (ip6_header_t);
168       ip46_address_set_ip6 (&src_ip, &iph6->src_address);
169     }
170
171   udp_header_t *uhd = current_b_data - sizeof (udp_header_t);
172   u16 udp_src_port = clib_host_to_net_u16 (uhd->src_port);;
173   u16 udp_dst_port = clib_host_to_net_u16 (uhd->dst_port);;
174
175   message_header_t *header = current_b_data;
176   under_load = false;
177
178   if (PREDICT_FALSE (header->type == MESSAGE_HANDSHAKE_COOKIE))
179     {
180       message_handshake_cookie_t *packet =
181         (message_handshake_cookie_t *) current_b_data;
182       u32 *entry =
183         wg_index_table_lookup (&wmp->index_table, packet->receiver_index);
184       if (entry)
185         peer = wg_peer_get (*entry);
186       else
187         return WG_INPUT_ERROR_PEER;
188
189       if (!cookie_maker_consume_payload (
190             vm, &peer->cookie_maker, packet->nonce, packet->encrypted_cookie))
191         return WG_INPUT_ERROR_COOKIE_DECRYPTION;
192
193       return WG_INPUT_ERROR_NONE;
194     }
195
196   u32 len = (header->type == MESSAGE_HANDSHAKE_INITIATION ?
197              sizeof (message_handshake_initiation_t) :
198              sizeof (message_handshake_response_t));
199
200   message_macs_t *macs = (message_macs_t *)
201     ((u8 *) current_b_data + len - sizeof (*macs));
202
203   index_t *ii;
204   wg_ifs = wg_if_indexes_get_by_port (udp_dst_port);
205   if (NULL == wg_ifs)
206     return WG_INPUT_ERROR_INTERFACE;
207
208   vec_foreach (ii, wg_ifs)
209     {
210       wg_if = wg_if_get (*ii);
211       if (NULL == wg_if)
212         continue;
213
214       mac_state = cookie_checker_validate_macs (
215         vm, &wg_if->cookie_checker, macs, current_b_data, len, under_load,
216         &src_ip, udp_src_port);
217       if (mac_state == INVALID_MAC)
218         {
219           wg_if = NULL;
220           continue;
221         }
222       break;
223     }
224
225   if (NULL == wg_if)
226     return WG_INPUT_ERROR_HANDSHAKE_MAC;
227
228   if ((under_load && mac_state == VALID_MAC_WITH_COOKIE)
229       || (!under_load && mac_state == VALID_MAC_BUT_NO_COOKIE))
230     packet_needs_cookie = false;
231   else if (under_load && mac_state == VALID_MAC_BUT_NO_COOKIE)
232     packet_needs_cookie = true;
233   else
234     return WG_INPUT_ERROR_HANDSHAKE_MAC;
235
236   switch (header->type)
237     {
238     case MESSAGE_HANDSHAKE_INITIATION:
239       {
240         message_handshake_initiation_t *message = current_b_data;
241
242         if (packet_needs_cookie)
243           {
244             // TODO: Add processing
245           }
246         noise_remote_t *rp;
247         if (noise_consume_initiation
248             (vm, noise_local_get (wg_if->local_idx), &rp,
249              message->sender_index, message->unencrypted_ephemeral,
250              message->encrypted_static, message->encrypted_timestamp))
251           {
252             peer = wg_peer_get (rp->r_peer_idx);
253           }
254         else
255           {
256             return WG_INPUT_ERROR_PEER;
257           }
258
259         // set_peer_address (peer, ip4_src, udp_src_port);
260         if (PREDICT_FALSE (!wg_send_handshake_response (vm, peer)))
261           {
262             vlib_node_increment_counter (vm, node_idx,
263                                          WG_INPUT_ERROR_HANDSHAKE_SEND, 1);
264           }
265         else
266           {
267             wg_peer_update_flags (rp->r_peer_idx, WG_PEER_ESTABLISHED, true);
268           }
269         break;
270       }
271     case MESSAGE_HANDSHAKE_RESPONSE:
272       {
273         message_handshake_response_t *resp = current_b_data;
274         index_t peeri = INDEX_INVALID;
275         u32 *entry =
276           wg_index_table_lookup (&wmp->index_table, resp->receiver_index);
277
278         if (PREDICT_TRUE (entry != NULL))
279           {
280             peeri = *entry;
281             peer = wg_peer_get (peeri);
282             if (wg_peer_is_dead (peer))
283               return WG_INPUT_ERROR_PEER;
284           }
285         else
286           return WG_INPUT_ERROR_PEER;
287
288         if (!noise_consume_response
289             (vm, &peer->remote, resp->sender_index,
290              resp->receiver_index, resp->unencrypted_ephemeral,
291              resp->encrypted_nothing))
292           {
293             return WG_INPUT_ERROR_PEER;
294           }
295         if (packet_needs_cookie)
296           {
297             // TODO: Add processing
298           }
299
300         // set_peer_address (peer, ip4_src, udp_src_port);
301         if (noise_remote_begin_session (vm, &peer->remote))
302           {
303
304             wg_timers_session_derived (peer);
305             wg_timers_handshake_complete (peer);
306             if (PREDICT_FALSE (!wg_send_keepalive (vm, peer)))
307               {
308                 vlib_node_increment_counter (vm, node_idx,
309                                              WG_INPUT_ERROR_KEEPALIVE_SEND, 1);
310               }
311             else
312               {
313                 wg_peer_update_flags (peeri, WG_PEER_ESTABLISHED, true);
314               }
315           }
316         break;
317       }
318     default:
319       return WG_INPUT_ERROR_HANDSHAKE_RECEIVE;
320     }
321
322   wg_timers_any_authenticated_packet_received (peer);
323   wg_timers_any_authenticated_packet_traversal (peer);
324   return WG_INPUT_ERROR_NONE;
325 }
326
327 static_always_inline int
328 wg_input_post_process (vlib_main_t *vm, vlib_buffer_t *b, u16 *next,
329                        wg_peer_t *peer, message_data_t *data,
330                        bool *is_keepalive)
331 {
332   next[0] = WG_INPUT_NEXT_PUNT;
333
334   noise_keypair_t *kp =
335     wg_get_active_keypair (&peer->remote, data->receiver_index);
336
337   if (!noise_counter_recv (&kp->kp_ctr, data->counter))
338     {
339       return -1;
340     }
341
342   u16 encr_len = b->current_length - sizeof (message_data_t);
343   u16 decr_len = encr_len - NOISE_AUTHTAG_LEN;
344
345   vlib_buffer_advance (b, sizeof (message_data_t));
346   b->current_length = decr_len;
347   vnet_buffer_offload_flags_clear (b, VNET_BUFFER_OFFLOAD_F_UDP_CKSUM);
348
349   /* Keepalive packet has zero length */
350   if (decr_len == 0)
351     {
352       *is_keepalive = true;
353       return -1;
354     }
355
356   wg_timers_data_received (peer);
357
358   ip46_address_t src_ip;
359   u8 is_ip4_inner = is_ip4_header (vlib_buffer_get_current (b));
360   if (is_ip4_inner)
361     {
362       ip46_address_set_ip4 (
363         &src_ip, &((ip4_header_t *) vlib_buffer_get_current (b))->src_address);
364     }
365   else
366     {
367       ip46_address_set_ip6 (
368         &src_ip, &((ip6_header_t *) vlib_buffer_get_current (b))->src_address);
369     }
370
371   const fib_prefix_t *allowed_ip;
372   bool allowed = false;
373
374   /*
375    * we could make this into an ACL, but the expectation
376    * is that there aren't many allowed IPs and thus a linear
377    * walk is faster than an ACL
378    */
379   vec_foreach (allowed_ip, peer->allowed_ips)
380     {
381       if (fib_prefix_is_cover_addr_46 (allowed_ip, &src_ip))
382         {
383           allowed = true;
384           break;
385         }
386     }
387   if (allowed)
388     {
389       vnet_buffer (b)->sw_if_index[VLIB_RX] = peer->wg_sw_if_index;
390       next[0] =
391         is_ip4_inner ? WG_INPUT_NEXT_IP4_INPUT : WG_INPUT_NEXT_IP6_INPUT;
392     }
393
394   return 0;
395 }
396
397 static_always_inline void
398 wg_input_process_ops (vlib_main_t *vm, vlib_node_runtime_t *node,
399                       vnet_crypto_op_t *ops, vlib_buffer_t *b[], u16 *nexts,
400                       u16 drop_next)
401 {
402   u32 n_fail, n_ops = vec_len (ops);
403   vnet_crypto_op_t *op = ops;
404
405   if (n_ops == 0)
406     return;
407
408   n_fail = n_ops - vnet_crypto_process_ops (vm, op, n_ops);
409
410   while (n_fail)
411     {
412       ASSERT (op - ops < n_ops);
413
414       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
415         {
416           u32 bi = op->user_data;
417           b[bi]->error = node->errors[WG_INPUT_ERROR_DECRYPTION];
418           nexts[bi] = drop_next;
419           n_fail--;
420         }
421       op++;
422     }
423 }
424
425 always_inline void
426 wg_prepare_sync_dec_op (vlib_main_t *vm, vnet_crypto_op_t **crypto_ops,
427                         u8 *src, u32 src_len, u8 *dst, u8 *aad, u32 aad_len,
428                         vnet_crypto_key_index_t key_index, u32 bi, u8 *iv)
429 {
430   vnet_crypto_op_t _op, *op = &_op;
431   u8 src_[] = {};
432
433   vec_add2_aligned (crypto_ops[0], op, 1, CLIB_CACHE_LINE_BYTES);
434   vnet_crypto_op_init (op, VNET_CRYPTO_OP_CHACHA20_POLY1305_DEC);
435
436   op->tag_len = NOISE_AUTHTAG_LEN;
437   op->tag = src + src_len;
438   op->src = !src ? src_ : src;
439   op->len = src_len;
440   op->dst = dst;
441   op->key_index = key_index;
442   op->aad = aad;
443   op->aad_len = aad_len;
444   op->iv = iv;
445   op->user_data = bi;
446   op->flags |= VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
447 }
448
449 static_always_inline void
450 wg_input_add_to_frame (vlib_main_t *vm, vnet_crypto_async_frame_t *f,
451                        u32 key_index, u32 crypto_len, i16 crypto_start_offset,
452                        u32 buffer_index, u16 next_node, u8 *iv, u8 *tag,
453                        u8 flags)
454 {
455   vnet_crypto_async_frame_elt_t *fe;
456   u16 index;
457
458   ASSERT (f->n_elts < VNET_CRYPTO_FRAME_SIZE);
459
460   index = f->n_elts;
461   fe = &f->elts[index];
462   f->n_elts++;
463   fe->key_index = key_index;
464   fe->crypto_total_length = crypto_len;
465   fe->crypto_start_offset = crypto_start_offset;
466   fe->iv = iv;
467   fe->tag = tag;
468   fe->flags = flags;
469   f->buffer_indices[index] = buffer_index;
470   f->next_node_index[index] = next_node;
471 }
472
473 static_always_inline enum noise_state_crypt
474 wg_input_process (vlib_main_t *vm, wg_per_thread_data_t *ptd,
475                   vnet_crypto_op_t **crypto_ops,
476                   vnet_crypto_async_frame_t **async_frame, vlib_buffer_t *b,
477                   u32 buf_idx, noise_remote_t *r, uint32_t r_idx,
478                   uint64_t nonce, uint8_t *src, size_t srclen, uint8_t *dst,
479                   u32 from_idx, u8 *iv, f64 time, u8 is_async,
480                   u16 async_next_node)
481 {
482   noise_keypair_t *kp;
483   enum noise_state_crypt ret = SC_FAILED;
484
485   if ((kp = wg_get_active_keypair (r, r_idx)) == NULL)
486     {
487       goto error;
488     }
489
490   /* We confirm that our values are within our tolerances. These values
491    * are the same as the encrypt routine.
492    *
493    * kp_ctr isn't locked here, we're happy to accept a racy read. */
494   if (wg_birthdate_has_expired_opt (kp->kp_birthdate, REJECT_AFTER_TIME,
495                                     time) ||
496       kp->kp_ctr.c_recv >= REJECT_AFTER_MESSAGES)
497     goto error;
498
499   /* Decrypt, then validate the counter. We don't want to validate the
500    * counter before decrypting as we do not know the message is authentic
501    * prior to decryption. */
502
503   clib_memset (iv, 0, 4);
504   clib_memcpy (iv + 4, &nonce, sizeof (nonce));
505
506   if (is_async)
507     {
508       if (NULL == *async_frame ||
509           vnet_crypto_async_frame_is_full (*async_frame))
510         {
511           *async_frame = vnet_crypto_async_get_frame (
512             vm, VNET_CRYPTO_OP_CHACHA20_POLY1305_TAG16_AAD0_DEC);
513           /* Save the frame to the list we'll submit at the end */
514           vec_add1 (ptd->async_frames, *async_frame);
515         }
516
517       wg_input_add_to_frame (vm, *async_frame, kp->kp_recv_index, srclen,
518                              src - b->data, buf_idx, async_next_node, iv,
519                              src + srclen, VNET_CRYPTO_OP_FLAG_HMAC_CHECK);
520     }
521   else
522     {
523       wg_prepare_sync_dec_op (vm, crypto_ops, src, srclen, dst, NULL, 0,
524                               kp->kp_recv_index, from_idx, iv);
525     }
526
527   /* If we've received the handshake confirming data packet then move the
528    * next keypair into current. If we do slide the next keypair in, then
529    * we skip the REKEY_AFTER_TIME_RECV check. This is safe to do as a
530    * data packet can't confirm a session that we are an INITIATOR of. */
531   if (kp == r->r_next)
532     {
533       clib_rwlock_writer_lock (&r->r_keypair_lock);
534       if (kp == r->r_next && kp->kp_local_index == r_idx)
535         {
536           noise_remote_keypair_free (vm, r, &r->r_previous);
537           r->r_previous = r->r_current;
538           r->r_current = r->r_next;
539           r->r_next = NULL;
540
541           ret = SC_CONN_RESET;
542           clib_rwlock_writer_unlock (&r->r_keypair_lock);
543           goto error;
544         }
545       clib_rwlock_writer_unlock (&r->r_keypair_lock);
546     }
547
548   /* Similar to when we encrypt, we want to notify the caller when we
549    * are approaching our tolerances. We notify if:
550    *  - we're the initiator and the current keypair is older than
551    *    REKEY_AFTER_TIME_RECV seconds. */
552   ret = SC_KEEP_KEY_FRESH;
553   kp = r->r_current;
554   if (kp != NULL && kp->kp_valid && kp->kp_is_initiator &&
555       wg_birthdate_has_expired_opt (kp->kp_birthdate, REKEY_AFTER_TIME_RECV,
556                                     time))
557     goto error;
558
559   ret = SC_OK;
560 error:
561   return ret;
562 }
563
564 always_inline uword
565 wg_input_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
566                  vlib_frame_t *frame, u8 is_ip4, u16 async_next_node)
567 {
568   vnet_main_t *vnm = vnet_get_main ();
569   vnet_interface_main_t *im = &vnm->interface_main;
570   wg_main_t *wmp = &wg_main;
571   wg_per_thread_data_t *ptd =
572     vec_elt_at_index (wmp->per_thread_data, vm->thread_index);
573   u32 *from = vlib_frame_vector_args (frame);
574   u32 n_left_from = frame->n_vectors;
575
576   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
577   u32 thread_index = vm->thread_index;
578   vnet_crypto_op_t **crypto_ops = &ptd->crypto_ops;
579   const u16 drop_next = WG_INPUT_NEXT_PUNT;
580   message_type_t header_type;
581   vlib_buffer_t *data_bufs[VLIB_FRAME_SIZE];
582   u32 data_bi[VLIB_FRAME_SIZE];  /* buffer index for data */
583   u32 other_bi[VLIB_FRAME_SIZE]; /* buffer index for drop or handoff */
584   u16 other_nexts[VLIB_FRAME_SIZE], *other_next = other_nexts, n_other = 0;
585   u16 data_nexts[VLIB_FRAME_SIZE], *data_next = data_nexts, n_data = 0;
586   u16 n_async = 0;
587   const u8 is_async = wg_op_mode_is_set_ASYNC ();
588   vnet_crypto_async_frame_t *async_frame = NULL;
589
590   vlib_get_buffers (vm, from, bufs, n_left_from);
591   vec_reset_length (ptd->crypto_ops);
592   vec_reset_length (ptd->async_frames);
593
594   f64 time = clib_time_now (&vm->clib_time) + vm->time_offset;
595
596   wg_peer_t *peer = NULL;
597   u32 *last_peer_time_idx = NULL;
598   u32 last_rec_idx = ~0;
599
600   bool is_keepalive = false;
601   u32 *peer_idx = NULL;
602
603   while (n_left_from > 0)
604     {
605       if (n_left_from > 2)
606         {
607           u8 *p;
608           vlib_prefetch_buffer_header (b[2], LOAD);
609           p = vlib_buffer_get_current (b[1]);
610           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
611           CLIB_PREFETCH (vlib_buffer_get_tail (b[1]), CLIB_CACHE_LINE_BYTES,
612                          LOAD);
613         }
614
615       other_next[n_other] = WG_INPUT_NEXT_PUNT;
616       data_nexts[n_data] = WG_INPUT_N_NEXT;
617
618       header_type =
619         ((message_header_t *) vlib_buffer_get_current (b[0]))->type;
620
621       if (PREDICT_TRUE (header_type == MESSAGE_DATA))
622         {
623           message_data_t *data = vlib_buffer_get_current (b[0]);
624           u8 *iv_data = b[0]->pre_data;
625           u32 buf_idx = from[b - bufs];
626           peer_idx = wg_index_table_lookup (&wmp->index_table,
627                                             data->receiver_index);
628
629           if (data->receiver_index != last_rec_idx)
630             {
631               peer_idx = wg_index_table_lookup (&wmp->index_table,
632                                                 data->receiver_index);
633               if (PREDICT_TRUE (peer_idx != NULL))
634                 {
635                   peer = wg_peer_get (*peer_idx);
636                 }
637               last_rec_idx = data->receiver_index;
638             }
639
640           if (PREDICT_FALSE (!peer_idx))
641             {
642               other_next[n_other] = WG_INPUT_NEXT_ERROR;
643               b[0]->error = node->errors[WG_INPUT_ERROR_PEER];
644               other_bi[n_other] = buf_idx;
645               n_other += 1;
646               goto out;
647             }
648
649           if (PREDICT_FALSE (~0 == peer->input_thread_index))
650             {
651               /* this is the first packet to use this peer, claim the peer
652                * for this thread.
653                */
654               clib_atomic_cmp_and_swap (&peer->input_thread_index, ~0,
655                                         wg_peer_assign_thread (thread_index));
656             }
657
658           if (PREDICT_TRUE (thread_index != peer->input_thread_index))
659             {
660               other_next[n_other] = WG_INPUT_NEXT_HANDOFF_DATA;
661               other_bi[n_other] = buf_idx;
662               n_other += 1;
663               goto next;
664             }
665
666           u16 encr_len = b[0]->current_length - sizeof (message_data_t);
667           u16 decr_len = encr_len - NOISE_AUTHTAG_LEN;
668           if (PREDICT_FALSE (decr_len >= WG_DEFAULT_DATA_SIZE))
669             {
670               b[0]->error = node->errors[WG_INPUT_ERROR_TOO_BIG];
671               other_bi[n_other] = buf_idx;
672               n_other += 1;
673               goto out;
674             }
675
676           enum noise_state_crypt state_cr = wg_input_process (
677             vm, ptd, crypto_ops, &async_frame, b[0], buf_idx, &peer->remote,
678             data->receiver_index, data->counter, data->encrypted_data,
679             decr_len, data->encrypted_data, n_data, iv_data, time, is_async,
680             async_next_node);
681
682           if (PREDICT_FALSE (state_cr == SC_FAILED))
683             {
684               wg_peer_update_flags (*peer_idx, WG_PEER_ESTABLISHED, false);
685               other_next[n_other] = WG_INPUT_NEXT_ERROR;
686               b[0]->error = node->errors[WG_INPUT_ERROR_DECRYPTION];
687               other_bi[n_other] = buf_idx;
688               n_other += 1;
689               goto out;
690             }
691           if (!is_async)
692             {
693               data_bufs[n_data] = b[0];
694               data_bi[n_data] = buf_idx;
695               n_data += 1;
696             }
697           else
698             {
699               n_async += 1;
700             }
701
702           if (PREDICT_FALSE (state_cr == SC_CONN_RESET))
703             {
704               wg_timers_handshake_complete (peer);
705               goto next;
706             }
707           else if (PREDICT_FALSE (state_cr == SC_KEEP_KEY_FRESH))
708             {
709               wg_send_handshake_from_mt (*peer_idx, false);
710               goto next;
711             }
712           else if (PREDICT_TRUE (state_cr == SC_OK))
713             goto next;
714         }
715       else
716         {
717           peer_idx = NULL;
718
719           /* Handshake packets should be processed in main thread */
720           if (thread_index != 0)
721             {
722               other_next[n_other] = WG_INPUT_NEXT_HANDOFF_HANDSHAKE;
723               other_bi[n_other] = from[b - bufs];
724               n_other += 1;
725               goto next;
726             }
727
728           wg_input_error_t ret =
729             wg_handshake_process (vm, wmp, b[0], node->node_index, is_ip4);
730           if (ret != WG_INPUT_ERROR_NONE)
731             {
732               other_next[n_other] = WG_INPUT_NEXT_ERROR;
733               b[0]->error = node->errors[ret];
734               other_bi[n_other] = from[b - bufs];
735               n_other += 1;
736             }
737           else
738             {
739               other_bi[n_other] = from[b - bufs];
740               n_other += 1;
741             }
742         }
743
744     out:
745       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
746                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
747         {
748           wg_input_trace_t *t = vlib_add_trace (vm, node, b[0], sizeof (*t));
749           t->type = header_type;
750           t->current_length = b[0]->current_length;
751           t->is_keepalive = is_keepalive;
752           t->peer = peer_idx ? *peer_idx : INDEX_INVALID;
753         }
754
755     next:
756       n_left_from -= 1;
757       b += 1;
758     }
759
760   /* decrypt packets */
761   wg_input_process_ops (vm, node, ptd->crypto_ops, data_bufs, data_nexts,
762                         drop_next);
763
764   /* process after decryption */
765   b = data_bufs;
766   n_left_from = n_data;
767   last_rec_idx = ~0;
768   last_peer_time_idx = NULL;
769
770   while (n_left_from > 0)
771     {
772       bool is_keepalive = false;
773       u32 *peer_idx = NULL;
774
775       if (PREDICT_FALSE (data_next[0] == WG_INPUT_NEXT_PUNT))
776         {
777           goto trace;
778         }
779       if (n_left_from > 2)
780         {
781           u8 *p;
782           vlib_prefetch_buffer_header (b[2], LOAD);
783           p = vlib_buffer_get_current (b[1]);
784           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
785           CLIB_PREFETCH (vlib_buffer_get_tail (b[1]), CLIB_CACHE_LINE_BYTES,
786                          LOAD);
787         }
788
789       message_data_t *data = vlib_buffer_get_current (b[0]);
790
791       if (data->receiver_index != last_rec_idx)
792         {
793           peer_idx =
794             wg_index_table_lookup (&wmp->index_table, data->receiver_index);
795           peer = wg_peer_get (*peer_idx);
796           last_rec_idx = data->receiver_index;
797         }
798
799       if (PREDICT_FALSE (wg_input_post_process (vm, b[0], data_next, peer,
800                                                 data, &is_keepalive) < 0))
801         goto trace;
802
803       if (PREDICT_FALSE (peer_idx && (last_peer_time_idx != peer_idx)))
804         {
805           wg_timers_any_authenticated_packet_received_opt (peer, time);
806           wg_timers_any_authenticated_packet_traversal (peer);
807           last_peer_time_idx = peer_idx;
808         }
809
810       vlib_increment_combined_counter (im->combined_sw_if_counters +
811                                          VNET_INTERFACE_COUNTER_RX,
812                                        vm->thread_index, peer->wg_sw_if_index,
813                                        1 /* packets */, b[0]->current_length);
814
815     trace:
816       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
817                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
818         {
819           wg_input_trace_t *t = vlib_add_trace (vm, node, b[0], sizeof (*t));
820           t->type = header_type;
821           t->current_length = b[0]->current_length;
822           t->is_keepalive = is_keepalive;
823           t->peer = peer_idx ? *peer_idx : INDEX_INVALID;
824         }
825
826       b += 1;
827       n_left_from -= 1;
828       data_next += 1;
829     }
830
831   if (n_async)
832     {
833       /* submit all of the open frames */
834       vnet_crypto_async_frame_t **async_frame;
835       vec_foreach (async_frame, ptd->async_frames)
836         {
837           if (PREDICT_FALSE (
838                 vnet_crypto_async_submit_open_frame (vm, *async_frame) < 0))
839             {
840               u32 n_drop = (*async_frame)->n_elts;
841               u32 *bi = (*async_frame)->buffer_indices;
842               u16 index = n_other;
843               while (n_drop--)
844                 {
845                   other_bi[index] = bi[0];
846                   vlib_buffer_t *b = vlib_get_buffer (vm, bi[0]);
847                   other_nexts[index] = drop_next;
848                   b->error = node->errors[WG_INPUT_ERROR_CRYPTO_ENGINE_ERROR];
849                   bi++;
850                   index++;
851                 }
852               n_other += (*async_frame)->n_elts;
853
854               vnet_crypto_async_reset_frame (*async_frame);
855               vnet_crypto_async_free_frame (vm, *async_frame);
856             }
857         }
858     }
859
860   /* enqueue other bufs */
861   if (n_other)
862     vlib_buffer_enqueue_to_next (vm, node, other_bi, other_next, n_other);
863
864   /* enqueue data bufs */
865   if (n_data)
866     vlib_buffer_enqueue_to_next (vm, node, data_bi, data_nexts, n_data);
867
868   return frame->n_vectors;
869 }
870
871 always_inline uword
872 wg_input_post (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
873 {
874   vnet_main_t *vnm = vnet_get_main ();
875   vnet_interface_main_t *im = &vnm->interface_main;
876   wg_main_t *wmp = &wg_main;
877   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
878   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
879   u32 *from = vlib_frame_vector_args (frame);
880   u32 n_left = frame->n_vectors;
881   wg_peer_t *peer = NULL;
882   u32 *peer_idx = NULL;
883   u32 *last_peer_time_idx = NULL;
884   u32 last_rec_idx = ~0;
885   f64 time = clib_time_now (&vm->clib_time) + vm->time_offset;
886
887   vlib_get_buffers (vm, from, b, n_left);
888
889   if (n_left >= 2)
890     {
891       vlib_prefetch_buffer_header (b[0], LOAD);
892       vlib_prefetch_buffer_header (b[1], LOAD);
893     }
894
895   while (n_left > 0)
896     {
897       if (n_left > 2)
898         {
899           u8 *p;
900           vlib_prefetch_buffer_header (b[2], LOAD);
901           p = vlib_buffer_get_current (b[1]);
902           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
903         }
904
905       bool is_keepalive = false;
906       message_data_t *data = vlib_buffer_get_current (b[0]);
907
908       if (data->receiver_index != last_rec_idx)
909         {
910           peer_idx =
911             wg_index_table_lookup (&wmp->index_table, data->receiver_index);
912
913           peer = wg_peer_get (*peer_idx);
914           last_rec_idx = data->receiver_index;
915         }
916
917       if (PREDICT_TRUE (peer != NULL))
918         {
919           if (PREDICT_FALSE (wg_input_post_process (vm, b[0], next, peer, data,
920                                                     &is_keepalive) < 0))
921             goto trace;
922         }
923       else
924         {
925           next[0] = WG_INPUT_NEXT_PUNT;
926           goto trace;
927         }
928
929       if (PREDICT_FALSE (peer_idx && (last_peer_time_idx != peer_idx)))
930         {
931           wg_timers_any_authenticated_packet_received_opt (peer, time);
932           wg_timers_any_authenticated_packet_traversal (peer);
933           last_peer_time_idx = peer_idx;
934         }
935
936       vlib_increment_combined_counter (im->combined_sw_if_counters +
937                                          VNET_INTERFACE_COUNTER_RX,
938                                        vm->thread_index, peer->wg_sw_if_index,
939                                        1 /* packets */, b[0]->current_length);
940
941     trace:
942       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
943                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
944         {
945           wg_input_post_trace_t *t =
946             vlib_add_trace (vm, node, b[0], sizeof (*t));
947           t->next = next[0];
948           t->peer = peer_idx ? *peer_idx : INDEX_INVALID;
949         }
950
951       b += 1;
952       next += 1;
953       n_left -= 1;
954     }
955
956   vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors);
957   return frame->n_vectors;
958 }
959
960 VLIB_NODE_FN (wg4_input_node)
961 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
962 {
963   return wg_input_inline (vm, node, frame, /* is_ip4 */ 1,
964                           wg_decrypt_async_next.wg4_post_next);
965 }
966
967 VLIB_NODE_FN (wg6_input_node)
968 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
969 {
970   return wg_input_inline (vm, node, frame, /* is_ip4 */ 0,
971                           wg_decrypt_async_next.wg6_post_next);
972 }
973
974 VLIB_NODE_FN (wg4_input_post_node)
975 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *from_frame)
976 {
977   return wg_input_post (vm, node, from_frame);
978 }
979
980 VLIB_NODE_FN (wg6_input_post_node)
981 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *from_frame)
982 {
983   return wg_input_post (vm, node, from_frame);
984 }
985
986 /* *INDENT-OFF* */
987 VLIB_REGISTER_NODE (wg4_input_node) =
988 {
989   .name = "wg4-input",
990   .vector_size = sizeof (u32),
991   .format_trace = format_wg_input_trace,
992   .type = VLIB_NODE_TYPE_INTERNAL,
993   .n_errors = ARRAY_LEN (wg_input_error_strings),
994   .error_strings = wg_input_error_strings,
995   .n_next_nodes = WG_INPUT_N_NEXT,
996   /* edit / add dispositions here */
997   .next_nodes = {
998         [WG_INPUT_NEXT_HANDOFF_HANDSHAKE] = "wg4-handshake-handoff",
999         [WG_INPUT_NEXT_HANDOFF_DATA] = "wg4-input-data-handoff",
1000         [WG_INPUT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1001         [WG_INPUT_NEXT_IP6_INPUT] = "ip6-input",
1002         [WG_INPUT_NEXT_PUNT] = "error-punt",
1003         [WG_INPUT_NEXT_ERROR] = "error-drop",
1004   },
1005 };
1006
1007 VLIB_REGISTER_NODE (wg6_input_node) =
1008 {
1009   .name = "wg6-input",
1010   .vector_size = sizeof (u32),
1011   .format_trace = format_wg_input_trace,
1012   .type = VLIB_NODE_TYPE_INTERNAL,
1013   .n_errors = ARRAY_LEN (wg_input_error_strings),
1014   .error_strings = wg_input_error_strings,
1015   .n_next_nodes = WG_INPUT_N_NEXT,
1016   /* edit / add dispositions here */
1017   .next_nodes = {
1018         [WG_INPUT_NEXT_HANDOFF_HANDSHAKE] = "wg6-handshake-handoff",
1019         [WG_INPUT_NEXT_HANDOFF_DATA] = "wg6-input-data-handoff",
1020         [WG_INPUT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1021         [WG_INPUT_NEXT_IP6_INPUT] = "ip6-input",
1022         [WG_INPUT_NEXT_PUNT] = "error-punt",
1023         [WG_INPUT_NEXT_ERROR] = "error-drop",
1024   },
1025 };
1026
1027 VLIB_REGISTER_NODE (wg4_input_post_node) = {
1028   .name = "wg4-input-post-node",
1029   .vector_size = sizeof (u32),
1030   .format_trace = format_wg_input_post_trace,
1031   .type = VLIB_NODE_TYPE_INTERNAL,
1032   .sibling_of = "wg4-input",
1033
1034   .n_errors = ARRAY_LEN (wg_input_error_strings),
1035   .error_strings = wg_input_error_strings,
1036 };
1037
1038 VLIB_REGISTER_NODE (wg6_input_post_node) = {
1039   .name = "wg6-input-post-node",
1040   .vector_size = sizeof (u32),
1041   .format_trace = format_wg_input_post_trace,
1042   .type = VLIB_NODE_TYPE_INTERNAL,
1043   .sibling_of = "wg6-input",
1044
1045   .n_errors = ARRAY_LEN (wg_input_error_strings),
1046   .error_strings = wg_input_error_strings,
1047 };
1048
1049 /* *INDENT-ON* */
1050
1051 /*
1052  * fd.io coding-style-patch-verification: ON
1053  *
1054  * Local Variables:
1055  * eval: (c-set-style "gnu")
1056  * End:
1057  */