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