wireguard: move adjacency processing from wireguard_peer to wireguard_interface
[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   _ (TOO_BIG, "Packet too big")                                               \
35   _ (UNDEFINED, "Undefined error")
36
37 typedef enum
38 {
39 #define _(sym,str) WG_INPUT_ERROR_##sym,
40   foreach_wg_input_error
41 #undef _
42     WG_INPUT_N_ERROR,
43 } wg_input_error_t;
44
45 static char *wg_input_error_strings[] = {
46 #define _(sym,string) string,
47   foreach_wg_input_error
48 #undef _
49 };
50
51 typedef struct
52 {
53   message_type_t type;
54   u16 current_length;
55   bool is_keepalive;
56   index_t peer;
57 } wg_input_trace_t;
58
59 u8 *
60 format_wg_message_type (u8 * s, va_list * args)
61 {
62   message_type_t type = va_arg (*args, message_type_t);
63
64   switch (type)
65     {
66 #define _(v,a) case MESSAGE_##v: return (format (s, "%s", a));
67       foreach_wg_message_type
68 #undef _
69     }
70   return (format (s, "unknown"));
71 }
72
73 /* packet trace format function */
74 static u8 *
75 format_wg_input_trace (u8 * s, va_list * args)
76 {
77   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
78   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
79
80   wg_input_trace_t *t = va_arg (*args, wg_input_trace_t *);
81
82   s = format (s, "WG input: \n");
83   s = format (s, "  Type: %U\n", format_wg_message_type, t->type);
84   s = format (s, "  peer: %d\n", t->peer);
85   s = format (s, "  Length: %d\n", t->current_length);
86   s = format (s, "  Keepalive: %s", t->is_keepalive ? "true" : "false");
87
88   return s;
89 }
90
91 typedef enum
92 {
93   WG_INPUT_NEXT_HANDOFF_HANDSHAKE,
94   WG_INPUT_NEXT_HANDOFF_DATA,
95   WG_INPUT_NEXT_IP4_INPUT,
96   WG_INPUT_NEXT_PUNT,
97   WG_INPUT_NEXT_ERROR,
98   WG_INPUT_N_NEXT,
99 } wg_input_next_t;
100
101 /* static void */
102 /* set_peer_address (wg_peer_t * peer, ip4_address_t ip4, u16 udp_port) */
103 /* { */
104 /*   if (peer) */
105 /*     { */
106 /*       ip46_address_set_ip4 (&peer->dst.addr, &ip4); */
107 /*       peer->dst.port = udp_port; */
108 /*     } */
109 /* } */
110
111 static wg_input_error_t
112 wg_handshake_process (vlib_main_t * vm, wg_main_t * wmp, vlib_buffer_t * b)
113 {
114   ASSERT (vm->thread_index == 0);
115
116   enum cookie_mac_state mac_state;
117   bool packet_needs_cookie;
118   bool under_load;
119   wg_if_t *wg_if;
120   wg_peer_t *peer = NULL;
121
122   void *current_b_data = vlib_buffer_get_current (b);
123
124   udp_header_t *uhd = current_b_data - sizeof (udp_header_t);
125   ip4_header_t *iph =
126     current_b_data - sizeof (udp_header_t) - sizeof (ip4_header_t);
127   ip4_address_t ip4_src = iph->src_address;
128   u16 udp_src_port = clib_host_to_net_u16 (uhd->src_port);;
129   u16 udp_dst_port = clib_host_to_net_u16 (uhd->dst_port);;
130
131   message_header_t *header = current_b_data;
132   under_load = false;
133
134   wg_if = wg_if_get_by_port (udp_dst_port);
135
136   if (NULL == wg_if)
137     return WG_INPUT_ERROR_INTERFACE;
138
139   if (PREDICT_FALSE (header->type == MESSAGE_HANDSHAKE_COOKIE))
140     {
141       message_handshake_cookie_t *packet =
142         (message_handshake_cookie_t *) current_b_data;
143       u32 *entry =
144         wg_index_table_lookup (&wmp->index_table, packet->receiver_index);
145       if (entry)
146         peer = wg_peer_get (*entry);
147       else
148         return WG_INPUT_ERROR_PEER;
149
150       // TODO: Implement cookie_maker_consume_payload
151
152       return WG_INPUT_ERROR_NONE;
153     }
154
155   u32 len = (header->type == MESSAGE_HANDSHAKE_INITIATION ?
156              sizeof (message_handshake_initiation_t) :
157              sizeof (message_handshake_response_t));
158
159   message_macs_t *macs = (message_macs_t *)
160     ((u8 *) current_b_data + len - sizeof (*macs));
161
162   mac_state =
163     cookie_checker_validate_macs (vm, &wg_if->cookie_checker, macs,
164                                   current_b_data, len, under_load, ip4_src,
165                                   udp_src_port);
166
167   if ((under_load && mac_state == VALID_MAC_WITH_COOKIE)
168       || (!under_load && mac_state == VALID_MAC_BUT_NO_COOKIE))
169     packet_needs_cookie = false;
170   else if (under_load && mac_state == VALID_MAC_BUT_NO_COOKIE)
171     packet_needs_cookie = true;
172   else
173     return WG_INPUT_ERROR_HANDSHAKE_MAC;
174
175   switch (header->type)
176     {
177     case MESSAGE_HANDSHAKE_INITIATION:
178       {
179         message_handshake_initiation_t *message = current_b_data;
180
181         if (packet_needs_cookie)
182           {
183             // TODO: Add processing
184           }
185         noise_remote_t *rp;
186         if (noise_consume_initiation
187             (vm, noise_local_get (wg_if->local_idx), &rp,
188              message->sender_index, message->unencrypted_ephemeral,
189              message->encrypted_static, message->encrypted_timestamp))
190           {
191             peer = wg_peer_get (rp->r_peer_idx);
192           }
193         else
194           {
195             return WG_INPUT_ERROR_PEER;
196           }
197
198         // set_peer_address (peer, ip4_src, udp_src_port);
199         if (PREDICT_FALSE (!wg_send_handshake_response (vm, peer)))
200           {
201             vlib_node_increment_counter (vm, wg_input_node.index,
202                                          WG_INPUT_ERROR_HANDSHAKE_SEND, 1);
203           }
204         break;
205       }
206     case MESSAGE_HANDSHAKE_RESPONSE:
207       {
208         message_handshake_response_t *resp = current_b_data;
209         u32 *entry =
210           wg_index_table_lookup (&wmp->index_table, resp->receiver_index);
211
212         if (PREDICT_TRUE (entry != NULL))
213           {
214             peer = wg_peer_get (*entry);
215             if (peer->is_dead)
216               return WG_INPUT_ERROR_PEER;
217           }
218         else
219           return WG_INPUT_ERROR_PEER;
220
221         if (!noise_consume_response
222             (vm, &peer->remote, resp->sender_index,
223              resp->receiver_index, resp->unencrypted_ephemeral,
224              resp->encrypted_nothing))
225           {
226             return WG_INPUT_ERROR_PEER;
227           }
228         if (packet_needs_cookie)
229           {
230             // TODO: Add processing
231           }
232
233         // set_peer_address (peer, ip4_src, udp_src_port);
234         if (noise_remote_begin_session (vm, &peer->remote))
235           {
236
237             wg_timers_session_derived (peer);
238             wg_timers_handshake_complete (peer);
239             if (PREDICT_FALSE (!wg_send_keepalive (vm, peer)))
240               {
241                 vlib_node_increment_counter (vm, wg_input_node.index,
242                                              WG_INPUT_ERROR_KEEPALIVE_SEND,
243                                              1);
244               }
245           }
246         break;
247       }
248     default:
249       return WG_INPUT_ERROR_HANDSHAKE_RECEIVE;
250     }
251
252   wg_timers_any_authenticated_packet_received (peer);
253   wg_timers_any_authenticated_packet_traversal (peer);
254   return WG_INPUT_ERROR_NONE;
255 }
256
257 VLIB_NODE_FN (wg_input_node) (vlib_main_t * vm,
258                               vlib_node_runtime_t * node,
259                               vlib_frame_t * frame)
260 {
261   message_type_t header_type;
262   u32 n_left_from;
263   u32 *from;
264   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b;
265   u16 nexts[VLIB_FRAME_SIZE], *next;
266   u32 thread_index = vm->thread_index;
267
268   from = vlib_frame_vector_args (frame);
269   n_left_from = frame->n_vectors;
270   b = bufs;
271   next = nexts;
272
273   vlib_get_buffers (vm, from, bufs, n_left_from);
274
275   wg_main_t *wmp = &wg_main;
276   wg_peer_t *peer = NULL;
277
278   while (n_left_from > 0)
279     {
280       bool is_keepalive = false;
281       next[0] = WG_INPUT_NEXT_PUNT;
282       header_type =
283         ((message_header_t *) vlib_buffer_get_current (b[0]))->type;
284       u32 *peer_idx;
285
286       if (PREDICT_TRUE (header_type == MESSAGE_DATA))
287         {
288           message_data_t *data = vlib_buffer_get_current (b[0]);
289
290           peer_idx = wg_index_table_lookup (&wmp->index_table,
291                                             data->receiver_index);
292
293           if (peer_idx)
294             {
295               peer = wg_peer_get (*peer_idx);
296             }
297           else
298             {
299               next[0] = WG_INPUT_NEXT_ERROR;
300               b[0]->error = node->errors[WG_INPUT_ERROR_PEER];
301               goto out;
302             }
303
304           if (PREDICT_FALSE (~0 == peer->input_thread_index))
305             {
306               /* this is the first packet to use this peer, claim the peer
307                * for this thread.
308                */
309               clib_atomic_cmp_and_swap (&peer->input_thread_index, ~0,
310                                         wg_peer_assign_thread (thread_index));
311             }
312
313           if (PREDICT_TRUE (thread_index != peer->input_thread_index))
314             {
315               next[0] = WG_INPUT_NEXT_HANDOFF_DATA;
316               goto next;
317             }
318
319           u16 encr_len = b[0]->current_length - sizeof (message_data_t);
320           u16 decr_len = encr_len - NOISE_AUTHTAG_LEN;
321           if (PREDICT_FALSE (decr_len >= WG_DEFAULT_DATA_SIZE))
322             {
323               b[0]->error = node->errors[WG_INPUT_ERROR_TOO_BIG];
324               goto out;
325             }
326
327           u8 *decr_data = wmp->per_thread_data[thread_index].data;
328
329           enum noise_state_crypt state_cr = noise_remote_decrypt (vm,
330                                                                   &peer->remote,
331                                                                   data->receiver_index,
332                                                                   data->counter,
333                                                                   data->encrypted_data,
334                                                                   encr_len,
335                                                                   decr_data);
336
337           if (PREDICT_FALSE (state_cr == SC_CONN_RESET))
338             {
339               wg_timers_handshake_complete (peer);
340             }
341           else if (PREDICT_FALSE (state_cr == SC_KEEP_KEY_FRESH))
342             {
343               wg_send_handshake_from_mt (*peer_idx, false);
344             }
345           else if (PREDICT_FALSE (state_cr == SC_FAILED))
346             {
347               next[0] = WG_INPUT_NEXT_ERROR;
348               b[0]->error = node->errors[WG_INPUT_ERROR_DECRYPTION];
349               goto out;
350             }
351
352           clib_memcpy (vlib_buffer_get_current (b[0]), decr_data, decr_len);
353           b[0]->current_length = decr_len;
354           vnet_buffer_offload_flags_clear (b[0],
355                                            VNET_BUFFER_OFFLOAD_F_UDP_CKSUM);
356
357           wg_timers_any_authenticated_packet_received (peer);
358           wg_timers_any_authenticated_packet_traversal (peer);
359
360           /* Keepalive packet has zero length */
361           if (decr_len == 0)
362             {
363               is_keepalive = true;
364               goto out;
365             }
366
367           wg_timers_data_received (peer);
368
369           ip4_header_t *iph = vlib_buffer_get_current (b[0]);
370
371           const fib_prefix_t *allowed_ip;
372           bool allowed = false;
373
374           /*
375            * we could make this into an ACL, but the expectation
376            * is that there aren't many allowed IPs and thus a linear
377            * walk is fater than an ACL
378            */
379           vec_foreach (allowed_ip, peer->allowed_ips)
380           {
381             if (fib_prefix_is_cover_addr_4 (allowed_ip, &iph->src_address))
382               {
383                 allowed = true;
384                 break;
385               }
386           }
387           if (allowed)
388             {
389               vnet_buffer (b[0])->sw_if_index[VLIB_RX] = peer->wg_sw_if_index;
390               next[0] = WG_INPUT_NEXT_IP4_INPUT;
391             }
392         }
393       else
394         {
395           peer_idx = NULL;
396
397           /* Handshake packets should be processed in main thread */
398           if (thread_index != 0)
399             {
400               next[0] = WG_INPUT_NEXT_HANDOFF_HANDSHAKE;
401               goto next;
402             }
403
404           wg_input_error_t ret = wg_handshake_process (vm, wmp, b[0]);
405           if (ret != WG_INPUT_ERROR_NONE)
406             {
407               next[0] = WG_INPUT_NEXT_ERROR;
408               b[0]->error = node->errors[ret];
409             }
410         }
411
412     out:
413       if (PREDICT_FALSE ((node->flags & VLIB_NODE_FLAG_TRACE)
414                          && (b[0]->flags & VLIB_BUFFER_IS_TRACED)))
415         {
416           wg_input_trace_t *t = vlib_add_trace (vm, node, b[0], sizeof (*t));
417           t->type = header_type;
418           t->current_length = b[0]->current_length;
419           t->is_keepalive = is_keepalive;
420           t->peer = peer_idx ? *peer_idx : INDEX_INVALID;
421         }
422     next:
423       n_left_from -= 1;
424       next += 1;
425       b += 1;
426     }
427   vlib_buffer_enqueue_to_next (vm, node, from, nexts, frame->n_vectors);
428
429   return frame->n_vectors;
430 }
431
432 /* *INDENT-OFF* */
433 VLIB_REGISTER_NODE (wg_input_node) =
434 {
435   .name = "wg-input",
436   .vector_size = sizeof (u32),
437   .format_trace = format_wg_input_trace,
438   .type = VLIB_NODE_TYPE_INTERNAL,
439   .n_errors = ARRAY_LEN (wg_input_error_strings),
440   .error_strings = wg_input_error_strings,
441   .n_next_nodes = WG_INPUT_N_NEXT,
442   /* edit / add dispositions here */
443   .next_nodes = {
444         [WG_INPUT_NEXT_HANDOFF_HANDSHAKE] = "wg-handshake-handoff",
445         [WG_INPUT_NEXT_HANDOFF_DATA] = "wg-input-data-handoff",
446         [WG_INPUT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
447         [WG_INPUT_NEXT_PUNT] = "error-punt",
448         [WG_INPUT_NEXT_ERROR] = "error-drop",
449   },
450 };
451 /* *INDENT-ON* */
452
453 /*
454  * fd.io coding-style-patch-verification: ON
455  *
456  * Local Variables:
457  * eval: (c-set-style "gnu")
458  * End:
459  */