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