wireguard: add events for peer
[vpp.git] / src / plugins / wireguard / wireguard_peer.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 <vnet/adj/adj_midchain.h>
18 #include <vnet/fib/fib_table.h>
19 #include <wireguard/wireguard_peer.h>
20 #include <wireguard/wireguard_if.h>
21 #include <wireguard/wireguard_messages.h>
22 #include <wireguard/wireguard_key.h>
23 #include <wireguard/wireguard_send.h>
24 #include <wireguard/wireguard.h>
25 #include <vnet/tunnel/tunnel_dp.h>
26
27 wg_peer_t *wg_peer_pool;
28
29 index_t *wg_peer_by_adj_index;
30
31 static void
32 wg_peer_endpoint_reset (wg_peer_endpoint_t * ep)
33 {
34   ip46_address_reset (&ep->addr);
35   ep->port = 0;
36 }
37
38 static void
39 wg_peer_endpoint_init (wg_peer_endpoint_t *ep, const ip46_address_t *addr,
40                        u16 port)
41 {
42   ip46_address_copy (&ep->addr, addr);
43   ep->port = port;
44 }
45
46 static void
47 wg_peer_clear (vlib_main_t * vm, wg_peer_t * peer)
48 {
49   index_t perri = peer - wg_peer_pool;
50   wg_timers_stop (peer);
51   wg_peer_update_flags (perri, WG_PEER_ESTABLISHED, false);
52   wg_peer_update_flags (perri, WG_PEER_STATUS_DEAD, true);
53   for (int i = 0; i < WG_N_TIMERS; i++)
54     {
55       peer->timers[i] = ~0;
56       peer->timers_dispatched[i] = 0;
57     }
58
59   peer->last_sent_handshake = vlib_time_now (vm) - (REKEY_TIMEOUT + 1);
60
61   clib_memset (&peer->cookie_maker, 0, sizeof (peer->cookie_maker));
62
63   wg_peer_endpoint_reset (&peer->src);
64   wg_peer_endpoint_reset (&peer->dst);
65
66   adj_index_t *adj_index;
67   vec_foreach (adj_index, peer->adj_indices)
68     {
69       if (INDEX_INVALID != *adj_index)
70         {
71           wg_peer_by_adj_index[*adj_index] = INDEX_INVALID;
72         }
73     }
74   peer->input_thread_index = ~0;
75   peer->output_thread_index = ~0;
76   peer->timer_wheel = 0;
77   peer->persistent_keepalive_interval = 0;
78   peer->timer_handshake_attempts = 0;
79   peer->last_sent_packet = 0;
80   peer->last_received_packet = 0;
81   peer->session_derived = 0;
82   peer->rehandshake_started = 0;
83   peer->new_handshake_interval_tick = 0;
84   peer->rehandshake_interval_tick = 0;
85   peer->timer_need_another_keepalive = false;
86   vec_free (peer->allowed_ips);
87   vec_free (peer->adj_indices);
88 }
89
90 static void
91 wg_peer_init (vlib_main_t * vm, wg_peer_t * peer)
92 {
93   peer->api_client_by_client_index = hash_create (0, sizeof (u32));
94   peer->api_clients = NULL;
95   wg_peer_clear (vm, peer);
96 }
97
98 static u8 *
99 wg_peer_build_rewrite (const wg_peer_t *peer, u8 is_ip4)
100 {
101   u8 *rewrite = NULL;
102   if (is_ip4)
103     {
104       ip4_udp_header_t *hdr;
105
106       vec_validate (rewrite, sizeof (*hdr) - 1);
107       hdr = (ip4_udp_header_t *) rewrite;
108
109       hdr->ip4.ip_version_and_header_length = 0x45;
110       hdr->ip4.ttl = 64;
111       hdr->ip4.src_address = peer->src.addr.ip4;
112       hdr->ip4.dst_address = peer->dst.addr.ip4;
113       hdr->ip4.protocol = IP_PROTOCOL_UDP;
114       hdr->ip4.checksum = ip4_header_checksum (&hdr->ip4);
115
116       hdr->udp.src_port = clib_host_to_net_u16 (peer->src.port);
117       hdr->udp.dst_port = clib_host_to_net_u16 (peer->dst.port);
118       hdr->udp.checksum = 0;
119     }
120   else
121     {
122       ip6_udp_header_t *hdr;
123
124       vec_validate (rewrite, sizeof (*hdr) - 1);
125       hdr = (ip6_udp_header_t *) rewrite;
126
127       hdr->ip6.ip_version_traffic_class_and_flow_label = 0x60;
128       ip6_address_copy (&hdr->ip6.src_address, &peer->src.addr.ip6);
129       ip6_address_copy (&hdr->ip6.dst_address, &peer->dst.addr.ip6);
130       hdr->ip6.protocol = IP_PROTOCOL_UDP;
131       hdr->ip6.hop_limit = 64;
132
133       hdr->udp.src_port = clib_host_to_net_u16 (peer->src.port);
134       hdr->udp.dst_port = clib_host_to_net_u16 (peer->dst.port);
135       hdr->udp.checksum = 0;
136     }
137
138   return (rewrite);
139 }
140
141 static void
142 wg_peer_adj_stack (wg_peer_t *peer, adj_index_t ai)
143 {
144   ip_adjacency_t *adj;
145   u32 sw_if_index;
146   wg_if_t *wgi;
147   fib_protocol_t fib_proto;
148
149   if (!adj_is_valid (ai))
150     return;
151
152   adj = adj_get (ai);
153   sw_if_index = adj->rewrite_header.sw_if_index;
154   u8 is_ip4 = ip46_address_is_ip4 (&peer->src.addr);
155   fib_proto = is_ip4 ? FIB_PROTOCOL_IP4 : FIB_PROTOCOL_IP6;
156
157   wgi = wg_if_get (wg_if_find_by_sw_if_index (sw_if_index));
158
159   if (!wgi)
160     return;
161
162   if (!vnet_sw_interface_is_admin_up (vnet_get_main (), wgi->sw_if_index))
163     {
164       adj_midchain_delegate_unstack (ai);
165     }
166   else
167     {
168       /* *INDENT-OFF* */
169       fib_prefix_t dst = {
170         .fp_len = is_ip4 ? 32 : 128,
171         .fp_proto = fib_proto,
172         .fp_addr = peer->dst.addr,
173       };
174       /* *INDENT-ON* */
175       u32 fib_index;
176
177       fib_index = fib_table_find (fib_proto, peer->table_id);
178
179       adj_midchain_delegate_stack (ai, fib_index, &dst);
180     }
181 }
182
183 static void
184 wg_peer_66_fixup (vlib_main_t *vm, const ip_adjacency_t *adj, vlib_buffer_t *b,
185                   const void *data)
186 {
187   u8 iph_offset = 0;
188   ip6_header_t *ip6_out;
189   ip6_header_t *ip6_in;
190
191   /* Must set locally originated otherwise we're not allowed to
192      fragment the packet later */
193   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
194
195   ip6_out = vlib_buffer_get_current (b);
196   iph_offset = vnet_buffer (b)->ip.save_rewrite_length;
197   ip6_in = vlib_buffer_get_current (b) + iph_offset;
198
199   ip6_out->ip_version_traffic_class_and_flow_label =
200     ip6_in->ip_version_traffic_class_and_flow_label;
201 }
202
203 static void
204 wg_peer_46_fixup (vlib_main_t *vm, const ip_adjacency_t *adj, vlib_buffer_t *b,
205                   const void *data)
206 {
207   u8 iph_offset = 0;
208   ip6_header_t *ip6_out;
209   ip4_header_t *ip4_in;
210
211   /* Must set locally originated otherwise we're not allowed to
212      fragment the packet later */
213   b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED;
214
215   ip6_out = vlib_buffer_get_current (b);
216   iph_offset = vnet_buffer (b)->ip.save_rewrite_length;
217   ip4_in = vlib_buffer_get_current (b) + iph_offset;
218
219   u32 vtcfl = 0x6 << 28;
220   vtcfl |= ip4_in->tos << 20;
221   vtcfl |= vnet_buffer (b)->ip.flow_hash & 0x000fffff;
222
223   ip6_out->ip_version_traffic_class_and_flow_label =
224     clib_host_to_net_u32 (vtcfl);
225 }
226
227 static adj_midchain_fixup_t
228 wg_peer_get_fixup (wg_peer_t *peer, vnet_link_t lt)
229 {
230   if (!ip46_address_is_ip4 (&peer->dst.addr))
231     {
232       if (lt == VNET_LINK_IP4)
233         return (wg_peer_46_fixup);
234       if (lt == VNET_LINK_IP6)
235         return (wg_peer_66_fixup);
236     }
237   return (NULL);
238 }
239
240 walk_rc_t
241 wg_peer_if_admin_state_change (index_t peeri, void *data)
242 {
243   wg_peer_t *peer;
244   adj_index_t *adj_index;
245   peer = wg_peer_get (peeri);
246   vec_foreach (adj_index, peer->adj_indices)
247     {
248       wg_peer_adj_stack (peer, *adj_index);
249     }
250   return (WALK_CONTINUE);
251 }
252
253 walk_rc_t
254 wg_peer_if_adj_change (index_t peeri, void *data)
255 {
256   adj_index_t *adj_index = data;
257   adj_midchain_fixup_t fixup;
258   ip_adjacency_t *adj;
259   wg_peer_t *peer;
260   fib_prefix_t *allowed_ip;
261
262   adj = adj_get (*adj_index);
263
264   peer = wg_peer_get (peeri);
265   vec_foreach (allowed_ip, peer->allowed_ips)
266     {
267       if (fib_prefix_is_cover_addr_46 (allowed_ip,
268                                        &adj->sub_type.nbr.next_hop))
269         {
270           vec_add1 (peer->adj_indices, *adj_index);
271           vec_validate_init_empty (wg_peer_by_adj_index, *adj_index,
272                                    INDEX_INVALID);
273           wg_peer_by_adj_index[*adj_index] = peer - wg_peer_pool;
274
275           fixup = wg_peer_get_fixup (peer, adj_get_link_type (*adj_index));
276           adj_nbr_midchain_update_rewrite (*adj_index, fixup, NULL,
277                                            ADJ_FLAG_MIDCHAIN_IP_STACK,
278                                            vec_dup (peer->rewrite));
279
280           wg_peer_adj_stack (peer, *adj_index);
281           return (WALK_STOP);
282         }
283     }
284
285   return (WALK_CONTINUE);
286 }
287
288 adj_walk_rc_t
289 wg_peer_adj_walk (adj_index_t ai, void *data)
290 {
291   return wg_peer_if_adj_change ((*(index_t *) (data)), &ai) == WALK_CONTINUE ?
292            ADJ_WALK_RC_CONTINUE :
293            ADJ_WALK_RC_STOP;
294 }
295
296 walk_rc_t
297 wg_peer_if_delete (index_t peeri, void *data)
298 {
299   wg_peer_remove (peeri);
300   return (WALK_CONTINUE);
301 }
302
303 static int
304 wg_peer_fill (vlib_main_t *vm, wg_peer_t *peer, u32 table_id,
305               const ip46_address_t *dst, u16 port,
306               u16 persistent_keepalive_interval,
307               const fib_prefix_t *allowed_ips, u32 wg_sw_if_index)
308 {
309   index_t perri = peer - wg_peer_pool;
310   wg_peer_endpoint_init (&peer->dst, dst, port);
311
312   peer->table_id = table_id;
313   peer->wg_sw_if_index = wg_sw_if_index;
314   peer->timer_wheel = &wg_main.timer_wheel;
315   peer->persistent_keepalive_interval = persistent_keepalive_interval;
316   peer->last_sent_handshake = vlib_time_now (vm) - (REKEY_TIMEOUT + 1);
317   wg_peer_update_flags (perri, WG_PEER_STATUS_DEAD, false);
318
319   const wg_if_t *wgi = wg_if_get (wg_if_find_by_sw_if_index (wg_sw_if_index));
320
321   if (NULL == wgi)
322     return (VNET_API_ERROR_INVALID_INTERFACE);
323
324   ip_address_to_46 (&wgi->src_ip, &peer->src.addr);
325   peer->src.port = wgi->port;
326
327   u8 is_ip4 = ip46_address_is_ip4 (&peer->dst.addr);
328   peer->rewrite = wg_peer_build_rewrite (peer, is_ip4);
329
330   u32 ii;
331   vec_validate (peer->allowed_ips, vec_len (allowed_ips) - 1);
332   vec_foreach_index (ii, allowed_ips)
333   {
334     peer->allowed_ips[ii] = allowed_ips[ii];
335   }
336
337   fib_protocol_t proto;
338   FOR_EACH_FIB_IP_PROTOCOL (proto)
339   {
340     adj_nbr_walk (wg_sw_if_index, proto, wg_peer_adj_walk, &perri);
341   }
342   return (0);
343 }
344
345 void
346 wg_peer_update_flags (index_t peeri, wg_peer_flags flag, bool add_del)
347 {
348   wg_peer_t *peer = wg_peer_get (peeri);
349   if ((add_del && (peer->flags & flag)) || (!add_del && !(peer->flags & flag)))
350     {
351       return;
352     }
353
354   peer->flags ^= flag;
355   wg_api_peer_event (peeri, peer->flags);
356 }
357
358 int
359 wg_peer_add (u32 tun_sw_if_index, const u8 public_key[NOISE_PUBLIC_KEY_LEN],
360              u32 table_id, const ip46_address_t *endpoint,
361              const fib_prefix_t *allowed_ips, u16 port,
362              u16 persistent_keepalive, u32 *peer_index)
363 {
364   wg_if_t *wg_if;
365   wg_peer_t *peer;
366   int rv;
367
368   vlib_main_t *vm = vlib_get_main ();
369
370   if (tun_sw_if_index == ~0)
371     return (VNET_API_ERROR_INVALID_SW_IF_INDEX);
372
373   wg_if = wg_if_get (wg_if_find_by_sw_if_index (tun_sw_if_index));
374   if (!wg_if)
375     return (VNET_API_ERROR_INVALID_SW_IF_INDEX);
376
377   /* *INDENT-OFF* */
378   pool_foreach (peer, wg_peer_pool)
379    {
380     if (!memcmp (peer->remote.r_public, public_key, NOISE_PUBLIC_KEY_LEN))
381     {
382       return (VNET_API_ERROR_ENTRY_ALREADY_EXISTS);
383     }
384   }
385   /* *INDENT-ON* */
386
387   if (pool_elts (wg_peer_pool) > MAX_PEERS)
388     return (VNET_API_ERROR_LIMIT_EXCEEDED);
389
390   pool_get (wg_peer_pool, peer);
391
392   wg_peer_init (vm, peer);
393
394   rv = wg_peer_fill (vm, peer, table_id, endpoint, (u16) port,
395                      persistent_keepalive, allowed_ips, tun_sw_if_index);
396
397   if (rv)
398     {
399       wg_peer_clear (vm, peer);
400       pool_put (wg_peer_pool, peer);
401       return (rv);
402     }
403
404   noise_remote_init (&peer->remote, peer - wg_peer_pool, public_key,
405                      wg_if->local_idx);
406   cookie_maker_init (&peer->cookie_maker, public_key);
407
408   wg_send_handshake (vm, peer, false);
409   if (peer->persistent_keepalive_interval != 0)
410     {
411       wg_send_keepalive (vm, peer);
412     }
413
414   *peer_index = peer - wg_peer_pool;
415   wg_if_peer_add (wg_if, *peer_index);
416
417   return (0);
418 }
419
420 int
421 wg_peer_remove (index_t peeri)
422 {
423   wg_main_t *wmp = &wg_main;
424   wg_peer_t *peer = NULL;
425   wg_if_t *wgi;
426
427   if (pool_is_free_index (wg_peer_pool, peeri))
428     return VNET_API_ERROR_NO_SUCH_ENTRY;
429
430   peer = pool_elt_at_index (wg_peer_pool, peeri);
431
432   wgi = wg_if_get (wg_if_find_by_sw_if_index (peer->wg_sw_if_index));
433   wg_if_peer_remove (wgi, peeri);
434
435   noise_remote_clear (wmp->vlib_main, &peer->remote);
436   wg_peer_clear (wmp->vlib_main, peer);
437   pool_put (wg_peer_pool, peer);
438
439   return (0);
440 }
441
442 index_t
443 wg_peer_walk (wg_peer_walk_cb_t fn, void *data)
444 {
445   index_t peeri;
446
447   /* *INDENT-OFF* */
448   pool_foreach_index (peeri, wg_peer_pool)
449   {
450     if (WALK_STOP == fn(peeri, data))
451       return peeri;
452   }
453   /* *INDENT-ON* */
454   return INDEX_INVALID;
455 }
456
457 static u8 *
458 format_wg_peer_endpoint (u8 * s, va_list * args)
459 {
460   wg_peer_endpoint_t *ep = va_arg (*args, wg_peer_endpoint_t *);
461
462   s = format (s, "%U:%d", format_ip46_address, &ep->addr, IP46_TYPE_ANY,
463               ep->port);
464
465   return (s);
466 }
467
468 u8 *
469 format_wg_peer (u8 * s, va_list * va)
470 {
471   index_t peeri = va_arg (*va, index_t);
472   fib_prefix_t *allowed_ip;
473   adj_index_t *adj_index;
474   u8 key[NOISE_KEY_LEN_BASE64];
475   wg_peer_t *peer;
476
477   peer = wg_peer_get (peeri);
478   key_to_base64 (peer->remote.r_public, NOISE_PUBLIC_KEY_LEN, key);
479
480   s = format (
481     s,
482     "[%d] endpoint:[%U->%U] %U keep-alive:%d flags: %d, api-clients count: %d",
483     peeri, format_wg_peer_endpoint, &peer->src, format_wg_peer_endpoint,
484     &peer->dst, format_vnet_sw_if_index_name, vnet_get_main (),
485     peer->wg_sw_if_index, peer->persistent_keepalive_interval, peer->flags,
486     pool_elts (peer->api_clients));
487   s = format (s, "\n  adj:");
488   vec_foreach (adj_index, peer->adj_indices)
489     {
490       s = format (s, " %d", *adj_index);
491     }
492   s = format (s, "\n  key:%=s %U", key, format_hex_bytes,
493               peer->remote.r_public, NOISE_PUBLIC_KEY_LEN);
494   s = format (s, "\n  allowed-ips:");
495   vec_foreach (allowed_ip, peer->allowed_ips)
496   {
497     s = format (s, " %U", format_fib_prefix, allowed_ip);
498   }
499
500   return s;
501 }
502
503 /*
504  * fd.io coding-style-patch-verification: ON
505  *
506  * Local Variables:
507  * eval: (c-set-style "gnu")
508  * End:
509  */