777f0ec54b3558effa29f9c1e4b9df1d78a7bc86
[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   noise_keypair_t *kp;
347
348   if ((kp = wg_get_active_keypair (&peer->remote, data->receiver_index)) ==
349       NULL)
350     return -1;
351
352   if (!noise_counter_recv (&kp->kp_ctr, data->counter))
353     {
354       return -1;
355     }
356
357   u16 encr_len = b->current_length - sizeof (message_data_t);
358   u16 decr_len = encr_len - NOISE_AUTHTAG_LEN;
359
360   vlib_buffer_advance (b, sizeof (message_data_t));
361   b->current_length = decr_len;
362   vnet_buffer_offload_flags_clear (b, VNET_BUFFER_OFFLOAD_F_UDP_CKSUM);
363
364   /* Keepalive packet has zero length */
365   if (decr_len == 0)
366     {
367       *is_keepalive = true;
368       return -1;
369     }
370
371   wg_timers_data_received (peer);
372
373   ip46_address_t src_ip;
374   u8 is_ip4_inner = is_ip4_header (vlib_buffer_get_current (b));
375   if (is_ip4_inner)
376     {
377       ip46_address_set_ip4 (
378         &src_ip, &((ip4_header_t *) vlib_buffer_get_current (b))->src_address);
379     }
380   else
381     {
382       ip46_address_set_ip6 (
383         &src_ip, &((ip6_header_t *) vlib_buffer_get_current (b))->src_address);
384     }
385
386   const fib_prefix_t *allowed_ip;
387   bool allowed = false;
388
389   /*
390    * we could make this into an ACL, but the expectation
391    * is that there aren't many allowed IPs and thus a linear
392    * walk is faster than an ACL
393    */
394   vec_foreach (allowed_ip, peer->allowed_ips)
395     {
396       if (fib_prefix_is_cover_addr_46 (allowed_ip, &src_ip))
397         {
398           allowed = true;
399           break;
400         }
401     }
402   if (allowed)
403     {
404       vnet_buffer (b)->sw_if_index[VLIB_RX] = peer->wg_sw_if_index;
405       next[0] =
406         is_ip4_inner ? WG_INPUT_NEXT_IP4_INPUT : WG_INPUT_NEXT_IP6_INPUT;
407     }
408
409   return 0;
410 }
411
412 static_always_inline void
413 wg_input_process_ops (vlib_main_t *vm, vlib_node_runtime_t *node,
414                       vnet_crypto_op_t *ops, vlib_buffer_t *b[], u16 *nexts,
415                       u16 drop_next)
416 {
417   u32 n_fail, n_ops = vec_len (ops);
418   vnet_crypto_op_t *op = ops;
419
420   if (n_ops == 0)
421     return;
422
423   n_fail = n_ops - vnet_crypto_process_ops (vm, op, n_ops);
424
425   while (n_fail)
426     {
427       ASSERT (op - ops < n_ops);
428
429       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
430         {
431           u32 bi = op->user_data;
432           b[bi]->error = node->errors[WG_INPUT_ERROR_DECRYPTION];
433           nexts[bi] = drop_next;
434           n_fail--;
435         }
436       op++;
437     }
438 }
439
440 always_inline void
441 wg_prepare_sync_dec_op (vlib_main_t *vm, vnet_crypto_op_t **crypto_ops,
442                         u8 *src, u32 src_len, u8 *dst, u8 *aad, u32 aad_len,
443                         vnet_crypto_key_index_t key_index, u32 bi, u8 *iv)
444 {
445   vnet_crypto_op_t _op, *op = &_op;
446   u8 src_[] = {};
447
448   vec_add2_aligned (crypto_ops[0], op, 1, CLIB_CACHE_LINE_BYTES);
449   vnet_crypto_op_init (op, VNET_CRYPTO_OP_CHACHA20_POLY1305_DEC);
450
451   op->tag_len = NOISE_AUTHTAG_LEN;
452   op->tag = src + src_len;
453   op->src = !src ? src_ : src;
454   op->len = src_len;
455   op->dst = dst;
456   op->key_index = key_index;
457   op->aad = aad;
458   op->aad_len = aad_len;
459   op->iv = iv;
460   op->user_data = bi;
461   op->flags |= VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
462 }
463
464 static_always_inline void
465 wg_input_add_to_frame (vlib_main_t *vm, vnet_crypto_async_frame_t *f,
466                        u32 key_index, u32 crypto_len, i16 crypto_start_offset,
467                        u32 buffer_index, u16 next_node, u8 *iv, u8 *tag,
468                        u8 flags)
469 {
470   vnet_crypto_async_frame_elt_t *fe;
471   u16 index;
472
473   ASSERT (f->n_elts < VNET_CRYPTO_FRAME_SIZE);
474
475   index = f->n_elts;
476   fe = &f->elts[index];
477   f->n_elts++;
478   fe->key_index = key_index;
479   fe->crypto_total_length = crypto_len;
480   fe->crypto_start_offset = crypto_start_offset;
481   fe->iv = iv;
482   fe->tag = tag;
483   fe->flags = flags;
484   f->buffer_indices[index] = buffer_index;
485   f->next_node_index[index] = next_node;
486 }
487
488 static_always_inline enum noise_state_crypt
489 wg_input_process (vlib_main_t *vm, wg_per_thread_data_t *ptd,
490                   vnet_crypto_op_t **crypto_ops,
491                   vnet_crypto_async_frame_t **async_frame, vlib_buffer_t *b,
492                   u32 buf_idx, noise_remote_t *r, uint32_t r_idx,
493                   uint64_t nonce, uint8_t *src, size_t srclen, uint8_t *dst,
494                   u32 from_idx, u8 *iv, f64 time, u8 is_async,
495                   u16 async_next_node)
496 {
497   noise_keypair_t *kp;
498   enum noise_state_crypt ret = SC_FAILED;
499
500   if ((kp = wg_get_active_keypair (r, r_idx)) == NULL)
501     {
502       goto error;
503     }
504
505   /* We confirm that our values are within our tolerances. These values
506    * are the same as the encrypt routine.
507    *
508    * kp_ctr isn't locked here, we're happy to accept a racy read. */
509   if (wg_birthdate_has_expired_opt (kp->kp_birthdate, REJECT_AFTER_TIME,
510                                     time) ||
511       kp->kp_ctr.c_recv >= REJECT_AFTER_MESSAGES)
512     goto error;
513
514   /* Decrypt, then validate the counter. We don't want to validate the
515    * counter before decrypting as we do not know the message is authentic
516    * prior to decryption. */
517
518   clib_memset (iv, 0, 4);
519   clib_memcpy (iv + 4, &nonce, sizeof (nonce));
520
521   if (is_async)
522     {
523       if (NULL == *async_frame ||
524           vnet_crypto_async_frame_is_full (*async_frame))
525         {
526           *async_frame = vnet_crypto_async_get_frame (
527             vm, VNET_CRYPTO_OP_CHACHA20_POLY1305_TAG16_AAD0_DEC);
528           /* Save the frame to the list we'll submit at the end */
529           vec_add1 (ptd->async_frames, *async_frame);
530         }
531
532       wg_input_add_to_frame (vm, *async_frame, kp->kp_recv_index, srclen,
533                              src - b->data, buf_idx, async_next_node, iv,
534                              src + srclen, VNET_CRYPTO_OP_FLAG_HMAC_CHECK);
535     }
536   else
537     {
538       wg_prepare_sync_dec_op (vm, crypto_ops, src, srclen, dst, NULL, 0,
539                               kp->kp_recv_index, from_idx, iv);
540     }
541
542   /* If we've received the handshake confirming data packet then move the
543    * next keypair into current. If we do slide the next keypair in, then
544    * we skip the REKEY_AFTER_TIME_RECV check. This is safe to do as a
545    * data packet can't confirm a session that we are an INITIATOR of. */
546   if (kp == r->r_next)
547     {
548       clib_rwlock_writer_lock (&r->r_keypair_lock);
549       if (kp == r->r_next && kp->kp_local_index == r_idx)
550         {
551           noise_remote_keypair_free (vm, r, &r->r_previous);
552           r->r_previous = r->r_current;
553           r->r_current = r->r_next;
554           r->r_next = NULL;
555
556           ret = SC_CONN_RESET;
557           clib_rwlock_writer_unlock (&r->r_keypair_lock);
558           goto error;
559         }
560       clib_rwlock_writer_unlock (&r->r_keypair_lock);
561     }
562
563   /* Similar to when we encrypt, we want to notify the caller when we
564    * are approaching our tolerances. We notify if:
565    *  - we're the initiator and the current keypair is older than
566    *    REKEY_AFTER_TIME_RECV seconds. */
567   ret = SC_KEEP_KEY_FRESH;
568   kp = r->r_current;
569   if (kp != NULL && kp->kp_valid && kp->kp_is_initiator &&
570       wg_birthdate_has_expired_opt (kp->kp_birthdate, REKEY_AFTER_TIME_RECV,
571                                     time))
572     goto error;
573
574   ret = SC_OK;
575 error:
576   return ret;
577 }
578
579 static_always_inline void
580 wg_find_outer_addr_port (vlib_buffer_t *b, ip46_address_t *addr, u16 *port,
581                          u8 is_ip4)
582 {
583   if (is_ip4)
584     {
585       ip4_udp_header_t *ip4_udp_hdr =
586         vlib_buffer_get_current (b) - sizeof (ip4_udp_header_t);
587       ip46_address_set_ip4 (addr, &ip4_udp_hdr->ip4.src_address);
588       *port = clib_net_to_host_u16 (ip4_udp_hdr->udp.src_port);
589     }
590   else
591     {
592       ip6_udp_header_t *ip6_udp_hdr =
593         vlib_buffer_get_current (b) - sizeof (ip6_udp_header_t);
594       ip46_address_set_ip6 (addr, &ip6_udp_hdr->ip6.src_address);
595       *port = clib_net_to_host_u16 (ip6_udp_hdr->udp.src_port);
596     }
597 }
598
599 always_inline uword
600 wg_input_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
601                  vlib_frame_t *frame, u8 is_ip4, u16 async_next_node)
602 {
603   vnet_main_t *vnm = vnet_get_main ();
604   vnet_interface_main_t *im = &vnm->interface_main;
605   wg_main_t *wmp = &wg_main;
606   wg_per_thread_data_t *ptd =
607     vec_elt_at_index (wmp->per_thread_data, vm->thread_index);
608   u32 *from = vlib_frame_vector_args (frame);
609   u32 n_left_from = frame->n_vectors;
610
611   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
612   u32 thread_index = vm->thread_index;
613   vnet_crypto_op_t **crypto_ops = &ptd->crypto_ops;
614   const u16 drop_next = WG_INPUT_NEXT_PUNT;
615   message_type_t header_type;
616   vlib_buffer_t *data_bufs[VLIB_FRAME_SIZE];
617   u32 data_bi[VLIB_FRAME_SIZE];  /* buffer index for data */
618   u32 other_bi[VLIB_FRAME_SIZE]; /* buffer index for drop or handoff */
619   u16 other_nexts[VLIB_FRAME_SIZE], *other_next = other_nexts, n_other = 0;
620   u16 data_nexts[VLIB_FRAME_SIZE], *data_next = data_nexts, n_data = 0;
621   u16 n_async = 0;
622   const u8 is_async = wg_op_mode_is_set_ASYNC ();
623   vnet_crypto_async_frame_t *async_frame = NULL;
624
625   vlib_get_buffers (vm, from, bufs, n_left_from);
626   vec_reset_length (ptd->crypto_ops);
627   vec_reset_length (ptd->async_frames);
628
629   f64 time = clib_time_now (&vm->clib_time) + vm->time_offset;
630
631   wg_peer_t *peer = NULL;
632   u32 *last_peer_time_idx = NULL;
633   u32 last_rec_idx = ~0;
634
635   bool is_keepalive = false;
636   u32 *peer_idx = NULL;
637   index_t peeri = INDEX_INVALID;
638
639   while (n_left_from > 0)
640     {
641       if (n_left_from > 2)
642         {
643           u8 *p;
644           vlib_prefetch_buffer_header (b[2], LOAD);
645           p = vlib_buffer_get_current (b[1]);
646           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
647           CLIB_PREFETCH (vlib_buffer_get_tail (b[1]), CLIB_CACHE_LINE_BYTES,
648                          LOAD);
649         }
650
651       other_next[n_other] = WG_INPUT_NEXT_PUNT;
652       data_nexts[n_data] = WG_INPUT_N_NEXT;
653
654       header_type =
655         ((message_header_t *) vlib_buffer_get_current (b[0]))->type;
656
657       if (PREDICT_TRUE (header_type == MESSAGE_DATA))
658         {
659           message_data_t *data = vlib_buffer_get_current (b[0]);
660           u8 *iv_data = b[0]->pre_data;
661           u32 buf_idx = from[b - bufs];
662           peer_idx = wg_index_table_lookup (&wmp->index_table,
663                                             data->receiver_index);
664
665           if (data->receiver_index != last_rec_idx)
666             {
667               peer_idx = wg_index_table_lookup (&wmp->index_table,
668                                                 data->receiver_index);
669               if (PREDICT_TRUE (peer_idx != NULL))
670                 {
671                   peeri = *peer_idx;
672                   peer = wg_peer_get (peeri);
673                   last_rec_idx = data->receiver_index;
674                 }
675               else
676                 {
677                   peer = NULL;
678                   last_rec_idx = ~0;
679                 }
680             }
681
682           if (PREDICT_FALSE (!peer_idx))
683             {
684               other_next[n_other] = WG_INPUT_NEXT_ERROR;
685               b[0]->error = node->errors[WG_INPUT_ERROR_PEER];
686               other_bi[n_other] = buf_idx;
687               n_other += 1;
688               goto out;
689             }
690
691           if (PREDICT_FALSE (~0 == peer->input_thread_index))
692             {
693               /* this is the first packet to use this peer, claim the peer
694                * for this thread.
695                */
696               clib_atomic_cmp_and_swap (&peer->input_thread_index, ~0,
697                                         wg_peer_assign_thread (thread_index));
698             }
699
700           if (PREDICT_TRUE (thread_index != peer->input_thread_index))
701             {
702               other_next[n_other] = WG_INPUT_NEXT_HANDOFF_DATA;
703               other_bi[n_other] = buf_idx;
704               n_other += 1;
705               goto next;
706             }
707
708           u16 encr_len = b[0]->current_length - sizeof (message_data_t);
709           u16 decr_len = encr_len - NOISE_AUTHTAG_LEN;
710           if (PREDICT_FALSE (decr_len >= WG_DEFAULT_DATA_SIZE))
711             {
712               b[0]->error = node->errors[WG_INPUT_ERROR_TOO_BIG];
713               other_bi[n_other] = buf_idx;
714               n_other += 1;
715               goto out;
716             }
717
718           enum noise_state_crypt state_cr = wg_input_process (
719             vm, ptd, crypto_ops, &async_frame, b[0], buf_idx, &peer->remote,
720             data->receiver_index, data->counter, data->encrypted_data,
721             decr_len, data->encrypted_data, n_data, iv_data, time, is_async,
722             async_next_node);
723
724           if (PREDICT_FALSE (state_cr == SC_FAILED))
725             {
726               wg_peer_update_flags (*peer_idx, WG_PEER_ESTABLISHED, false);
727               other_next[n_other] = WG_INPUT_NEXT_ERROR;
728               b[0]->error = node->errors[WG_INPUT_ERROR_DECRYPTION];
729               other_bi[n_other] = buf_idx;
730               n_other += 1;
731               goto out;
732             }
733           if (!is_async)
734             {
735               data_bufs[n_data] = b[0];
736               data_bi[n_data] = buf_idx;
737               n_data += 1;
738             }
739           else
740             {
741               n_async += 1;
742             }
743
744           if (PREDICT_FALSE (state_cr == SC_CONN_RESET))
745             {
746               wg_timers_handshake_complete (peer);
747               goto next;
748             }
749           else if (PREDICT_FALSE (state_cr == SC_KEEP_KEY_FRESH))
750             {
751               wg_send_handshake_from_mt (peeri, false);
752               goto next;
753             }
754           else if (PREDICT_TRUE (state_cr == SC_OK))
755             goto next;
756         }
757       else
758         {
759           /* Handshake packets should be processed in main thread */
760           if (thread_index != 0)
761             {
762               other_next[n_other] = WG_INPUT_NEXT_HANDOFF_HANDSHAKE;
763               other_bi[n_other] = from[b - bufs];
764               n_other += 1;
765               goto next;
766             }
767
768           wg_input_error_t ret =
769             wg_handshake_process (vm, wmp, b[0], node->node_index, is_ip4);
770           if (ret != WG_INPUT_ERROR_NONE)
771             {
772               other_next[n_other] = WG_INPUT_NEXT_ERROR;
773               b[0]->error = node->errors[ret];
774               other_bi[n_other] = from[b - bufs];
775               n_other += 1;
776             }
777           else
778             {
779               other_bi[n_other] = from[b - bufs];
780               n_other += 1;
781             }
782         }
783
784     out:
785       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
786                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
787         {
788           wg_input_trace_t *t = vlib_add_trace (vm, node, b[0], sizeof (*t));
789           t->type = header_type;
790           t->current_length = b[0]->current_length;
791           t->is_keepalive = is_keepalive;
792           t->peer = peer_idx ? peeri : INDEX_INVALID;
793         }
794
795     next:
796       n_left_from -= 1;
797       b += 1;
798     }
799
800   /* decrypt packets */
801   wg_input_process_ops (vm, node, ptd->crypto_ops, data_bufs, data_nexts,
802                         drop_next);
803
804   /* process after decryption */
805   b = data_bufs;
806   n_left_from = n_data;
807   last_rec_idx = ~0;
808   last_peer_time_idx = NULL;
809
810   while (n_left_from > 0)
811     {
812       bool is_keepalive = false;
813       u32 *peer_idx = NULL;
814
815       if (PREDICT_FALSE (data_next[0] == WG_INPUT_NEXT_PUNT))
816         {
817           goto trace;
818         }
819       if (n_left_from > 2)
820         {
821           u8 *p;
822           vlib_prefetch_buffer_header (b[2], LOAD);
823           p = vlib_buffer_get_current (b[1]);
824           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
825           CLIB_PREFETCH (vlib_buffer_get_tail (b[1]), CLIB_CACHE_LINE_BYTES,
826                          LOAD);
827         }
828
829       message_data_t *data = vlib_buffer_get_current (b[0]);
830       ip46_address_t out_src_ip;
831       u16 out_udp_src_port;
832
833       wg_find_outer_addr_port (b[0], &out_src_ip, &out_udp_src_port, is_ip4);
834
835       if (data->receiver_index != last_rec_idx)
836         {
837           peer_idx =
838             wg_index_table_lookup (&wmp->index_table, data->receiver_index);
839           if (PREDICT_TRUE (peer_idx != NULL))
840             {
841               peeri = *peer_idx;
842               peer = wg_peer_get (peeri);
843               last_rec_idx = data->receiver_index;
844             }
845           else
846             {
847               peer = NULL;
848               last_rec_idx = ~0;
849             }
850         }
851
852       if (PREDICT_TRUE (peer != NULL))
853         {
854           if (PREDICT_FALSE (wg_input_post_process (vm, b[0], data_next, peer,
855                                                     data, &is_keepalive) < 0))
856             goto trace;
857         }
858       else
859         {
860           data_next[0] = WG_INPUT_NEXT_PUNT;
861           goto trace;
862         }
863
864       if (PREDICT_FALSE (peer_idx && (last_peer_time_idx != peer_idx)))
865         {
866           if (PREDICT_FALSE (
867                 !ip46_address_is_equal (&peer->dst.addr, &out_src_ip) ||
868                 peer->dst.port != out_udp_src_port))
869             wg_peer_update_endpoint_from_mt (peeri, &out_src_ip,
870                                              out_udp_src_port);
871           wg_timers_any_authenticated_packet_received_opt (peer, time);
872           wg_timers_any_authenticated_packet_traversal (peer);
873           last_peer_time_idx = peer_idx;
874         }
875
876       vlib_increment_combined_counter (im->combined_sw_if_counters +
877                                          VNET_INTERFACE_COUNTER_RX,
878                                        vm->thread_index, peer->wg_sw_if_index,
879                                        1 /* packets */, b[0]->current_length);
880
881     trace:
882       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
883                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
884         {
885           wg_input_trace_t *t = vlib_add_trace (vm, node, b[0], sizeof (*t));
886           t->type = header_type;
887           t->current_length = b[0]->current_length;
888           t->is_keepalive = is_keepalive;
889           t->peer = peer_idx ? peeri : INDEX_INVALID;
890         }
891
892       b += 1;
893       n_left_from -= 1;
894       data_next += 1;
895     }
896
897   if (n_async)
898     {
899       /* submit all of the open frames */
900       vnet_crypto_async_frame_t **async_frame;
901       vec_foreach (async_frame, ptd->async_frames)
902         {
903           if (PREDICT_FALSE (
904                 vnet_crypto_async_submit_open_frame (vm, *async_frame) < 0))
905             {
906               u32 n_drop = (*async_frame)->n_elts;
907               u32 *bi = (*async_frame)->buffer_indices;
908               u16 index = n_other;
909               while (n_drop--)
910                 {
911                   other_bi[index] = bi[0];
912                   vlib_buffer_t *b = vlib_get_buffer (vm, bi[0]);
913                   other_nexts[index] = drop_next;
914                   b->error = node->errors[WG_INPUT_ERROR_CRYPTO_ENGINE_ERROR];
915                   bi++;
916                   index++;
917                 }
918               n_other += (*async_frame)->n_elts;
919
920               vnet_crypto_async_reset_frame (*async_frame);
921               vnet_crypto_async_free_frame (vm, *async_frame);
922             }
923         }
924     }
925
926   /* enqueue other bufs */
927   if (n_other)
928     vlib_buffer_enqueue_to_next (vm, node, other_bi, other_next, n_other);
929
930   /* enqueue data bufs */
931   if (n_data)
932     vlib_buffer_enqueue_to_next (vm, node, data_bi, data_nexts, n_data);
933
934   return frame->n_vectors;
935 }
936
937 always_inline uword
938 wg_input_post (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame,
939                u8 is_ip4)
940 {
941   vnet_main_t *vnm = vnet_get_main ();
942   vnet_interface_main_t *im = &vnm->interface_main;
943   wg_main_t *wmp = &wg_main;
944   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
945   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
946   u32 *from = vlib_frame_vector_args (frame);
947   u32 n_left = frame->n_vectors;
948   wg_peer_t *peer = NULL;
949   u32 *peer_idx = NULL;
950   u32 *last_peer_time_idx = NULL;
951   index_t peeri = INDEX_INVALID;
952   u32 last_rec_idx = ~0;
953   f64 time = clib_time_now (&vm->clib_time) + vm->time_offset;
954
955   vlib_get_buffers (vm, from, b, n_left);
956
957   if (n_left >= 2)
958     {
959       vlib_prefetch_buffer_header (b[0], LOAD);
960       vlib_prefetch_buffer_header (b[1], LOAD);
961     }
962
963   while (n_left > 0)
964     {
965       if (n_left > 2)
966         {
967           u8 *p;
968           vlib_prefetch_buffer_header (b[2], LOAD);
969           p = vlib_buffer_get_current (b[1]);
970           CLIB_PREFETCH (p, CLIB_CACHE_LINE_BYTES, LOAD);
971         }
972
973       bool is_keepalive = false;
974       message_data_t *data = vlib_buffer_get_current (b[0]);
975       ip46_address_t out_src_ip;
976       u16 out_udp_src_port;
977
978       wg_find_outer_addr_port (b[0], &out_src_ip, &out_udp_src_port, is_ip4);
979
980       if (data->receiver_index != last_rec_idx)
981         {
982           peer_idx =
983             wg_index_table_lookup (&wmp->index_table, data->receiver_index);
984
985           if (PREDICT_TRUE (peer_idx != NULL))
986             {
987               peeri = *peer_idx;
988               peer = wg_peer_get (peeri);
989               last_rec_idx = data->receiver_index;
990             }
991           else
992             {
993               peer = NULL;
994               last_rec_idx = ~0;
995             }
996         }
997
998       if (PREDICT_TRUE (peer != NULL))
999         {
1000           if (PREDICT_FALSE (wg_input_post_process (vm, b[0], next, peer, data,
1001                                                     &is_keepalive) < 0))
1002             goto trace;
1003         }
1004       else
1005         {
1006           next[0] = WG_INPUT_NEXT_PUNT;
1007           goto trace;
1008         }
1009
1010       if (PREDICT_FALSE (peer_idx && (last_peer_time_idx != peer_idx)))
1011         {
1012           if (PREDICT_FALSE (
1013                 !ip46_address_is_equal (&peer->dst.addr, &out_src_ip) ||
1014                 peer->dst.port != out_udp_src_port))
1015             wg_peer_update_endpoint_from_mt (peeri, &out_src_ip,
1016                                              out_udp_src_port);
1017           wg_timers_any_authenticated_packet_received_opt (peer, time);
1018           wg_timers_any_authenticated_packet_traversal (peer);
1019           last_peer_time_idx = peer_idx;
1020         }
1021
1022       vlib_increment_combined_counter (im->combined_sw_if_counters +
1023                                          VNET_INTERFACE_COUNTER_RX,
1024                                        vm->thread_index, peer->wg_sw_if_index,
1025                                        1 /* packets */, b[0]->current_length);
1026
1027     trace:
1028       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE) &&
1029                          (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
1030         {
1031           wg_input_post_trace_t *t =
1032             vlib_add_trace (vm, node, b[0], sizeof (*t));
1033           t->next = next[0];
1034           t->peer = peer_idx ? peeri : INDEX_INVALID;
1035         }
1036
1037       b += 1;
1038       next += 1;
1039       n_left -= 1;
1040     }
1041
1042   vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors);
1043   return frame->n_vectors;
1044 }
1045
1046 VLIB_NODE_FN (wg4_input_node)
1047 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
1048 {
1049   return wg_input_inline (vm, node, frame, /* is_ip4 */ 1,
1050                           wg_decrypt_async_next.wg4_post_next);
1051 }
1052
1053 VLIB_NODE_FN (wg6_input_node)
1054 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
1055 {
1056   return wg_input_inline (vm, node, frame, /* is_ip4 */ 0,
1057                           wg_decrypt_async_next.wg6_post_next);
1058 }
1059
1060 VLIB_NODE_FN (wg4_input_post_node)
1061 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *from_frame)
1062 {
1063   return wg_input_post (vm, node, from_frame, /* is_ip4 */ 1);
1064 }
1065
1066 VLIB_NODE_FN (wg6_input_post_node)
1067 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *from_frame)
1068 {
1069   return wg_input_post (vm, node, from_frame, /* is_ip4 */ 0);
1070 }
1071
1072 /* *INDENT-OFF* */
1073 VLIB_REGISTER_NODE (wg4_input_node) =
1074 {
1075   .name = "wg4-input",
1076   .vector_size = sizeof (u32),
1077   .format_trace = format_wg_input_trace,
1078   .type = VLIB_NODE_TYPE_INTERNAL,
1079   .n_errors = ARRAY_LEN (wg_input_error_strings),
1080   .error_strings = wg_input_error_strings,
1081   .n_next_nodes = WG_INPUT_N_NEXT,
1082   /* edit / add dispositions here */
1083   .next_nodes = {
1084         [WG_INPUT_NEXT_HANDOFF_HANDSHAKE] = "wg4-handshake-handoff",
1085         [WG_INPUT_NEXT_HANDOFF_DATA] = "wg4-input-data-handoff",
1086         [WG_INPUT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1087         [WG_INPUT_NEXT_IP6_INPUT] = "ip6-input",
1088         [WG_INPUT_NEXT_PUNT] = "error-punt",
1089         [WG_INPUT_NEXT_ERROR] = "error-drop",
1090   },
1091 };
1092
1093 VLIB_REGISTER_NODE (wg6_input_node) =
1094 {
1095   .name = "wg6-input",
1096   .vector_size = sizeof (u32),
1097   .format_trace = format_wg_input_trace,
1098   .type = VLIB_NODE_TYPE_INTERNAL,
1099   .n_errors = ARRAY_LEN (wg_input_error_strings),
1100   .error_strings = wg_input_error_strings,
1101   .n_next_nodes = WG_INPUT_N_NEXT,
1102   /* edit / add dispositions here */
1103   .next_nodes = {
1104         [WG_INPUT_NEXT_HANDOFF_HANDSHAKE] = "wg6-handshake-handoff",
1105         [WG_INPUT_NEXT_HANDOFF_DATA] = "wg6-input-data-handoff",
1106         [WG_INPUT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1107         [WG_INPUT_NEXT_IP6_INPUT] = "ip6-input",
1108         [WG_INPUT_NEXT_PUNT] = "error-punt",
1109         [WG_INPUT_NEXT_ERROR] = "error-drop",
1110   },
1111 };
1112
1113 VLIB_REGISTER_NODE (wg4_input_post_node) = {
1114   .name = "wg4-input-post-node",
1115   .vector_size = sizeof (u32),
1116   .format_trace = format_wg_input_post_trace,
1117   .type = VLIB_NODE_TYPE_INTERNAL,
1118   .sibling_of = "wg4-input",
1119
1120   .n_errors = ARRAY_LEN (wg_input_error_strings),
1121   .error_strings = wg_input_error_strings,
1122 };
1123
1124 VLIB_REGISTER_NODE (wg6_input_post_node) = {
1125   .name = "wg6-input-post-node",
1126   .vector_size = sizeof (u32),
1127   .format_trace = format_wg_input_post_trace,
1128   .type = VLIB_NODE_TYPE_INTERNAL,
1129   .sibling_of = "wg6-input",
1130
1131   .n_errors = ARRAY_LEN (wg_input_error_strings),
1132   .error_strings = wg_input_error_strings,
1133 };
1134
1135 /* *INDENT-ON* */
1136
1137 /*
1138  * fd.io coding-style-patch-verification: ON
1139  *
1140  * Local Variables:
1141  * eval: (c-set-style "gnu")
1142  * End:
1143  */