xref: /freebsd-13-stable/sys/dev/wg/if_wg.c (revision 894bf6bd7d1dcdb2869cf065bea697e1dda07cb0)
1 /* SPDX-License-Identifier: ISC
2  *
3  * Copyright (C) 2015-2021 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4  * Copyright (C) 2019-2021 Matt Dunwoodie <ncon@noconroy.net>
5  * Copyright (c) 2019-2020 Rubicon Communications, LLC (Netgate)
6  * Copyright (c) 2021 Kyle Evans <kevans@FreeBSD.org>
7  * Copyright (c) 2022 The FreeBSD Foundation
8  */
9 
10 #include "opt_inet.h"
11 #include "opt_inet6.h"
12 
13 #include <sys/param.h>
14 #include <sys/systm.h>
15 #include <sys/counter.h>
16 #include <sys/endian.h>
17 #include <sys/gtaskqueue.h>
18 #include <sys/jail.h>
19 #include <sys/kernel.h>
20 #include <sys/lock.h>
21 #include <sys/mbuf.h>
22 #include <sys/module.h>
23 #include <sys/nv.h>
24 #include <sys/priv.h>
25 #include <sys/proc.h>
26 #include <sys/protosw.h>
27 #include <sys/rmlock.h>
28 #include <sys/rwlock.h>
29 #include <sys/smp.h>
30 #include <sys/socket.h>
31 #include <sys/socketvar.h>
32 #include <sys/sockio.h>
33 #include <sys/sysctl.h>
34 #include <sys/sx.h>
35 #include <machine/_inttypes.h>
36 #include <net/bpf.h>
37 #include <net/ethernet.h>
38 #include <net/if.h>
39 #include <net/if_clone.h>
40 #include <net/if_types.h>
41 #include <net/if_var.h>
42 #include <net/netisr.h>
43 #include <net/radix.h>
44 #include <netinet/in.h>
45 #include <netinet6/in6_var.h>
46 #include <netinet/ip.h>
47 #include <netinet/ip6.h>
48 #include <netinet/ip_icmp.h>
49 #include <netinet/ip_var.h>
50 #include <netinet/icmp6.h>
51 #include <netinet/udp.h>
52 #include <netinet/udp_var.h>
53 #include <netinet6/nd6.h>
54 
55 #include "wg_noise.h"
56 #include "wg_cookie.h"
57 #include "version.h"
58 #include "if_wg.h"
59 
60 #define DEFAULT_MTU		(ETHERMTU - 80)
61 #define MAX_MTU			(IF_MAXMTU - 80)
62 
63 #define MAX_STAGED_PKT		128
64 #define MAX_QUEUED_PKT		1024
65 #define MAX_QUEUED_PKT_MASK	(MAX_QUEUED_PKT - 1)
66 
67 #define MAX_QUEUED_HANDSHAKES	4096
68 
69 #define REKEY_TIMEOUT_JITTER	334 /* 1/3 sec, round for arc4random_uniform */
70 #define MAX_TIMER_HANDSHAKES	(90 / REKEY_TIMEOUT)
71 #define NEW_HANDSHAKE_TIMEOUT	(REKEY_TIMEOUT + KEEPALIVE_TIMEOUT)
72 #define UNDERLOAD_TIMEOUT	1
73 
74 #define DPRINTF(sc, ...) if (sc->sc_ifp->if_flags & IFF_DEBUG) if_printf(sc->sc_ifp, ##__VA_ARGS__)
75 
76 /* First byte indicating packet type on the wire */
77 #define WG_PKT_INITIATION htole32(1)
78 #define WG_PKT_RESPONSE htole32(2)
79 #define WG_PKT_COOKIE htole32(3)
80 #define WG_PKT_DATA htole32(4)
81 
82 #define WG_PKT_PADDING		16
83 #define WG_KEY_SIZE		32
84 
85 struct wg_pkt_initiation {
86 	uint32_t		t;
87 	uint32_t		s_idx;
88 	uint8_t			ue[NOISE_PUBLIC_KEY_LEN];
89 	uint8_t			es[NOISE_PUBLIC_KEY_LEN + NOISE_AUTHTAG_LEN];
90 	uint8_t			ets[NOISE_TIMESTAMP_LEN + NOISE_AUTHTAG_LEN];
91 	struct cookie_macs	m;
92 };
93 
94 struct wg_pkt_response {
95 	uint32_t		t;
96 	uint32_t		s_idx;
97 	uint32_t		r_idx;
98 	uint8_t			ue[NOISE_PUBLIC_KEY_LEN];
99 	uint8_t			en[0 + NOISE_AUTHTAG_LEN];
100 	struct cookie_macs	m;
101 };
102 
103 struct wg_pkt_cookie {
104 	uint32_t		t;
105 	uint32_t		r_idx;
106 	uint8_t			nonce[COOKIE_NONCE_SIZE];
107 	uint8_t			ec[COOKIE_ENCRYPTED_SIZE];
108 };
109 
110 struct wg_pkt_data {
111 	uint32_t		t;
112 	uint32_t		r_idx;
113 	uint64_t		nonce;
114 	uint8_t			buf[];
115 };
116 
117 struct wg_endpoint {
118 	union {
119 		struct sockaddr		r_sa;
120 		struct sockaddr_in	r_sin;
121 #ifdef INET6
122 		struct sockaddr_in6	r_sin6;
123 #endif
124 	} e_remote;
125 	union {
126 		struct in_addr		l_in;
127 #ifdef INET6
128 		struct in6_pktinfo	l_pktinfo6;
129 #define l_in6 l_pktinfo6.ipi6_addr
130 #endif
131 	} e_local;
132 };
133 
134 struct aip_addr {
135 	uint8_t		length;
136 	union {
137 		uint8_t		bytes[16];
138 		uint32_t	ip;
139 		uint32_t	ip6[4];
140 		struct in_addr	in;
141 		struct in6_addr	in6;
142 	};
143 };
144 
145 struct wg_aip {
146 	struct radix_node	 a_nodes[2];
147 	LIST_ENTRY(wg_aip)	 a_entry;
148 	struct aip_addr		 a_addr;
149 	struct aip_addr		 a_mask;
150 	struct wg_peer		*a_peer;
151 	sa_family_t		 a_af;
152 };
153 
154 struct wg_packet {
155 	STAILQ_ENTRY(wg_packet)	 p_serial;
156 	STAILQ_ENTRY(wg_packet)	 p_parallel;
157 	struct wg_endpoint	 p_endpoint;
158 	struct noise_keypair	*p_keypair;
159 	uint64_t		 p_nonce;
160 	struct mbuf		*p_mbuf;
161 	int			 p_mtu;
162 	sa_family_t		 p_af;
163 	enum wg_ring_state {
164 		WG_PACKET_UNCRYPTED,
165 		WG_PACKET_CRYPTED,
166 		WG_PACKET_DEAD,
167 	}			 p_state;
168 };
169 
170 STAILQ_HEAD(wg_packet_list, wg_packet);
171 
172 struct wg_queue {
173 	struct mtx		 q_mtx;
174 	struct wg_packet_list	 q_queue;
175 	size_t			 q_len;
176 };
177 
178 struct wg_peer {
179 	TAILQ_ENTRY(wg_peer)		 p_entry;
180 	uint64_t			 p_id;
181 	struct wg_softc			*p_sc;
182 
183 	struct noise_remote		*p_remote;
184 	struct cookie_maker		 p_cookie;
185 
186 	struct rwlock			 p_endpoint_lock;
187 	struct wg_endpoint		 p_endpoint;
188 
189 	struct wg_queue	 		 p_stage_queue;
190 	struct wg_queue	 		 p_encrypt_serial;
191 	struct wg_queue	 		 p_decrypt_serial;
192 
193 	bool				 p_enabled;
194 	bool				 p_need_another_keepalive;
195 	uint16_t			 p_persistent_keepalive_interval;
196 	struct callout			 p_new_handshake;
197 	struct callout			 p_send_keepalive;
198 	struct callout			 p_retry_handshake;
199 	struct callout			 p_zero_key_material;
200 	struct callout			 p_persistent_keepalive;
201 
202 	struct mtx			 p_handshake_mtx;
203 	struct timespec			 p_handshake_complete;	/* nanotime */
204 	int				 p_handshake_retries;
205 
206 	struct grouptask		 p_send;
207 	struct grouptask		 p_recv;
208 
209 	counter_u64_t			 p_tx_bytes;
210 	counter_u64_t			 p_rx_bytes;
211 
212 	LIST_HEAD(, wg_aip)		 p_aips;
213 	size_t				 p_aips_num;
214 };
215 
216 struct wg_socket {
217 	struct socket	*so_so4;
218 	struct socket	*so_so6;
219 	uint32_t	 so_user_cookie;
220 	int		 so_fibnum;
221 	in_port_t	 so_port;
222 };
223 
224 struct wg_softc {
225 	LIST_ENTRY(wg_softc)	 sc_entry;
226 	struct ifnet		*sc_ifp;
227 	int			 sc_flags;
228 
229 	struct ucred		*sc_ucred;
230 	struct wg_socket	 sc_socket;
231 
232 	TAILQ_HEAD(,wg_peer)	 sc_peers;
233 	size_t			 sc_peers_num;
234 
235 	struct noise_local	*sc_local;
236 	struct cookie_checker	 sc_cookie;
237 
238 	struct radix_node_head	*sc_aip4;
239 	struct radix_node_head	*sc_aip6;
240 
241 	struct grouptask	 sc_handshake;
242 	struct wg_queue		 sc_handshake_queue;
243 
244 	struct grouptask	*sc_encrypt;
245 	struct grouptask	*sc_decrypt;
246 	struct wg_queue		 sc_encrypt_parallel;
247 	struct wg_queue		 sc_decrypt_parallel;
248 	u_int			 sc_encrypt_last_cpu;
249 	u_int			 sc_decrypt_last_cpu;
250 
251 	struct sx		 sc_lock;
252 };
253 
254 #define	WGF_DYING	0x0001
255 
256 #define MAX_LOOPS	8
257 #define MTAG_WGLOOP	0x77676c70 /* wglp */
258 
259 #define	GROUPTASK_DRAIN(gtask)			\
260 	gtaskqueue_drain((gtask)->gt_taskqueue, &(gtask)->gt_task)
261 
262 #define BPF_MTAP2_AF(ifp, m, af) do { \
263 		uint32_t __bpf_tap_af = (af); \
264 		BPF_MTAP2(ifp, &__bpf_tap_af, sizeof(__bpf_tap_af), m); \
265 	} while (0)
266 
267 static int clone_count;
268 static uma_zone_t wg_packet_zone;
269 static volatile unsigned long peer_counter = 0;
270 static const char wgname[] = "wg";
271 static unsigned wg_osd_jail_slot;
272 
273 static struct sx wg_sx;
274 SX_SYSINIT(wg_sx, &wg_sx, "wg_sx");
275 
276 static LIST_HEAD(, wg_softc) wg_list = LIST_HEAD_INITIALIZER(wg_list);
277 
278 static TASKQGROUP_DEFINE(wg_tqg, mp_ncpus, 1);
279 
280 MALLOC_DEFINE(M_WG, "WG", "wireguard");
281 
282 VNET_DEFINE_STATIC(struct if_clone *, wg_cloner);
283 
284 #define	V_wg_cloner	VNET(wg_cloner)
285 #define	WG_CAPS		IFCAP_LINKSTATE
286 
287 struct wg_timespec64 {
288 	uint64_t	tv_sec;
289 	uint64_t	tv_nsec;
290 };
291 
292 static int wg_socket_init(struct wg_softc *, in_port_t);
293 static int wg_socket_bind(struct socket **, struct socket **, in_port_t *);
294 static void wg_socket_set(struct wg_softc *, struct socket *, struct socket *);
295 static void wg_socket_uninit(struct wg_softc *);
296 static int wg_socket_set_sockopt(struct socket *, struct socket *, int, void *, size_t);
297 static int wg_socket_set_cookie(struct wg_softc *, uint32_t);
298 static int wg_socket_set_fibnum(struct wg_softc *, int);
299 static int wg_send(struct wg_softc *, struct wg_endpoint *, struct mbuf *);
300 static void wg_timers_enable(struct wg_peer *);
301 static void wg_timers_disable(struct wg_peer *);
302 static void wg_timers_set_persistent_keepalive(struct wg_peer *, uint16_t);
303 static void wg_timers_get_last_handshake(struct wg_peer *, struct wg_timespec64 *);
304 static void wg_timers_event_data_sent(struct wg_peer *);
305 static void wg_timers_event_data_received(struct wg_peer *);
306 static void wg_timers_event_any_authenticated_packet_sent(struct wg_peer *);
307 static void wg_timers_event_any_authenticated_packet_received(struct wg_peer *);
308 static void wg_timers_event_any_authenticated_packet_traversal(struct wg_peer *);
309 static void wg_timers_event_handshake_initiated(struct wg_peer *);
310 static void wg_timers_event_handshake_complete(struct wg_peer *);
311 static void wg_timers_event_session_derived(struct wg_peer *);
312 static void wg_timers_event_want_initiation(struct wg_peer *);
313 static void wg_timers_run_send_initiation(struct wg_peer *, bool);
314 static void wg_timers_run_retry_handshake(void *);
315 static void wg_timers_run_send_keepalive(void *);
316 static void wg_timers_run_new_handshake(void *);
317 static void wg_timers_run_zero_key_material(void *);
318 static void wg_timers_run_persistent_keepalive(void *);
319 static int wg_aip_add(struct wg_softc *, struct wg_peer *, sa_family_t, const void *, uint8_t);
320 static struct wg_peer *wg_aip_lookup(struct wg_softc *, sa_family_t, void *);
321 static void wg_aip_remove_all(struct wg_softc *, struct wg_peer *);
322 static struct wg_peer *wg_peer_alloc(struct wg_softc *, const uint8_t [WG_KEY_SIZE]);
323 static void wg_peer_free_deferred(struct noise_remote *);
324 static void wg_peer_destroy(struct wg_peer *);
325 static void wg_peer_destroy_all(struct wg_softc *);
326 static void wg_peer_send_buf(struct wg_peer *, uint8_t *, size_t);
327 static void wg_send_initiation(struct wg_peer *);
328 static void wg_send_response(struct wg_peer *);
329 static void wg_send_cookie(struct wg_softc *, struct cookie_macs *, uint32_t, struct wg_endpoint *);
330 static void wg_peer_set_endpoint(struct wg_peer *, struct wg_endpoint *);
331 static void wg_peer_clear_src(struct wg_peer *);
332 static void wg_peer_get_endpoint(struct wg_peer *, struct wg_endpoint *);
333 static void wg_send_buf(struct wg_softc *, struct wg_endpoint *, uint8_t *, size_t);
334 static void wg_send_keepalive(struct wg_peer *);
335 static void wg_handshake(struct wg_softc *, struct wg_packet *);
336 static void wg_encrypt(struct wg_softc *, struct wg_packet *);
337 static void wg_decrypt(struct wg_softc *, struct wg_packet *);
338 static void wg_softc_handshake_receive(struct wg_softc *);
339 static void wg_softc_decrypt(struct wg_softc *);
340 static void wg_softc_encrypt(struct wg_softc *);
341 static void wg_encrypt_dispatch(struct wg_softc *);
342 static void wg_decrypt_dispatch(struct wg_softc *);
343 static void wg_deliver_out(struct wg_peer *);
344 static void wg_deliver_in(struct wg_peer *);
345 static struct wg_packet *wg_packet_alloc(struct mbuf *);
346 static void wg_packet_free(struct wg_packet *);
347 static void wg_queue_init(struct wg_queue *, const char *);
348 static void wg_queue_deinit(struct wg_queue *);
349 static size_t wg_queue_len(struct wg_queue *);
350 static int wg_queue_enqueue_handshake(struct wg_queue *, struct wg_packet *);
351 static struct wg_packet *wg_queue_dequeue_handshake(struct wg_queue *);
352 static void wg_queue_push_staged(struct wg_queue *, struct wg_packet *);
353 static void wg_queue_enlist_staged(struct wg_queue *, struct wg_packet_list *);
354 static void wg_queue_delist_staged(struct wg_queue *, struct wg_packet_list *);
355 static void wg_queue_purge(struct wg_queue *);
356 static int wg_queue_both(struct wg_queue *, struct wg_queue *, struct wg_packet *);
357 static struct wg_packet *wg_queue_dequeue_serial(struct wg_queue *);
358 static struct wg_packet *wg_queue_dequeue_parallel(struct wg_queue *);
359 static void wg_input(struct mbuf *, int, struct inpcb *, const struct sockaddr *, void *);
360 static void wg_peer_send_staged(struct wg_peer *);
361 static int wg_clone_create(struct if_clone *ifc, char *name, size_t len,
362 	struct ifc_data *ifd, struct ifnet **ifpp);
363 static void wg_qflush(struct ifnet *);
364 static inline int determine_af_and_pullup(struct mbuf **m, sa_family_t *af);
365 static int wg_xmit(struct ifnet *, struct mbuf *, sa_family_t, uint32_t);
366 static int wg_transmit(struct ifnet *, struct mbuf *);
367 static int wg_output(struct ifnet *, struct mbuf *, const struct sockaddr *, struct route *);
368 static int wg_clone_destroy(struct if_clone *ifc, struct ifnet *ifp,
369 	uint32_t flags);
370 static bool wgc_privileged(struct wg_softc *);
371 static int wgc_get(struct wg_softc *, struct wg_data_io *);
372 static int wgc_set(struct wg_softc *, struct wg_data_io *);
373 static int wg_up(struct wg_softc *);
374 static void wg_down(struct wg_softc *);
375 static void wg_reassign(struct ifnet *, struct vnet *, char *unused);
376 static void wg_init(void *);
377 static int wg_ioctl(struct ifnet *, u_long, caddr_t);
378 static void vnet_wg_init(const void *);
379 static void vnet_wg_uninit(const void *);
380 static int wg_module_init(void);
381 static void wg_module_deinit(void);
382 
383 /* TODO Peer */
384 static struct wg_peer *
wg_peer_alloc(struct wg_softc * sc,const uint8_t pub_key[WG_KEY_SIZE])385 wg_peer_alloc(struct wg_softc *sc, const uint8_t pub_key[WG_KEY_SIZE])
386 {
387 	struct wg_peer *peer;
388 
389 	sx_assert(&sc->sc_lock, SX_XLOCKED);
390 
391 	peer = malloc(sizeof(*peer), M_WG, M_WAITOK | M_ZERO);
392 	peer->p_remote = noise_remote_alloc(sc->sc_local, peer, pub_key);
393 	peer->p_tx_bytes = counter_u64_alloc(M_WAITOK);
394 	peer->p_rx_bytes = counter_u64_alloc(M_WAITOK);
395 	peer->p_id = peer_counter++;
396 	peer->p_sc = sc;
397 
398 	cookie_maker_init(&peer->p_cookie, pub_key);
399 
400 	rw_init(&peer->p_endpoint_lock, "wg_peer_endpoint");
401 
402 	wg_queue_init(&peer->p_stage_queue, "stageq");
403 	wg_queue_init(&peer->p_encrypt_serial, "txq");
404 	wg_queue_init(&peer->p_decrypt_serial, "rxq");
405 
406 	peer->p_enabled = false;
407 	peer->p_need_another_keepalive = false;
408 	peer->p_persistent_keepalive_interval = 0;
409 	callout_init(&peer->p_new_handshake, true);
410 	callout_init(&peer->p_send_keepalive, true);
411 	callout_init(&peer->p_retry_handshake, true);
412 	callout_init(&peer->p_persistent_keepalive, true);
413 	callout_init(&peer->p_zero_key_material, true);
414 
415 	mtx_init(&peer->p_handshake_mtx, "peer handshake", NULL, MTX_DEF);
416 	bzero(&peer->p_handshake_complete, sizeof(peer->p_handshake_complete));
417 	peer->p_handshake_retries = 0;
418 
419 	GROUPTASK_INIT(&peer->p_send, 0, (gtask_fn_t *)wg_deliver_out, peer);
420 	taskqgroup_attach(qgroup_wg_tqg, &peer->p_send, peer, NULL, NULL, "wg send");
421 	GROUPTASK_INIT(&peer->p_recv, 0, (gtask_fn_t *)wg_deliver_in, peer);
422 	taskqgroup_attach(qgroup_wg_tqg, &peer->p_recv, peer, NULL, NULL, "wg recv");
423 
424 	LIST_INIT(&peer->p_aips);
425 	peer->p_aips_num = 0;
426 
427 	return (peer);
428 }
429 
430 static void
wg_peer_free_deferred(struct noise_remote * r)431 wg_peer_free_deferred(struct noise_remote *r)
432 {
433 	struct wg_peer *peer = noise_remote_arg(r);
434 
435 	/* While there are no references remaining, we may still have
436 	 * p_{send,recv} executing (think empty queue, but wg_deliver_{in,out}
437 	 * needs to check the queue. We should wait for them and then free. */
438 	GROUPTASK_DRAIN(&peer->p_recv);
439 	GROUPTASK_DRAIN(&peer->p_send);
440 	taskqgroup_detach(qgroup_wg_tqg, &peer->p_recv);
441 	taskqgroup_detach(qgroup_wg_tqg, &peer->p_send);
442 
443 	wg_queue_deinit(&peer->p_decrypt_serial);
444 	wg_queue_deinit(&peer->p_encrypt_serial);
445 	wg_queue_deinit(&peer->p_stage_queue);
446 
447 	counter_u64_free(peer->p_tx_bytes);
448 	counter_u64_free(peer->p_rx_bytes);
449 	rw_destroy(&peer->p_endpoint_lock);
450 	mtx_destroy(&peer->p_handshake_mtx);
451 
452 	cookie_maker_free(&peer->p_cookie);
453 
454 	free(peer, M_WG);
455 }
456 
457 static void
wg_peer_destroy(struct wg_peer * peer)458 wg_peer_destroy(struct wg_peer *peer)
459 {
460 	struct wg_softc *sc = peer->p_sc;
461 	sx_assert(&sc->sc_lock, SX_XLOCKED);
462 
463 	/* Disable remote and timers. This will prevent any new handshakes
464 	 * occuring. */
465 	noise_remote_disable(peer->p_remote);
466 	wg_timers_disable(peer);
467 
468 	/* Now we can remove all allowed IPs so no more packets will be routed
469 	 * to the peer. */
470 	wg_aip_remove_all(sc, peer);
471 
472 	/* Remove peer from the interface, then free. Some references may still
473 	 * exist to p_remote, so noise_remote_free will wait until they're all
474 	 * put to call wg_peer_free_deferred. */
475 	sc->sc_peers_num--;
476 	TAILQ_REMOVE(&sc->sc_peers, peer, p_entry);
477 	DPRINTF(sc, "Peer %" PRIu64 " destroyed\n", peer->p_id);
478 	noise_remote_free(peer->p_remote, wg_peer_free_deferred);
479 }
480 
481 static void
wg_peer_destroy_all(struct wg_softc * sc)482 wg_peer_destroy_all(struct wg_softc *sc)
483 {
484 	struct wg_peer *peer, *tpeer;
485 	TAILQ_FOREACH_SAFE(peer, &sc->sc_peers, p_entry, tpeer)
486 		wg_peer_destroy(peer);
487 }
488 
489 static void
wg_peer_set_endpoint(struct wg_peer * peer,struct wg_endpoint * e)490 wg_peer_set_endpoint(struct wg_peer *peer, struct wg_endpoint *e)
491 {
492 	MPASS(e->e_remote.r_sa.sa_family != 0);
493 	if (memcmp(e, &peer->p_endpoint, sizeof(*e)) == 0)
494 		return;
495 
496 	rw_wlock(&peer->p_endpoint_lock);
497 	peer->p_endpoint = *e;
498 	rw_wunlock(&peer->p_endpoint_lock);
499 }
500 
501 static void
wg_peer_clear_src(struct wg_peer * peer)502 wg_peer_clear_src(struct wg_peer *peer)
503 {
504 	rw_wlock(&peer->p_endpoint_lock);
505 	bzero(&peer->p_endpoint.e_local, sizeof(peer->p_endpoint.e_local));
506 	rw_wunlock(&peer->p_endpoint_lock);
507 }
508 
509 static void
wg_peer_get_endpoint(struct wg_peer * peer,struct wg_endpoint * e)510 wg_peer_get_endpoint(struct wg_peer *peer, struct wg_endpoint *e)
511 {
512 	rw_rlock(&peer->p_endpoint_lock);
513 	*e = peer->p_endpoint;
514 	rw_runlock(&peer->p_endpoint_lock);
515 }
516 
517 /* Allowed IP */
518 static int
wg_aip_add(struct wg_softc * sc,struct wg_peer * peer,sa_family_t af,const void * addr,uint8_t cidr)519 wg_aip_add(struct wg_softc *sc, struct wg_peer *peer, sa_family_t af, const void *addr, uint8_t cidr)
520 {
521 	struct radix_node_head	*root;
522 	struct radix_node	*node;
523 	struct wg_aip		*aip;
524 	int			 ret = 0;
525 
526 	aip = malloc(sizeof(*aip), M_WG, M_WAITOK | M_ZERO);
527 	aip->a_peer = peer;
528 	aip->a_af = af;
529 
530 	switch (af) {
531 #ifdef INET
532 	case AF_INET:
533 		if (cidr > 32) cidr = 32;
534 		root = sc->sc_aip4;
535 		aip->a_addr.in = *(const struct in_addr *)addr;
536 		aip->a_mask.ip = htonl(~((1LL << (32 - cidr)) - 1) & 0xffffffff);
537 		aip->a_addr.ip &= aip->a_mask.ip;
538 		aip->a_addr.length = aip->a_mask.length = offsetof(struct aip_addr, in) + sizeof(struct in_addr);
539 		break;
540 #endif
541 #ifdef INET6
542 	case AF_INET6:
543 		if (cidr > 128) cidr = 128;
544 		root = sc->sc_aip6;
545 		aip->a_addr.in6 = *(const struct in6_addr *)addr;
546 		in6_prefixlen2mask(&aip->a_mask.in6, cidr);
547 		for (int i = 0; i < 4; i++)
548 			aip->a_addr.ip6[i] &= aip->a_mask.ip6[i];
549 		aip->a_addr.length = aip->a_mask.length = offsetof(struct aip_addr, in6) + sizeof(struct in6_addr);
550 		break;
551 #endif
552 	default:
553 		free(aip, M_WG);
554 		return (EAFNOSUPPORT);
555 	}
556 
557 	RADIX_NODE_HEAD_LOCK(root);
558 	node = root->rnh_addaddr(&aip->a_addr, &aip->a_mask, &root->rh, aip->a_nodes);
559 	if (node == aip->a_nodes) {
560 		LIST_INSERT_HEAD(&peer->p_aips, aip, a_entry);
561 		peer->p_aips_num++;
562 	} else if (!node)
563 		node = root->rnh_lookup(&aip->a_addr, &aip->a_mask, &root->rh);
564 	if (!node) {
565 		free(aip, M_WG);
566 		ret = ENOMEM;
567 	} else if (node != aip->a_nodes) {
568 		free(aip, M_WG);
569 		aip = (struct wg_aip *)node;
570 		if (aip->a_peer != peer) {
571 			LIST_REMOVE(aip, a_entry);
572 			aip->a_peer->p_aips_num--;
573 			aip->a_peer = peer;
574 			LIST_INSERT_HEAD(&peer->p_aips, aip, a_entry);
575 			aip->a_peer->p_aips_num++;
576 		}
577 	}
578 	RADIX_NODE_HEAD_UNLOCK(root);
579 	return (ret);
580 }
581 
582 static struct wg_peer *
wg_aip_lookup(struct wg_softc * sc,sa_family_t af,void * a)583 wg_aip_lookup(struct wg_softc *sc, sa_family_t af, void *a)
584 {
585 	struct radix_node_head	*root;
586 	struct radix_node	*node;
587 	struct wg_peer		*peer;
588 	struct aip_addr		 addr;
589 	RADIX_NODE_HEAD_RLOCK_TRACKER;
590 
591 	switch (af) {
592 	case AF_INET:
593 		root = sc->sc_aip4;
594 		memcpy(&addr.in, a, sizeof(addr.in));
595 		addr.length = offsetof(struct aip_addr, in) + sizeof(struct in_addr);
596 		break;
597 	case AF_INET6:
598 		root = sc->sc_aip6;
599 		memcpy(&addr.in6, a, sizeof(addr.in6));
600 		addr.length = offsetof(struct aip_addr, in6) + sizeof(struct in6_addr);
601 		break;
602 	default:
603 		return NULL;
604 	}
605 
606 	RADIX_NODE_HEAD_RLOCK(root);
607 	node = root->rnh_matchaddr(&addr, &root->rh);
608 	if (node != NULL) {
609 		peer = ((struct wg_aip *)node)->a_peer;
610 		noise_remote_ref(peer->p_remote);
611 	} else {
612 		peer = NULL;
613 	}
614 	RADIX_NODE_HEAD_RUNLOCK(root);
615 
616 	return (peer);
617 }
618 
619 static void
wg_aip_remove_all(struct wg_softc * sc,struct wg_peer * peer)620 wg_aip_remove_all(struct wg_softc *sc, struct wg_peer *peer)
621 {
622 	struct wg_aip		*aip, *taip;
623 
624 	RADIX_NODE_HEAD_LOCK(sc->sc_aip4);
625 	LIST_FOREACH_SAFE(aip, &peer->p_aips, a_entry, taip) {
626 		if (aip->a_af == AF_INET) {
627 			if (sc->sc_aip4->rnh_deladdr(&aip->a_addr, &aip->a_mask, &sc->sc_aip4->rh) == NULL)
628 				panic("failed to delete aip %p", aip);
629 			LIST_REMOVE(aip, a_entry);
630 			peer->p_aips_num--;
631 			free(aip, M_WG);
632 		}
633 	}
634 	RADIX_NODE_HEAD_UNLOCK(sc->sc_aip4);
635 
636 	RADIX_NODE_HEAD_LOCK(sc->sc_aip6);
637 	LIST_FOREACH_SAFE(aip, &peer->p_aips, a_entry, taip) {
638 		if (aip->a_af == AF_INET6) {
639 			if (sc->sc_aip6->rnh_deladdr(&aip->a_addr, &aip->a_mask, &sc->sc_aip6->rh) == NULL)
640 				panic("failed to delete aip %p", aip);
641 			LIST_REMOVE(aip, a_entry);
642 			peer->p_aips_num--;
643 			free(aip, M_WG);
644 		}
645 	}
646 	RADIX_NODE_HEAD_UNLOCK(sc->sc_aip6);
647 
648 	if (!LIST_EMPTY(&peer->p_aips) || peer->p_aips_num != 0)
649 		panic("wg_aip_remove_all could not delete all %p", peer);
650 }
651 
652 static int
wg_socket_init(struct wg_softc * sc,in_port_t port)653 wg_socket_init(struct wg_softc *sc, in_port_t port)
654 {
655 	struct ucred *cred = sc->sc_ucred;
656 	struct socket *so4 = NULL, *so6 = NULL;
657 	int rc;
658 
659 	sx_assert(&sc->sc_lock, SX_XLOCKED);
660 
661 	if (!cred)
662 		return (EBUSY);
663 
664 	/*
665 	 * For socket creation, we use the creds of the thread that created the
666 	 * tunnel rather than the current thread to maintain the semantics that
667 	 * WireGuard has on Linux with network namespaces -- that the sockets
668 	 * are created in their home vnet so that they can be configured and
669 	 * functionally attached to a foreign vnet as the jail's only interface
670 	 * to the network.
671 	 */
672 #ifdef INET
673 	rc = socreate(AF_INET, &so4, SOCK_DGRAM, IPPROTO_UDP, cred, curthread);
674 	if (rc)
675 		goto out;
676 
677 	rc = udp_set_kernel_tunneling(so4, wg_input, NULL, sc);
678 	/*
679 	 * udp_set_kernel_tunneling can only fail if there is already a tunneling function set.
680 	 * This should never happen with a new socket.
681 	 */
682 	MPASS(rc == 0);
683 #endif
684 
685 #ifdef INET6
686 	rc = socreate(AF_INET6, &so6, SOCK_DGRAM, IPPROTO_UDP, cred, curthread);
687 	if (rc)
688 		goto out;
689 	rc = udp_set_kernel_tunneling(so6, wg_input, NULL, sc);
690 	MPASS(rc == 0);
691 #endif
692 
693 	if (sc->sc_socket.so_user_cookie) {
694 		rc = wg_socket_set_sockopt(so4, so6, SO_USER_COOKIE, &sc->sc_socket.so_user_cookie, sizeof(sc->sc_socket.so_user_cookie));
695 		if (rc)
696 			goto out;
697 	}
698 	rc = wg_socket_set_sockopt(so4, so6, SO_SETFIB, &sc->sc_socket.so_fibnum, sizeof(sc->sc_socket.so_fibnum));
699 	if (rc)
700 		goto out;
701 
702 	rc = wg_socket_bind(&so4, &so6, &port);
703 	if (!rc) {
704 		sc->sc_socket.so_port = port;
705 		wg_socket_set(sc, so4, so6);
706 	}
707 out:
708 	if (rc) {
709 		if (so4 != NULL)
710 			soclose(so4);
711 		if (so6 != NULL)
712 			soclose(so6);
713 	}
714 	return (rc);
715 }
716 
wg_socket_set_sockopt(struct socket * so4,struct socket * so6,int name,void * val,size_t len)717 static int wg_socket_set_sockopt(struct socket *so4, struct socket *so6, int name, void *val, size_t len)
718 {
719 	int ret4 = 0, ret6 = 0;
720 	struct sockopt sopt = {
721 		.sopt_dir = SOPT_SET,
722 		.sopt_level = SOL_SOCKET,
723 		.sopt_name = name,
724 		.sopt_val = val,
725 		.sopt_valsize = len
726 	};
727 
728 	if (so4)
729 		ret4 = sosetopt(so4, &sopt);
730 	if (so6)
731 		ret6 = sosetopt(so6, &sopt);
732 	return (ret4 ?: ret6);
733 }
734 
wg_socket_set_cookie(struct wg_softc * sc,uint32_t user_cookie)735 static int wg_socket_set_cookie(struct wg_softc *sc, uint32_t user_cookie)
736 {
737 	struct wg_socket *so = &sc->sc_socket;
738 	int ret;
739 
740 	sx_assert(&sc->sc_lock, SX_XLOCKED);
741 	ret = wg_socket_set_sockopt(so->so_so4, so->so_so6, SO_USER_COOKIE, &user_cookie, sizeof(user_cookie));
742 	if (!ret)
743 		so->so_user_cookie = user_cookie;
744 	return (ret);
745 }
746 
wg_socket_set_fibnum(struct wg_softc * sc,int fibnum)747 static int wg_socket_set_fibnum(struct wg_softc *sc, int fibnum)
748 {
749 	struct wg_socket *so = &sc->sc_socket;
750 	int ret;
751 
752 	sx_assert(&sc->sc_lock, SX_XLOCKED);
753 
754 	ret = wg_socket_set_sockopt(so->so_so4, so->so_so6, SO_SETFIB, &fibnum, sizeof(fibnum));
755 	if (!ret)
756 		so->so_fibnum = fibnum;
757 	return (ret);
758 }
759 
760 static void
wg_socket_uninit(struct wg_softc * sc)761 wg_socket_uninit(struct wg_softc *sc)
762 {
763 	wg_socket_set(sc, NULL, NULL);
764 }
765 
766 static void
wg_socket_set(struct wg_softc * sc,struct socket * new_so4,struct socket * new_so6)767 wg_socket_set(struct wg_softc *sc, struct socket *new_so4, struct socket *new_so6)
768 {
769 	struct wg_socket *so = &sc->sc_socket;
770 	struct socket *so4, *so6;
771 
772 	sx_assert(&sc->sc_lock, SX_XLOCKED);
773 
774 	so4 = atomic_load_ptr(&so->so_so4);
775 	so6 = atomic_load_ptr(&so->so_so6);
776 	atomic_store_ptr(&so->so_so4, new_so4);
777 	atomic_store_ptr(&so->so_so6, new_so6);
778 
779 	if (!so4 && !so6)
780 		return;
781 	NET_EPOCH_WAIT();
782 	if (so4)
783 		soclose(so4);
784 	if (so6)
785 		soclose(so6);
786 }
787 
788 static int
wg_socket_bind(struct socket ** in_so4,struct socket ** in_so6,in_port_t * requested_port)789 wg_socket_bind(struct socket **in_so4, struct socket **in_so6, in_port_t *requested_port)
790 {
791 	struct socket *so4 = *in_so4, *so6 = *in_so6;
792 	int ret4 = 0, ret6 = 0;
793 	in_port_t port = *requested_port;
794 	struct sockaddr_in sin = {
795 		.sin_len = sizeof(struct sockaddr_in),
796 		.sin_family = AF_INET,
797 		.sin_port = htons(port)
798 	};
799 	struct sockaddr_in6 sin6 = {
800 		.sin6_len = sizeof(struct sockaddr_in6),
801 		.sin6_family = AF_INET6,
802 		.sin6_port = htons(port)
803 	};
804 
805 	if (so4) {
806 		ret4 = sobind(so4, (struct sockaddr *)&sin, curthread);
807 		if (ret4 && ret4 != EADDRNOTAVAIL)
808 			return (ret4);
809 		if (!ret4 && !sin.sin_port) {
810 			struct sockaddr_in *bound_sin;
811 			int ret = so4->so_proto->pr_usrreqs->pru_sockaddr(so4,
812 			    (struct sockaddr **)&bound_sin);
813 			if (ret)
814 				return (ret);
815 			port = ntohs(bound_sin->sin_port);
816 			sin6.sin6_port = bound_sin->sin_port;
817 			free(bound_sin, M_SONAME);
818 		}
819 	}
820 
821 	if (so6) {
822 		ret6 = sobind(so6, (struct sockaddr *)&sin6, curthread);
823 		if (ret6 && ret6 != EADDRNOTAVAIL)
824 			return (ret6);
825 		if (!ret6 && !sin6.sin6_port) {
826 			struct sockaddr_in6 *bound_sin6;
827 			int ret = so6->so_proto->pr_usrreqs->pru_sockaddr(so6,
828 			    (struct sockaddr **)&bound_sin6);
829 			if (ret)
830 				return (ret);
831 			port = ntohs(bound_sin6->sin6_port);
832 			free(bound_sin6, M_SONAME);
833 		}
834 	}
835 
836 	if (ret4 && ret6)
837 		return (ret4);
838 	*requested_port = port;
839 	if (ret4 && !ret6 && so4) {
840 		soclose(so4);
841 		*in_so4 = NULL;
842 	} else if (ret6 && !ret4 && so6) {
843 		soclose(so6);
844 		*in_so6 = NULL;
845 	}
846 	return (0);
847 }
848 
849 static int
wg_send(struct wg_softc * sc,struct wg_endpoint * e,struct mbuf * m)850 wg_send(struct wg_softc *sc, struct wg_endpoint *e, struct mbuf *m)
851 {
852 	struct epoch_tracker et;
853 	struct sockaddr *sa;
854 	struct wg_socket *so = &sc->sc_socket;
855 	struct socket *so4, *so6;
856 	struct mbuf *control = NULL;
857 	int ret = 0;
858 	size_t len = m->m_pkthdr.len;
859 
860 	/* Get local control address before locking */
861 	if (e->e_remote.r_sa.sa_family == AF_INET) {
862 		if (e->e_local.l_in.s_addr != INADDR_ANY)
863 			control = sbcreatecontrol((caddr_t)&e->e_local.l_in,
864 			    sizeof(struct in_addr), IP_SENDSRCADDR,
865 			    IPPROTO_IP);
866 #ifdef INET6
867 	} else if (e->e_remote.r_sa.sa_family == AF_INET6) {
868 		if (!IN6_IS_ADDR_UNSPECIFIED(&e->e_local.l_in6))
869 			control = sbcreatecontrol((caddr_t)&e->e_local.l_pktinfo6,
870 			    sizeof(struct in6_pktinfo), IPV6_PKTINFO,
871 			    IPPROTO_IPV6);
872 #endif
873 	} else {
874 		m_freem(m);
875 		return (EAFNOSUPPORT);
876 	}
877 
878 	/* Get remote address */
879 	sa = &e->e_remote.r_sa;
880 
881 	NET_EPOCH_ENTER(et);
882 	so4 = atomic_load_ptr(&so->so_so4);
883 	so6 = atomic_load_ptr(&so->so_so6);
884 	if (e->e_remote.r_sa.sa_family == AF_INET && so4 != NULL)
885 		ret = sosend(so4, sa, NULL, m, control, 0, curthread);
886 	else if (e->e_remote.r_sa.sa_family == AF_INET6 && so6 != NULL)
887 		ret = sosend(so6, sa, NULL, m, control, 0, curthread);
888 	else {
889 		ret = ENOTCONN;
890 		m_freem(control);
891 		m_freem(m);
892 	}
893 	NET_EPOCH_EXIT(et);
894 	if (ret == 0) {
895 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OPACKETS, 1);
896 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OBYTES, len);
897 	}
898 	return (ret);
899 }
900 
901 static void
wg_send_buf(struct wg_softc * sc,struct wg_endpoint * e,uint8_t * buf,size_t len)902 wg_send_buf(struct wg_softc *sc, struct wg_endpoint *e, uint8_t *buf, size_t len)
903 {
904 	struct mbuf	*m;
905 	int		 ret = 0;
906 	bool		 retried = false;
907 
908 retry:
909 	m = m_get2(len, M_NOWAIT, MT_DATA, M_PKTHDR);
910 	if (!m) {
911 		ret = ENOMEM;
912 		goto out;
913 	}
914 	m_copyback(m, 0, len, buf);
915 
916 	if (ret == 0) {
917 		ret = wg_send(sc, e, m);
918 		/* Retry if we couldn't bind to e->e_local */
919 		if (ret == EADDRNOTAVAIL && !retried) {
920 			bzero(&e->e_local, sizeof(e->e_local));
921 			retried = true;
922 			goto retry;
923 		}
924 	} else {
925 		ret = wg_send(sc, e, m);
926 	}
927 out:
928 	if (ret)
929 		DPRINTF(sc, "Unable to send packet: %d\n", ret);
930 }
931 
932 /* Timers */
933 static void
wg_timers_enable(struct wg_peer * peer)934 wg_timers_enable(struct wg_peer *peer)
935 {
936 	atomic_store_bool(&peer->p_enabled, true);
937 	wg_timers_run_persistent_keepalive(peer);
938 }
939 
940 static void
wg_timers_disable(struct wg_peer * peer)941 wg_timers_disable(struct wg_peer *peer)
942 {
943 	/* By setting p_enabled = false, then calling NET_EPOCH_WAIT, we can be
944 	 * sure no new handshakes are created after the wait. This is because
945 	 * all callout_resets (scheduling the callout) are guarded by
946 	 * p_enabled. We can be sure all sections that read p_enabled and then
947 	 * optionally call callout_reset are finished as they are surrounded by
948 	 * NET_EPOCH_{ENTER,EXIT}.
949 	 *
950 	 * However, as new callouts may be scheduled during NET_EPOCH_WAIT (but
951 	 * not after), we stop all callouts leaving no callouts active.
952 	 *
953 	 * We should also pull NET_EPOCH_WAIT out of the FOREACH(peer) loops, but the
954 	 * performance impact is acceptable for the time being. */
955 	atomic_store_bool(&peer->p_enabled, false);
956 	NET_EPOCH_WAIT();
957 	atomic_store_bool(&peer->p_need_another_keepalive, false);
958 
959 	callout_stop(&peer->p_new_handshake);
960 	callout_stop(&peer->p_send_keepalive);
961 	callout_stop(&peer->p_retry_handshake);
962 	callout_stop(&peer->p_persistent_keepalive);
963 	callout_stop(&peer->p_zero_key_material);
964 }
965 
966 static void
wg_timers_set_persistent_keepalive(struct wg_peer * peer,uint16_t interval)967 wg_timers_set_persistent_keepalive(struct wg_peer *peer, uint16_t interval)
968 {
969 	struct epoch_tracker et;
970 	if (interval != peer->p_persistent_keepalive_interval) {
971 		atomic_store_16(&peer->p_persistent_keepalive_interval, interval);
972 		NET_EPOCH_ENTER(et);
973 		if (atomic_load_bool(&peer->p_enabled))
974 			wg_timers_run_persistent_keepalive(peer);
975 		NET_EPOCH_EXIT(et);
976 	}
977 }
978 
979 static void
wg_timers_get_last_handshake(struct wg_peer * peer,struct wg_timespec64 * time)980 wg_timers_get_last_handshake(struct wg_peer *peer, struct wg_timespec64 *time)
981 {
982 	mtx_lock(&peer->p_handshake_mtx);
983 	time->tv_sec = peer->p_handshake_complete.tv_sec;
984 	time->tv_nsec = peer->p_handshake_complete.tv_nsec;
985 	mtx_unlock(&peer->p_handshake_mtx);
986 }
987 
988 static void
wg_timers_event_data_sent(struct wg_peer * peer)989 wg_timers_event_data_sent(struct wg_peer *peer)
990 {
991 	struct epoch_tracker et;
992 	NET_EPOCH_ENTER(et);
993 	if (atomic_load_bool(&peer->p_enabled) &&
994 	    !callout_pending(&peer->p_new_handshake))
995 		callout_reset(&peer->p_new_handshake, MSEC_2_TICKS(
996 		    NEW_HANDSHAKE_TIMEOUT * 1000 +
997 		    arc4random_uniform(REKEY_TIMEOUT_JITTER)),
998 		    wg_timers_run_new_handshake, peer);
999 	NET_EPOCH_EXIT(et);
1000 }
1001 
1002 static void
wg_timers_event_data_received(struct wg_peer * peer)1003 wg_timers_event_data_received(struct wg_peer *peer)
1004 {
1005 	struct epoch_tracker et;
1006 	NET_EPOCH_ENTER(et);
1007 	if (atomic_load_bool(&peer->p_enabled)) {
1008 		if (!callout_pending(&peer->p_send_keepalive))
1009 			callout_reset(&peer->p_send_keepalive,
1010 			    MSEC_2_TICKS(KEEPALIVE_TIMEOUT * 1000),
1011 			    wg_timers_run_send_keepalive, peer);
1012 		else
1013 			atomic_store_bool(&peer->p_need_another_keepalive,
1014 			    true);
1015 	}
1016 	NET_EPOCH_EXIT(et);
1017 }
1018 
1019 static void
wg_timers_event_any_authenticated_packet_sent(struct wg_peer * peer)1020 wg_timers_event_any_authenticated_packet_sent(struct wg_peer *peer)
1021 {
1022 	callout_stop(&peer->p_send_keepalive);
1023 }
1024 
1025 static void
wg_timers_event_any_authenticated_packet_received(struct wg_peer * peer)1026 wg_timers_event_any_authenticated_packet_received(struct wg_peer *peer)
1027 {
1028 	callout_stop(&peer->p_new_handshake);
1029 }
1030 
1031 static void
wg_timers_event_any_authenticated_packet_traversal(struct wg_peer * peer)1032 wg_timers_event_any_authenticated_packet_traversal(struct wg_peer *peer)
1033 {
1034 	struct epoch_tracker et;
1035 	uint16_t interval;
1036 	NET_EPOCH_ENTER(et);
1037 	interval = atomic_load_16(&peer->p_persistent_keepalive_interval);
1038 	if (atomic_load_bool(&peer->p_enabled) && interval > 0)
1039 		callout_reset(&peer->p_persistent_keepalive,
1040 		     MSEC_2_TICKS(interval * 1000),
1041 		     wg_timers_run_persistent_keepalive, peer);
1042 	NET_EPOCH_EXIT(et);
1043 }
1044 
1045 static void
wg_timers_event_handshake_initiated(struct wg_peer * peer)1046 wg_timers_event_handshake_initiated(struct wg_peer *peer)
1047 {
1048 	struct epoch_tracker et;
1049 	NET_EPOCH_ENTER(et);
1050 	if (atomic_load_bool(&peer->p_enabled))
1051 		callout_reset(&peer->p_retry_handshake, MSEC_2_TICKS(
1052 		    REKEY_TIMEOUT * 1000 +
1053 		    arc4random_uniform(REKEY_TIMEOUT_JITTER)),
1054 		    wg_timers_run_retry_handshake, peer);
1055 	NET_EPOCH_EXIT(et);
1056 }
1057 
1058 static void
wg_timers_event_handshake_complete(struct wg_peer * peer)1059 wg_timers_event_handshake_complete(struct wg_peer *peer)
1060 {
1061 	struct epoch_tracker et;
1062 	NET_EPOCH_ENTER(et);
1063 	if (atomic_load_bool(&peer->p_enabled)) {
1064 		mtx_lock(&peer->p_handshake_mtx);
1065 		callout_stop(&peer->p_retry_handshake);
1066 		peer->p_handshake_retries = 0;
1067 		getnanotime(&peer->p_handshake_complete);
1068 		mtx_unlock(&peer->p_handshake_mtx);
1069 		wg_timers_run_send_keepalive(peer);
1070 	}
1071 	NET_EPOCH_EXIT(et);
1072 }
1073 
1074 static void
wg_timers_event_session_derived(struct wg_peer * peer)1075 wg_timers_event_session_derived(struct wg_peer *peer)
1076 {
1077 	struct epoch_tracker et;
1078 	NET_EPOCH_ENTER(et);
1079 	if (atomic_load_bool(&peer->p_enabled))
1080 		callout_reset(&peer->p_zero_key_material,
1081 		    MSEC_2_TICKS(REJECT_AFTER_TIME * 3 * 1000),
1082 		    wg_timers_run_zero_key_material, peer);
1083 	NET_EPOCH_EXIT(et);
1084 }
1085 
1086 static void
wg_timers_event_want_initiation(struct wg_peer * peer)1087 wg_timers_event_want_initiation(struct wg_peer *peer)
1088 {
1089 	struct epoch_tracker et;
1090 	NET_EPOCH_ENTER(et);
1091 	if (atomic_load_bool(&peer->p_enabled))
1092 		wg_timers_run_send_initiation(peer, false);
1093 	NET_EPOCH_EXIT(et);
1094 }
1095 
1096 static void
wg_timers_run_send_initiation(struct wg_peer * peer,bool is_retry)1097 wg_timers_run_send_initiation(struct wg_peer *peer, bool is_retry)
1098 {
1099 	if (!is_retry)
1100 		peer->p_handshake_retries = 0;
1101 	if (noise_remote_initiation_expired(peer->p_remote) == ETIMEDOUT)
1102 		wg_send_initiation(peer);
1103 }
1104 
1105 static void
wg_timers_run_retry_handshake(void * _peer)1106 wg_timers_run_retry_handshake(void *_peer)
1107 {
1108 	struct epoch_tracker et;
1109 	struct wg_peer *peer = _peer;
1110 
1111 	mtx_lock(&peer->p_handshake_mtx);
1112 	if (peer->p_handshake_retries <= MAX_TIMER_HANDSHAKES) {
1113 		peer->p_handshake_retries++;
1114 		mtx_unlock(&peer->p_handshake_mtx);
1115 
1116 		DPRINTF(peer->p_sc, "Handshake for peer %" PRIu64 " did not complete "
1117 		    "after %d seconds, retrying (try %d)\n", peer->p_id,
1118 		    REKEY_TIMEOUT, peer->p_handshake_retries + 1);
1119 		wg_peer_clear_src(peer);
1120 		wg_timers_run_send_initiation(peer, true);
1121 	} else {
1122 		mtx_unlock(&peer->p_handshake_mtx);
1123 
1124 		DPRINTF(peer->p_sc, "Handshake for peer %" PRIu64 " did not complete "
1125 		    "after %d retries, giving up\n", peer->p_id,
1126 		    MAX_TIMER_HANDSHAKES + 2);
1127 
1128 		callout_stop(&peer->p_send_keepalive);
1129 		wg_queue_purge(&peer->p_stage_queue);
1130 		NET_EPOCH_ENTER(et);
1131 		if (atomic_load_bool(&peer->p_enabled) &&
1132 		    !callout_pending(&peer->p_zero_key_material))
1133 			callout_reset(&peer->p_zero_key_material,
1134 			    MSEC_2_TICKS(REJECT_AFTER_TIME * 3 * 1000),
1135 			    wg_timers_run_zero_key_material, peer);
1136 		NET_EPOCH_EXIT(et);
1137 	}
1138 }
1139 
1140 static void
wg_timers_run_send_keepalive(void * _peer)1141 wg_timers_run_send_keepalive(void *_peer)
1142 {
1143 	struct epoch_tracker et;
1144 	struct wg_peer *peer = _peer;
1145 
1146 	wg_send_keepalive(peer);
1147 	NET_EPOCH_ENTER(et);
1148 	if (atomic_load_bool(&peer->p_enabled) &&
1149 	    atomic_load_bool(&peer->p_need_another_keepalive)) {
1150 		atomic_store_bool(&peer->p_need_another_keepalive, false);
1151 		callout_reset(&peer->p_send_keepalive,
1152 		    MSEC_2_TICKS(KEEPALIVE_TIMEOUT * 1000),
1153 		    wg_timers_run_send_keepalive, peer);
1154 	}
1155 	NET_EPOCH_EXIT(et);
1156 }
1157 
1158 static void
wg_timers_run_new_handshake(void * _peer)1159 wg_timers_run_new_handshake(void *_peer)
1160 {
1161 	struct wg_peer *peer = _peer;
1162 
1163 	DPRINTF(peer->p_sc, "Retrying handshake with peer %" PRIu64 " because we "
1164 	    "stopped hearing back after %d seconds\n",
1165 	    peer->p_id, NEW_HANDSHAKE_TIMEOUT);
1166 
1167 	wg_peer_clear_src(peer);
1168 	wg_timers_run_send_initiation(peer, false);
1169 }
1170 
1171 static void
wg_timers_run_zero_key_material(void * _peer)1172 wg_timers_run_zero_key_material(void *_peer)
1173 {
1174 	struct wg_peer *peer = _peer;
1175 
1176 	DPRINTF(peer->p_sc, "Zeroing out keys for peer %" PRIu64 ", since we "
1177 	    "haven't received a new one in %d seconds\n",
1178 	    peer->p_id, REJECT_AFTER_TIME * 3);
1179 	noise_remote_keypairs_clear(peer->p_remote);
1180 }
1181 
1182 static void
wg_timers_run_persistent_keepalive(void * _peer)1183 wg_timers_run_persistent_keepalive(void *_peer)
1184 {
1185 	struct wg_peer *peer = _peer;
1186 
1187 	if (atomic_load_16(&peer->p_persistent_keepalive_interval) > 0)
1188 		wg_send_keepalive(peer);
1189 }
1190 
1191 /* TODO Handshake */
1192 static void
wg_peer_send_buf(struct wg_peer * peer,uint8_t * buf,size_t len)1193 wg_peer_send_buf(struct wg_peer *peer, uint8_t *buf, size_t len)
1194 {
1195 	struct wg_endpoint endpoint;
1196 
1197 	counter_u64_add(peer->p_tx_bytes, len);
1198 	wg_timers_event_any_authenticated_packet_traversal(peer);
1199 	wg_timers_event_any_authenticated_packet_sent(peer);
1200 	wg_peer_get_endpoint(peer, &endpoint);
1201 	wg_send_buf(peer->p_sc, &endpoint, buf, len);
1202 }
1203 
1204 static void
wg_send_initiation(struct wg_peer * peer)1205 wg_send_initiation(struct wg_peer *peer)
1206 {
1207 	struct wg_pkt_initiation pkt;
1208 
1209 	if (noise_create_initiation(peer->p_remote, &pkt.s_idx, pkt.ue,
1210 	    pkt.es, pkt.ets) != 0)
1211 		return;
1212 
1213 	DPRINTF(peer->p_sc, "Sending handshake initiation to peer %" PRIu64 "\n", peer->p_id);
1214 
1215 	pkt.t = WG_PKT_INITIATION;
1216 	cookie_maker_mac(&peer->p_cookie, &pkt.m, &pkt,
1217 	    sizeof(pkt) - sizeof(pkt.m));
1218 	wg_peer_send_buf(peer, (uint8_t *)&pkt, sizeof(pkt));
1219 	wg_timers_event_handshake_initiated(peer);
1220 }
1221 
1222 static void
wg_send_response(struct wg_peer * peer)1223 wg_send_response(struct wg_peer *peer)
1224 {
1225 	struct wg_pkt_response pkt;
1226 
1227 	if (noise_create_response(peer->p_remote, &pkt.s_idx, &pkt.r_idx,
1228 	    pkt.ue, pkt.en) != 0)
1229 		return;
1230 
1231 	DPRINTF(peer->p_sc, "Sending handshake response to peer %" PRIu64 "\n", peer->p_id);
1232 
1233 	wg_timers_event_session_derived(peer);
1234 	pkt.t = WG_PKT_RESPONSE;
1235 	cookie_maker_mac(&peer->p_cookie, &pkt.m, &pkt,
1236 	     sizeof(pkt)-sizeof(pkt.m));
1237 	wg_peer_send_buf(peer, (uint8_t*)&pkt, sizeof(pkt));
1238 }
1239 
1240 static void
wg_send_cookie(struct wg_softc * sc,struct cookie_macs * cm,uint32_t idx,struct wg_endpoint * e)1241 wg_send_cookie(struct wg_softc *sc, struct cookie_macs *cm, uint32_t idx,
1242     struct wg_endpoint *e)
1243 {
1244 	struct wg_pkt_cookie	pkt;
1245 
1246 	DPRINTF(sc, "Sending cookie response for denied handshake message\n");
1247 
1248 	pkt.t = WG_PKT_COOKIE;
1249 	pkt.r_idx = idx;
1250 
1251 	cookie_checker_create_payload(&sc->sc_cookie, cm, pkt.nonce,
1252 	    pkt.ec, &e->e_remote.r_sa);
1253 	wg_send_buf(sc, e, (uint8_t *)&pkt, sizeof(pkt));
1254 }
1255 
1256 static void
wg_send_keepalive(struct wg_peer * peer)1257 wg_send_keepalive(struct wg_peer *peer)
1258 {
1259 	struct wg_packet *pkt;
1260 	struct mbuf *m;
1261 
1262 	if (wg_queue_len(&peer->p_stage_queue) > 0)
1263 		goto send;
1264 	if ((m = m_gethdr(M_NOWAIT, MT_DATA)) == NULL)
1265 		return;
1266 	if ((pkt = wg_packet_alloc(m)) == NULL) {
1267 		m_freem(m);
1268 		return;
1269 	}
1270 	wg_queue_push_staged(&peer->p_stage_queue, pkt);
1271 	DPRINTF(peer->p_sc, "Sending keepalive packet to peer %" PRIu64 "\n", peer->p_id);
1272 send:
1273 	wg_peer_send_staged(peer);
1274 }
1275 
1276 static void
wg_handshake(struct wg_softc * sc,struct wg_packet * pkt)1277 wg_handshake(struct wg_softc *sc, struct wg_packet *pkt)
1278 {
1279 	struct wg_pkt_initiation	*init;
1280 	struct wg_pkt_response		*resp;
1281 	struct wg_pkt_cookie		*cook;
1282 	struct wg_endpoint		*e;
1283 	struct wg_peer			*peer;
1284 	struct mbuf			*m;
1285 	struct noise_remote		*remote = NULL;
1286 	int				 res;
1287 	bool				 underload = false;
1288 	static sbintime_t		 wg_last_underload; /* sbinuptime */
1289 
1290 	underload = wg_queue_len(&sc->sc_handshake_queue) >= MAX_QUEUED_HANDSHAKES / 8;
1291 	if (underload) {
1292 		wg_last_underload = getsbinuptime();
1293 	} else if (wg_last_underload) {
1294 		underload = wg_last_underload + UNDERLOAD_TIMEOUT * SBT_1S > getsbinuptime();
1295 		if (!underload)
1296 			wg_last_underload = 0;
1297 	}
1298 
1299 	m = pkt->p_mbuf;
1300 	e = &pkt->p_endpoint;
1301 
1302 	if ((pkt->p_mbuf = m = m_pullup(m, m->m_pkthdr.len)) == NULL)
1303 		goto error;
1304 
1305 	switch (*mtod(m, uint32_t *)) {
1306 	case WG_PKT_INITIATION:
1307 		init = mtod(m, struct wg_pkt_initiation *);
1308 
1309 		res = cookie_checker_validate_macs(&sc->sc_cookie, &init->m,
1310 				init, sizeof(*init) - sizeof(init->m),
1311 				underload, &e->e_remote.r_sa,
1312 				sc->sc_ifp->if_vnet);
1313 
1314 		if (res == EINVAL) {
1315 			DPRINTF(sc, "Invalid initiation MAC\n");
1316 			goto error;
1317 		} else if (res == ECONNREFUSED) {
1318 			DPRINTF(sc, "Handshake ratelimited\n");
1319 			goto error;
1320 		} else if (res == EAGAIN) {
1321 			wg_send_cookie(sc, &init->m, init->s_idx, e);
1322 			goto error;
1323 		} else if (res != 0) {
1324 			panic("unexpected response: %d\n", res);
1325 		}
1326 
1327 		if (noise_consume_initiation(sc->sc_local, &remote,
1328 		    init->s_idx, init->ue, init->es, init->ets) != 0) {
1329 			DPRINTF(sc, "Invalid handshake initiation\n");
1330 			goto error;
1331 		}
1332 
1333 		peer = noise_remote_arg(remote);
1334 
1335 		DPRINTF(sc, "Receiving handshake initiation from peer %" PRIu64 "\n", peer->p_id);
1336 
1337 		wg_peer_set_endpoint(peer, e);
1338 		wg_send_response(peer);
1339 		break;
1340 	case WG_PKT_RESPONSE:
1341 		resp = mtod(m, struct wg_pkt_response *);
1342 
1343 		res = cookie_checker_validate_macs(&sc->sc_cookie, &resp->m,
1344 				resp, sizeof(*resp) - sizeof(resp->m),
1345 				underload, &e->e_remote.r_sa,
1346 				sc->sc_ifp->if_vnet);
1347 
1348 		if (res == EINVAL) {
1349 			DPRINTF(sc, "Invalid response MAC\n");
1350 			goto error;
1351 		} else if (res == ECONNREFUSED) {
1352 			DPRINTF(sc, "Handshake ratelimited\n");
1353 			goto error;
1354 		} else if (res == EAGAIN) {
1355 			wg_send_cookie(sc, &resp->m, resp->s_idx, e);
1356 			goto error;
1357 		} else if (res != 0) {
1358 			panic("unexpected response: %d\n", res);
1359 		}
1360 
1361 		if (noise_consume_response(sc->sc_local, &remote,
1362 		    resp->s_idx, resp->r_idx, resp->ue, resp->en) != 0) {
1363 			DPRINTF(sc, "Invalid handshake response\n");
1364 			goto error;
1365 		}
1366 
1367 		peer = noise_remote_arg(remote);
1368 		DPRINTF(sc, "Receiving handshake response from peer %" PRIu64 "\n", peer->p_id);
1369 
1370 		wg_peer_set_endpoint(peer, e);
1371 		wg_timers_event_session_derived(peer);
1372 		wg_timers_event_handshake_complete(peer);
1373 		break;
1374 	case WG_PKT_COOKIE:
1375 		cook = mtod(m, struct wg_pkt_cookie *);
1376 
1377 		if ((remote = noise_remote_index(sc->sc_local, cook->r_idx)) == NULL) {
1378 			DPRINTF(sc, "Unknown cookie index\n");
1379 			goto error;
1380 		}
1381 
1382 		peer = noise_remote_arg(remote);
1383 
1384 		if (cookie_maker_consume_payload(&peer->p_cookie,
1385 		    cook->nonce, cook->ec) == 0) {
1386 			DPRINTF(sc, "Receiving cookie response\n");
1387 		} else {
1388 			DPRINTF(sc, "Could not decrypt cookie response\n");
1389 			goto error;
1390 		}
1391 
1392 		goto not_authenticated;
1393 	default:
1394 		panic("invalid packet in handshake queue");
1395 	}
1396 
1397 	wg_timers_event_any_authenticated_packet_received(peer);
1398 	wg_timers_event_any_authenticated_packet_traversal(peer);
1399 
1400 not_authenticated:
1401 	counter_u64_add(peer->p_rx_bytes, m->m_pkthdr.len);
1402 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IPACKETS, 1);
1403 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
1404 error:
1405 	if (remote != NULL)
1406 		noise_remote_put(remote);
1407 	wg_packet_free(pkt);
1408 }
1409 
1410 static void
wg_softc_handshake_receive(struct wg_softc * sc)1411 wg_softc_handshake_receive(struct wg_softc *sc)
1412 {
1413 	struct wg_packet *pkt;
1414 	while ((pkt = wg_queue_dequeue_handshake(&sc->sc_handshake_queue)) != NULL)
1415 		wg_handshake(sc, pkt);
1416 }
1417 
1418 static void
wg_mbuf_reset(struct mbuf * m)1419 wg_mbuf_reset(struct mbuf *m)
1420 {
1421 
1422 	struct m_tag *t, *tmp;
1423 
1424 	/*
1425 	 * We want to reset the mbuf to a newly allocated state, containing
1426 	 * just the packet contents. Unfortunately FreeBSD doesn't seem to
1427 	 * offer this anywhere, so we have to make it up as we go. If we can
1428 	 * get this in kern/kern_mbuf.c, that would be best.
1429 	 *
1430 	 * Notice: this may break things unexpectedly but it is better to fail
1431 	 *         closed in the extreme case than leak informtion in every
1432 	 *         case.
1433 	 *
1434 	 * With that said, all this attempts to do is remove any extraneous
1435 	 * information that could be present.
1436 	 */
1437 
1438 	M_ASSERTPKTHDR(m);
1439 
1440 	m->m_flags &= ~(M_BCAST|M_MCAST|M_VLANTAG|M_PROMISC|M_PROTOFLAGS);
1441 
1442 	M_HASHTYPE_CLEAR(m);
1443 #ifdef NUMA
1444         m->m_pkthdr.numa_domain = M_NODOM;
1445 #endif
1446 	SLIST_FOREACH_SAFE(t, &m->m_pkthdr.tags, m_tag_link, tmp) {
1447 		if ((t->m_tag_id != 0 || t->m_tag_cookie != MTAG_WGLOOP) &&
1448 		    t->m_tag_id != PACKET_TAG_MACLABEL)
1449 			m_tag_delete(m, t);
1450 	}
1451 
1452 	KASSERT((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0,
1453 	    ("%s: mbuf %p has a send tag", __func__, m));
1454 
1455 	m->m_pkthdr.csum_flags = 0;
1456 	m->m_pkthdr.PH_per.sixtyfour[0] = 0;
1457 	m->m_pkthdr.PH_loc.sixtyfour[0] = 0;
1458 }
1459 
1460 static inline unsigned int
calculate_padding(struct wg_packet * pkt)1461 calculate_padding(struct wg_packet *pkt)
1462 {
1463 	unsigned int padded_size, last_unit = pkt->p_mbuf->m_pkthdr.len;
1464 
1465 	/* Keepalive packets don't set p_mtu, but also have a length of zero. */
1466 	if (__predict_false(pkt->p_mtu == 0)) {
1467 		padded_size = (last_unit + (WG_PKT_PADDING - 1)) &
1468 		    ~(WG_PKT_PADDING - 1);
1469 		return (padded_size - last_unit);
1470 	}
1471 
1472 	if (__predict_false(last_unit > pkt->p_mtu))
1473 		last_unit %= pkt->p_mtu;
1474 
1475 	padded_size = (last_unit + (WG_PKT_PADDING - 1)) & ~(WG_PKT_PADDING - 1);
1476 	if (pkt->p_mtu < padded_size)
1477 		padded_size = pkt->p_mtu;
1478 	return (padded_size - last_unit);
1479 }
1480 
1481 static void
wg_encrypt(struct wg_softc * sc,struct wg_packet * pkt)1482 wg_encrypt(struct wg_softc *sc, struct wg_packet *pkt)
1483 {
1484 	static const uint8_t	 padding[WG_PKT_PADDING] = { 0 };
1485 	struct wg_pkt_data	*data;
1486 	struct wg_peer		*peer;
1487 	struct noise_remote	*remote;
1488 	struct mbuf		*m;
1489 	uint32_t		 idx;
1490 	unsigned int		 padlen;
1491 	enum wg_ring_state	 state = WG_PACKET_DEAD;
1492 
1493 	remote = noise_keypair_remote(pkt->p_keypair);
1494 	peer = noise_remote_arg(remote);
1495 	m = pkt->p_mbuf;
1496 
1497 	/* Pad the packet */
1498 	padlen = calculate_padding(pkt);
1499 	if (padlen != 0 && !m_append(m, padlen, padding))
1500 		goto out;
1501 
1502 	/* Do encryption */
1503 	if (noise_keypair_encrypt(pkt->p_keypair, &idx, pkt->p_nonce, m) != 0)
1504 		goto out;
1505 
1506 	/* Put header into packet */
1507 	M_PREPEND(m, sizeof(struct wg_pkt_data), M_NOWAIT);
1508 	if (m == NULL)
1509 		goto out;
1510 	data = mtod(m, struct wg_pkt_data *);
1511 	data->t = WG_PKT_DATA;
1512 	data->r_idx = idx;
1513 	data->nonce = htole64(pkt->p_nonce);
1514 
1515 	wg_mbuf_reset(m);
1516 	state = WG_PACKET_CRYPTED;
1517 out:
1518 	pkt->p_mbuf = m;
1519 	atomic_store_rel_int(&pkt->p_state, state);
1520 	GROUPTASK_ENQUEUE(&peer->p_send);
1521 	noise_remote_put(remote);
1522 }
1523 
1524 static void
wg_decrypt(struct wg_softc * sc,struct wg_packet * pkt)1525 wg_decrypt(struct wg_softc *sc, struct wg_packet *pkt)
1526 {
1527 	struct wg_peer		*peer, *allowed_peer;
1528 	struct noise_remote	*remote;
1529 	struct mbuf		*m;
1530 	int			 len;
1531 	enum wg_ring_state	 state = WG_PACKET_DEAD;
1532 
1533 	remote = noise_keypair_remote(pkt->p_keypair);
1534 	peer = noise_remote_arg(remote);
1535 	m = pkt->p_mbuf;
1536 
1537 	/* Read nonce and then adjust to remove the header. */
1538 	pkt->p_nonce = le64toh(mtod(m, struct wg_pkt_data *)->nonce);
1539 	m_adj(m, sizeof(struct wg_pkt_data));
1540 
1541 	if (noise_keypair_decrypt(pkt->p_keypair, pkt->p_nonce, m) != 0)
1542 		goto out;
1543 
1544 	/* A packet with length 0 is a keepalive packet */
1545 	if (__predict_false(m->m_pkthdr.len == 0)) {
1546 		DPRINTF(sc, "Receiving keepalive packet from peer "
1547 		    "%" PRIu64 "\n", peer->p_id);
1548 		state = WG_PACKET_CRYPTED;
1549 		goto out;
1550 	}
1551 
1552 	/*
1553 	 * We can let the network stack handle the intricate validation of the
1554 	 * IP header, we just worry about the sizeof and the version, so we can
1555 	 * read the source address in wg_aip_lookup.
1556 	 */
1557 
1558 	if (determine_af_and_pullup(&m, &pkt->p_af) == 0) {
1559 		if (pkt->p_af == AF_INET) {
1560 			struct ip *ip = mtod(m, struct ip *);
1561 			allowed_peer = wg_aip_lookup(sc, AF_INET, &ip->ip_src);
1562 			len = ntohs(ip->ip_len);
1563 			if (len >= sizeof(struct ip) && len < m->m_pkthdr.len)
1564 				m_adj(m, len - m->m_pkthdr.len);
1565 		} else if (pkt->p_af == AF_INET6) {
1566 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1567 			allowed_peer = wg_aip_lookup(sc, AF_INET6, &ip6->ip6_src);
1568 			len = ntohs(ip6->ip6_plen) + sizeof(struct ip6_hdr);
1569 			if (len < m->m_pkthdr.len)
1570 				m_adj(m, len - m->m_pkthdr.len);
1571 		} else
1572 			panic("determine_af_and_pullup returned unexpected value");
1573 	} else {
1574 		DPRINTF(sc, "Packet is neither ipv4 nor ipv6 from peer %" PRIu64 "\n", peer->p_id);
1575 		goto out;
1576 	}
1577 
1578 	/* We only want to compare the address, not dereference, so drop the ref. */
1579 	if (allowed_peer != NULL)
1580 		noise_remote_put(allowed_peer->p_remote);
1581 
1582 	if (__predict_false(peer != allowed_peer)) {
1583 		DPRINTF(sc, "Packet has unallowed src IP from peer %" PRIu64 "\n", peer->p_id);
1584 		goto out;
1585 	}
1586 
1587 	wg_mbuf_reset(m);
1588 	state = WG_PACKET_CRYPTED;
1589 out:
1590 	pkt->p_mbuf = m;
1591 	atomic_store_rel_int(&pkt->p_state, state);
1592 	GROUPTASK_ENQUEUE(&peer->p_recv);
1593 	noise_remote_put(remote);
1594 }
1595 
1596 static void
wg_softc_decrypt(struct wg_softc * sc)1597 wg_softc_decrypt(struct wg_softc *sc)
1598 {
1599 	struct wg_packet *pkt;
1600 
1601 	while ((pkt = wg_queue_dequeue_parallel(&sc->sc_decrypt_parallel)) != NULL)
1602 		wg_decrypt(sc, pkt);
1603 }
1604 
1605 static void
wg_softc_encrypt(struct wg_softc * sc)1606 wg_softc_encrypt(struct wg_softc *sc)
1607 {
1608 	struct wg_packet *pkt;
1609 
1610 	while ((pkt = wg_queue_dequeue_parallel(&sc->sc_encrypt_parallel)) != NULL)
1611 		wg_encrypt(sc, pkt);
1612 }
1613 
1614 static void
wg_encrypt_dispatch(struct wg_softc * sc)1615 wg_encrypt_dispatch(struct wg_softc *sc)
1616 {
1617 	/*
1618 	 * The update to encrypt_last_cpu is racey such that we may
1619 	 * reschedule the task for the same CPU multiple times, but
1620 	 * the race doesn't really matter.
1621 	 */
1622 	u_int cpu = (sc->sc_encrypt_last_cpu + 1) % mp_ncpus;
1623 	sc->sc_encrypt_last_cpu = cpu;
1624 	GROUPTASK_ENQUEUE(&sc->sc_encrypt[cpu]);
1625 }
1626 
1627 static void
wg_decrypt_dispatch(struct wg_softc * sc)1628 wg_decrypt_dispatch(struct wg_softc *sc)
1629 {
1630 	u_int cpu = (sc->sc_decrypt_last_cpu + 1) % mp_ncpus;
1631 	sc->sc_decrypt_last_cpu = cpu;
1632 	GROUPTASK_ENQUEUE(&sc->sc_decrypt[cpu]);
1633 }
1634 
1635 static void
wg_deliver_out(struct wg_peer * peer)1636 wg_deliver_out(struct wg_peer *peer)
1637 {
1638 	struct wg_endpoint	 endpoint;
1639 	struct wg_softc		*sc = peer->p_sc;
1640 	struct wg_packet	*pkt;
1641 	struct mbuf		*m;
1642 	int			 rc, len;
1643 
1644 	wg_peer_get_endpoint(peer, &endpoint);
1645 
1646 	while ((pkt = wg_queue_dequeue_serial(&peer->p_encrypt_serial)) != NULL) {
1647 		if (atomic_load_acq_int(&pkt->p_state) != WG_PACKET_CRYPTED)
1648 			goto error;
1649 
1650 		m = pkt->p_mbuf;
1651 		pkt->p_mbuf = NULL;
1652 
1653 		len = m->m_pkthdr.len;
1654 
1655 		wg_timers_event_any_authenticated_packet_traversal(peer);
1656 		wg_timers_event_any_authenticated_packet_sent(peer);
1657 		rc = wg_send(sc, &endpoint, m);
1658 		if (rc == 0) {
1659 			if (len > (sizeof(struct wg_pkt_data) + NOISE_AUTHTAG_LEN))
1660 				wg_timers_event_data_sent(peer);
1661 			counter_u64_add(peer->p_tx_bytes, len);
1662 		} else if (rc == EADDRNOTAVAIL) {
1663 			wg_peer_clear_src(peer);
1664 			wg_peer_get_endpoint(peer, &endpoint);
1665 			goto error;
1666 		} else {
1667 			goto error;
1668 		}
1669 		wg_packet_free(pkt);
1670 		if (noise_keep_key_fresh_send(peer->p_remote))
1671 			wg_timers_event_want_initiation(peer);
1672 		continue;
1673 error:
1674 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OERRORS, 1);
1675 		wg_packet_free(pkt);
1676 	}
1677 }
1678 
1679 static void
wg_deliver_in(struct wg_peer * peer)1680 wg_deliver_in(struct wg_peer *peer)
1681 {
1682 	struct wg_softc		*sc = peer->p_sc;
1683 	struct ifnet		*ifp = sc->sc_ifp;
1684 	struct wg_packet	*pkt;
1685 	struct mbuf		*m;
1686 	struct epoch_tracker	 et;
1687 
1688 	while ((pkt = wg_queue_dequeue_serial(&peer->p_decrypt_serial)) != NULL) {
1689 		if (atomic_load_acq_int(&pkt->p_state) != WG_PACKET_CRYPTED)
1690 			goto error;
1691 
1692 		m = pkt->p_mbuf;
1693 		if (noise_keypair_nonce_check(pkt->p_keypair, pkt->p_nonce) != 0)
1694 			goto error;
1695 
1696 		if (noise_keypair_received_with(pkt->p_keypair) == ECONNRESET)
1697 			wg_timers_event_handshake_complete(peer);
1698 
1699 		wg_timers_event_any_authenticated_packet_received(peer);
1700 		wg_timers_event_any_authenticated_packet_traversal(peer);
1701 		wg_peer_set_endpoint(peer, &pkt->p_endpoint);
1702 
1703 		counter_u64_add(peer->p_rx_bytes, m->m_pkthdr.len +
1704 		    sizeof(struct wg_pkt_data) + NOISE_AUTHTAG_LEN);
1705 		if_inc_counter(sc->sc_ifp, IFCOUNTER_IPACKETS, 1);
1706 		if_inc_counter(sc->sc_ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len +
1707 		    sizeof(struct wg_pkt_data) + NOISE_AUTHTAG_LEN);
1708 
1709 		if (m->m_pkthdr.len == 0)
1710 			goto done;
1711 
1712 		MPASS(pkt->p_af == AF_INET || pkt->p_af == AF_INET6);
1713 		pkt->p_mbuf = NULL;
1714 
1715 		m->m_pkthdr.rcvif = ifp;
1716 
1717 		NET_EPOCH_ENTER(et);
1718 		BPF_MTAP2_AF(ifp, m, pkt->p_af);
1719 
1720 		CURVNET_SET(ifp->if_vnet);
1721 		M_SETFIB(m, ifp->if_fib);
1722 		if (pkt->p_af == AF_INET)
1723 			netisr_dispatch(NETISR_IP, m);
1724 		if (pkt->p_af == AF_INET6)
1725 			netisr_dispatch(NETISR_IPV6, m);
1726 		CURVNET_RESTORE();
1727 		NET_EPOCH_EXIT(et);
1728 
1729 		wg_timers_event_data_received(peer);
1730 
1731 done:
1732 		if (noise_keep_key_fresh_recv(peer->p_remote))
1733 			wg_timers_event_want_initiation(peer);
1734 		wg_packet_free(pkt);
1735 		continue;
1736 error:
1737 		if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1738 		wg_packet_free(pkt);
1739 	}
1740 }
1741 
1742 static struct wg_packet *
wg_packet_alloc(struct mbuf * m)1743 wg_packet_alloc(struct mbuf *m)
1744 {
1745 	struct wg_packet *pkt;
1746 
1747 	if ((pkt = uma_zalloc(wg_packet_zone, M_NOWAIT | M_ZERO)) == NULL)
1748 		return (NULL);
1749 	pkt->p_mbuf = m;
1750 	return (pkt);
1751 }
1752 
1753 static void
wg_packet_free(struct wg_packet * pkt)1754 wg_packet_free(struct wg_packet *pkt)
1755 {
1756 	if (pkt->p_keypair != NULL)
1757 		noise_keypair_put(pkt->p_keypair);
1758 	if (pkt->p_mbuf != NULL)
1759 		m_freem(pkt->p_mbuf);
1760 	uma_zfree(wg_packet_zone, pkt);
1761 }
1762 
1763 static void
wg_queue_init(struct wg_queue * queue,const char * name)1764 wg_queue_init(struct wg_queue *queue, const char *name)
1765 {
1766 	mtx_init(&queue->q_mtx, name, NULL, MTX_DEF);
1767 	STAILQ_INIT(&queue->q_queue);
1768 	queue->q_len = 0;
1769 }
1770 
1771 static void
wg_queue_deinit(struct wg_queue * queue)1772 wg_queue_deinit(struct wg_queue *queue)
1773 {
1774 	wg_queue_purge(queue);
1775 	mtx_destroy(&queue->q_mtx);
1776 }
1777 
1778 static size_t
wg_queue_len(struct wg_queue * queue)1779 wg_queue_len(struct wg_queue *queue)
1780 {
1781 	return (queue->q_len);
1782 }
1783 
1784 static int
wg_queue_enqueue_handshake(struct wg_queue * hs,struct wg_packet * pkt)1785 wg_queue_enqueue_handshake(struct wg_queue *hs, struct wg_packet *pkt)
1786 {
1787 	int ret = 0;
1788 	mtx_lock(&hs->q_mtx);
1789 	if (hs->q_len < MAX_QUEUED_HANDSHAKES) {
1790 		STAILQ_INSERT_TAIL(&hs->q_queue, pkt, p_parallel);
1791 		hs->q_len++;
1792 	} else {
1793 		ret = ENOBUFS;
1794 	}
1795 	mtx_unlock(&hs->q_mtx);
1796 	if (ret != 0)
1797 		wg_packet_free(pkt);
1798 	return (ret);
1799 }
1800 
1801 static struct wg_packet *
wg_queue_dequeue_handshake(struct wg_queue * hs)1802 wg_queue_dequeue_handshake(struct wg_queue *hs)
1803 {
1804 	struct wg_packet *pkt;
1805 	mtx_lock(&hs->q_mtx);
1806 	if ((pkt = STAILQ_FIRST(&hs->q_queue)) != NULL) {
1807 		STAILQ_REMOVE_HEAD(&hs->q_queue, p_parallel);
1808 		hs->q_len--;
1809 	}
1810 	mtx_unlock(&hs->q_mtx);
1811 	return (pkt);
1812 }
1813 
1814 static void
wg_queue_push_staged(struct wg_queue * staged,struct wg_packet * pkt)1815 wg_queue_push_staged(struct wg_queue *staged, struct wg_packet *pkt)
1816 {
1817 	struct wg_packet *old = NULL;
1818 
1819 	mtx_lock(&staged->q_mtx);
1820 	if (staged->q_len >= MAX_STAGED_PKT) {
1821 		old = STAILQ_FIRST(&staged->q_queue);
1822 		STAILQ_REMOVE_HEAD(&staged->q_queue, p_parallel);
1823 		staged->q_len--;
1824 	}
1825 	STAILQ_INSERT_TAIL(&staged->q_queue, pkt, p_parallel);
1826 	staged->q_len++;
1827 	mtx_unlock(&staged->q_mtx);
1828 
1829 	if (old != NULL)
1830 		wg_packet_free(old);
1831 }
1832 
1833 static void
wg_queue_enlist_staged(struct wg_queue * staged,struct wg_packet_list * list)1834 wg_queue_enlist_staged(struct wg_queue *staged, struct wg_packet_list *list)
1835 {
1836 	struct wg_packet *pkt, *tpkt;
1837 	STAILQ_FOREACH_SAFE(pkt, list, p_parallel, tpkt)
1838 		wg_queue_push_staged(staged, pkt);
1839 }
1840 
1841 static void
wg_queue_delist_staged(struct wg_queue * staged,struct wg_packet_list * list)1842 wg_queue_delist_staged(struct wg_queue *staged, struct wg_packet_list *list)
1843 {
1844 	STAILQ_INIT(list);
1845 	mtx_lock(&staged->q_mtx);
1846 	STAILQ_CONCAT(list, &staged->q_queue);
1847 	staged->q_len = 0;
1848 	mtx_unlock(&staged->q_mtx);
1849 }
1850 
1851 static void
wg_queue_purge(struct wg_queue * staged)1852 wg_queue_purge(struct wg_queue *staged)
1853 {
1854 	struct wg_packet_list list;
1855 	struct wg_packet *pkt, *tpkt;
1856 	wg_queue_delist_staged(staged, &list);
1857 	STAILQ_FOREACH_SAFE(pkt, &list, p_parallel, tpkt)
1858 		wg_packet_free(pkt);
1859 }
1860 
1861 static int
wg_queue_both(struct wg_queue * parallel,struct wg_queue * serial,struct wg_packet * pkt)1862 wg_queue_both(struct wg_queue *parallel, struct wg_queue *serial, struct wg_packet *pkt)
1863 {
1864 	pkt->p_state = WG_PACKET_UNCRYPTED;
1865 
1866 	mtx_lock(&serial->q_mtx);
1867 	if (serial->q_len < MAX_QUEUED_PKT) {
1868 		serial->q_len++;
1869 		STAILQ_INSERT_TAIL(&serial->q_queue, pkt, p_serial);
1870 	} else {
1871 		mtx_unlock(&serial->q_mtx);
1872 		wg_packet_free(pkt);
1873 		return (ENOBUFS);
1874 	}
1875 	mtx_unlock(&serial->q_mtx);
1876 
1877 	mtx_lock(&parallel->q_mtx);
1878 	if (parallel->q_len < MAX_QUEUED_PKT) {
1879 		parallel->q_len++;
1880 		STAILQ_INSERT_TAIL(&parallel->q_queue, pkt, p_parallel);
1881 	} else {
1882 		mtx_unlock(&parallel->q_mtx);
1883 		pkt->p_state = WG_PACKET_DEAD;
1884 		return (ENOBUFS);
1885 	}
1886 	mtx_unlock(&parallel->q_mtx);
1887 
1888 	return (0);
1889 }
1890 
1891 static struct wg_packet *
wg_queue_dequeue_serial(struct wg_queue * serial)1892 wg_queue_dequeue_serial(struct wg_queue *serial)
1893 {
1894 	struct wg_packet *pkt = NULL;
1895 	mtx_lock(&serial->q_mtx);
1896 	if (serial->q_len > 0 && STAILQ_FIRST(&serial->q_queue)->p_state != WG_PACKET_UNCRYPTED) {
1897 		serial->q_len--;
1898 		pkt = STAILQ_FIRST(&serial->q_queue);
1899 		STAILQ_REMOVE_HEAD(&serial->q_queue, p_serial);
1900 	}
1901 	mtx_unlock(&serial->q_mtx);
1902 	return (pkt);
1903 }
1904 
1905 static struct wg_packet *
wg_queue_dequeue_parallel(struct wg_queue * parallel)1906 wg_queue_dequeue_parallel(struct wg_queue *parallel)
1907 {
1908 	struct wg_packet *pkt = NULL;
1909 	mtx_lock(&parallel->q_mtx);
1910 	if (parallel->q_len > 0) {
1911 		parallel->q_len--;
1912 		pkt = STAILQ_FIRST(&parallel->q_queue);
1913 		STAILQ_REMOVE_HEAD(&parallel->q_queue, p_parallel);
1914 	}
1915 	mtx_unlock(&parallel->q_mtx);
1916 	return (pkt);
1917 }
1918 
1919 static void
wg_input(struct mbuf * m,int offset,struct inpcb * inpcb,const struct sockaddr * sa,void * _sc)1920 wg_input(struct mbuf *m, int offset, struct inpcb *inpcb,
1921     const struct sockaddr *sa, void *_sc)
1922 {
1923 #ifdef INET
1924 	const struct sockaddr_in	*sin;
1925 #endif
1926 #ifdef INET6
1927 	const struct sockaddr_in6	*sin6;
1928 #endif
1929 	struct noise_remote		*remote;
1930 	struct wg_pkt_data		*data;
1931 	struct wg_packet		*pkt;
1932 	struct wg_peer			*peer;
1933 	struct wg_softc			*sc = _sc;
1934 	struct mbuf			*defragged;
1935 
1936 	defragged = m_defrag(m, M_NOWAIT);
1937 	if (defragged)
1938 		m = defragged;
1939 	m = m_unshare(m, M_NOWAIT);
1940 	if (!m) {
1941 		if_inc_counter(sc->sc_ifp, IFCOUNTER_IQDROPS, 1);
1942 		return;
1943 	}
1944 
1945 	/* Caller provided us with `sa`, no need for this header. */
1946 	m_adj(m, offset + sizeof(struct udphdr));
1947 
1948 	/* Pullup enough to read packet type */
1949 	if ((m = m_pullup(m, sizeof(uint32_t))) == NULL) {
1950 		if_inc_counter(sc->sc_ifp, IFCOUNTER_IQDROPS, 1);
1951 		return;
1952 	}
1953 
1954 	if ((pkt = wg_packet_alloc(m)) == NULL) {
1955 		if_inc_counter(sc->sc_ifp, IFCOUNTER_IQDROPS, 1);
1956 		m_freem(m);
1957 		return;
1958 	}
1959 
1960 	/* Save send/recv address and port for later. */
1961 	switch (sa->sa_family) {
1962 #ifdef INET
1963 	case AF_INET:
1964 		sin = (const struct sockaddr_in *)sa;
1965 		pkt->p_endpoint.e_remote.r_sin = sin[0];
1966 		pkt->p_endpoint.e_local.l_in = sin[1].sin_addr;
1967 		break;
1968 #endif
1969 #ifdef INET6
1970 	case AF_INET6:
1971 		sin6 = (const struct sockaddr_in6 *)sa;
1972 		pkt->p_endpoint.e_remote.r_sin6 = sin6[0];
1973 		pkt->p_endpoint.e_local.l_in6 = sin6[1].sin6_addr;
1974 		break;
1975 #endif
1976 	default:
1977 		goto error;
1978 	}
1979 
1980 	if ((m->m_pkthdr.len == sizeof(struct wg_pkt_initiation) &&
1981 		*mtod(m, uint32_t *) == WG_PKT_INITIATION) ||
1982 	    (m->m_pkthdr.len == sizeof(struct wg_pkt_response) &&
1983 		*mtod(m, uint32_t *) == WG_PKT_RESPONSE) ||
1984 	    (m->m_pkthdr.len == sizeof(struct wg_pkt_cookie) &&
1985 		*mtod(m, uint32_t *) == WG_PKT_COOKIE)) {
1986 
1987 		if (wg_queue_enqueue_handshake(&sc->sc_handshake_queue, pkt) != 0) {
1988 			if_inc_counter(sc->sc_ifp, IFCOUNTER_IQDROPS, 1);
1989 			DPRINTF(sc, "Dropping handshake packet\n");
1990 		}
1991 		GROUPTASK_ENQUEUE(&sc->sc_handshake);
1992 	} else if (m->m_pkthdr.len >= sizeof(struct wg_pkt_data) +
1993 	    NOISE_AUTHTAG_LEN && *mtod(m, uint32_t *) == WG_PKT_DATA) {
1994 
1995 		/* Pullup whole header to read r_idx below. */
1996 		if ((pkt->p_mbuf = m_pullup(m, sizeof(struct wg_pkt_data))) == NULL)
1997 			goto error;
1998 
1999 		data = mtod(pkt->p_mbuf, struct wg_pkt_data *);
2000 		if ((pkt->p_keypair = noise_keypair_lookup(sc->sc_local, data->r_idx)) == NULL)
2001 			goto error;
2002 
2003 		remote = noise_keypair_remote(pkt->p_keypair);
2004 		peer = noise_remote_arg(remote);
2005 		if (wg_queue_both(&sc->sc_decrypt_parallel, &peer->p_decrypt_serial, pkt) != 0)
2006 			if_inc_counter(sc->sc_ifp, IFCOUNTER_IQDROPS, 1);
2007 		wg_decrypt_dispatch(sc);
2008 		noise_remote_put(remote);
2009 	} else {
2010 		goto error;
2011 	}
2012 	return;
2013 error:
2014 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IERRORS, 1);
2015 	wg_packet_free(pkt);
2016 }
2017 
2018 static void
wg_peer_send_staged(struct wg_peer * peer)2019 wg_peer_send_staged(struct wg_peer *peer)
2020 {
2021 	struct wg_packet_list	 list;
2022 	struct noise_keypair	*keypair;
2023 	struct wg_packet	*pkt, *tpkt;
2024 	struct wg_softc		*sc = peer->p_sc;
2025 
2026 	wg_queue_delist_staged(&peer->p_stage_queue, &list);
2027 
2028 	if (STAILQ_EMPTY(&list))
2029 		return;
2030 
2031 	if ((keypair = noise_keypair_current(peer->p_remote)) == NULL)
2032 		goto error;
2033 
2034 	STAILQ_FOREACH(pkt, &list, p_parallel) {
2035 		if (noise_keypair_nonce_next(keypair, &pkt->p_nonce) != 0)
2036 			goto error_keypair;
2037 	}
2038 	STAILQ_FOREACH_SAFE(pkt, &list, p_parallel, tpkt) {
2039 		pkt->p_keypair = noise_keypair_ref(keypair);
2040 		if (wg_queue_both(&sc->sc_encrypt_parallel, &peer->p_encrypt_serial, pkt) != 0)
2041 			if_inc_counter(sc->sc_ifp, IFCOUNTER_OQDROPS, 1);
2042 	}
2043 	wg_encrypt_dispatch(sc);
2044 	noise_keypair_put(keypair);
2045 	return;
2046 
2047 error_keypair:
2048 	noise_keypair_put(keypair);
2049 error:
2050 	wg_queue_enlist_staged(&peer->p_stage_queue, &list);
2051 	wg_timers_event_want_initiation(peer);
2052 }
2053 
2054 static inline void
xmit_err(struct ifnet * ifp,struct mbuf * m,struct wg_packet * pkt,sa_family_t af)2055 xmit_err(struct ifnet *ifp, struct mbuf *m, struct wg_packet *pkt, sa_family_t af)
2056 {
2057 	if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2058 	switch (af) {
2059 #ifdef INET
2060 	case AF_INET:
2061 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
2062 		if (pkt)
2063 			pkt->p_mbuf = NULL;
2064 		m = NULL;
2065 		break;
2066 #endif
2067 #ifdef INET6
2068 	case AF_INET6:
2069 		icmp6_error(m, ICMP6_DST_UNREACH, 0, 0);
2070 		if (pkt)
2071 			pkt->p_mbuf = NULL;
2072 		m = NULL;
2073 		break;
2074 #endif
2075 	}
2076 	if (pkt)
2077 		wg_packet_free(pkt);
2078 	else if (m)
2079 		m_freem(m);
2080 }
2081 
2082 static int
wg_xmit(struct ifnet * ifp,struct mbuf * m,sa_family_t af,uint32_t mtu)2083 wg_xmit(struct ifnet *ifp, struct mbuf *m, sa_family_t af, uint32_t mtu)
2084 {
2085 	struct wg_packet	*pkt = NULL;
2086 	struct wg_softc		*sc = ifp->if_softc;
2087 	struct wg_peer		*peer;
2088 	int			 rc = 0;
2089 	sa_family_t		 peer_af;
2090 
2091 	/* Work around lifetime issue in the ipv6 mld code. */
2092 	if (__predict_false((ifp->if_flags & IFF_DYING) || !sc)) {
2093 		rc = ENXIO;
2094 		goto err_xmit;
2095 	}
2096 
2097 	if ((pkt = wg_packet_alloc(m)) == NULL) {
2098 		rc = ENOBUFS;
2099 		goto err_xmit;
2100 	}
2101 	pkt->p_mtu = mtu;
2102 	pkt->p_af = af;
2103 
2104 	if (af == AF_INET) {
2105 		peer = wg_aip_lookup(sc, AF_INET, &mtod(m, struct ip *)->ip_dst);
2106 	} else if (af == AF_INET6) {
2107 		peer = wg_aip_lookup(sc, AF_INET6, &mtod(m, struct ip6_hdr *)->ip6_dst);
2108 	} else {
2109 		rc = EAFNOSUPPORT;
2110 		goto err_xmit;
2111 	}
2112 
2113 	BPF_MTAP2_AF(ifp, m, pkt->p_af);
2114 
2115 	if (__predict_false(peer == NULL)) {
2116 		rc = ENETUNREACH;
2117 		goto err_xmit;
2118 	}
2119 
2120 	if (__predict_false(if_tunnel_check_nesting(ifp, m, MTAG_WGLOOP, MAX_LOOPS))) {
2121 		DPRINTF(sc, "Packet looped");
2122 		rc = ELOOP;
2123 		goto err_peer;
2124 	}
2125 
2126 	peer_af = peer->p_endpoint.e_remote.r_sa.sa_family;
2127 	if (__predict_false(peer_af != AF_INET && peer_af != AF_INET6)) {
2128 		DPRINTF(sc, "No valid endpoint has been configured or "
2129 			    "discovered for peer %" PRIu64 "\n", peer->p_id);
2130 		rc = EHOSTUNREACH;
2131 		goto err_peer;
2132 	}
2133 
2134 	wg_queue_push_staged(&peer->p_stage_queue, pkt);
2135 	wg_peer_send_staged(peer);
2136 	noise_remote_put(peer->p_remote);
2137 	return (0);
2138 
2139 err_peer:
2140 	noise_remote_put(peer->p_remote);
2141 err_xmit:
2142 	xmit_err(ifp, m, pkt, af);
2143 	return (rc);
2144 }
2145 
2146 static inline int
determine_af_and_pullup(struct mbuf ** m,sa_family_t * af)2147 determine_af_and_pullup(struct mbuf **m, sa_family_t *af)
2148 {
2149 	u_char ipv;
2150 	if ((*m)->m_pkthdr.len >= sizeof(struct ip6_hdr))
2151 		*m = m_pullup(*m, sizeof(struct ip6_hdr));
2152 	else if ((*m)->m_pkthdr.len >= sizeof(struct ip))
2153 		*m = m_pullup(*m, sizeof(struct ip));
2154 	else
2155 		return (EAFNOSUPPORT);
2156 	if (*m == NULL)
2157 		return (ENOBUFS);
2158 	ipv = mtod(*m, struct ip *)->ip_v;
2159 	if (ipv == 4)
2160 		*af = AF_INET;
2161 	else if (ipv == 6 && (*m)->m_pkthdr.len >= sizeof(struct ip6_hdr))
2162 		*af = AF_INET6;
2163 	else
2164 		return (EAFNOSUPPORT);
2165 	return (0);
2166 }
2167 
2168 static int
wg_transmit(struct ifnet * ifp,struct mbuf * m)2169 wg_transmit(struct ifnet *ifp, struct mbuf *m)
2170 {
2171 	sa_family_t af;
2172 	int ret;
2173 	struct mbuf *defragged;
2174 
2175 	defragged = m_defrag(m, M_NOWAIT);
2176 	if (defragged)
2177 		m = defragged;
2178 	m = m_unshare(m, M_NOWAIT);
2179 	if (!m) {
2180 		xmit_err(ifp, m, NULL, AF_UNSPEC);
2181 		return (ENOBUFS);
2182 	}
2183 
2184 	ret = determine_af_and_pullup(&m, &af);
2185 	if (ret) {
2186 		xmit_err(ifp, m, NULL, AF_UNSPEC);
2187 		return (ret);
2188 	}
2189 	return (wg_xmit(ifp, m, af, ifp->if_mtu));
2190 }
2191 
2192 static int
wg_output(struct ifnet * ifp,struct mbuf * m,const struct sockaddr * dst,struct route * ro)2193 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, struct route *ro)
2194 {
2195 	sa_family_t parsed_af;
2196 	uint32_t af, mtu;
2197 	int ret;
2198 	struct mbuf *defragged;
2199 
2200 	if (dst->sa_family == AF_UNSPEC)
2201 		memcpy(&af, dst->sa_data, sizeof(af));
2202 	else
2203 		af = dst->sa_family;
2204 	if (af == AF_UNSPEC) {
2205 		xmit_err(ifp, m, NULL, af);
2206 		return (EAFNOSUPPORT);
2207 	}
2208 
2209 	defragged = m_defrag(m, M_NOWAIT);
2210 	if (defragged)
2211 		m = defragged;
2212 	m = m_unshare(m, M_NOWAIT);
2213 	if (!m) {
2214 		xmit_err(ifp, m, NULL, AF_UNSPEC);
2215 		return (ENOBUFS);
2216 	}
2217 
2218 	ret = determine_af_and_pullup(&m, &parsed_af);
2219 	if (ret) {
2220 		xmit_err(ifp, m, NULL, AF_UNSPEC);
2221 		return (ret);
2222 	}
2223 	if (parsed_af != af) {
2224 		xmit_err(ifp, m, NULL, AF_UNSPEC);
2225 		return (EAFNOSUPPORT);
2226 	}
2227 	mtu = (ro != NULL && ro->ro_mtu > 0) ? ro->ro_mtu : ifp->if_mtu;
2228 	return (wg_xmit(ifp, m, parsed_af, mtu));
2229 }
2230 
2231 static int
wg_peer_add(struct wg_softc * sc,const nvlist_t * nvl)2232 wg_peer_add(struct wg_softc *sc, const nvlist_t *nvl)
2233 {
2234 	uint8_t			 public[WG_KEY_SIZE];
2235 	const void *pub_key, *preshared_key = NULL;
2236 	const struct sockaddr *endpoint;
2237 	int err;
2238 	size_t size;
2239 	struct noise_remote *remote;
2240 	struct wg_peer *peer = NULL;
2241 	bool need_insert = false;
2242 
2243 	sx_assert(&sc->sc_lock, SX_XLOCKED);
2244 
2245 	if (!nvlist_exists_binary(nvl, "public-key")) {
2246 		return (EINVAL);
2247 	}
2248 	pub_key = nvlist_get_binary(nvl, "public-key", &size);
2249 	if (size != WG_KEY_SIZE) {
2250 		return (EINVAL);
2251 	}
2252 	if (noise_local_keys(sc->sc_local, public, NULL) == 0 &&
2253 	    bcmp(public, pub_key, WG_KEY_SIZE) == 0) {
2254 		return (0); // Silently ignored; not actually a failure.
2255 	}
2256 	if ((remote = noise_remote_lookup(sc->sc_local, pub_key)) != NULL)
2257 		peer = noise_remote_arg(remote);
2258 	if (nvlist_exists_bool(nvl, "remove") &&
2259 		nvlist_get_bool(nvl, "remove")) {
2260 		if (remote != NULL) {
2261 			wg_peer_destroy(peer);
2262 			noise_remote_put(remote);
2263 		}
2264 		return (0);
2265 	}
2266 	if (nvlist_exists_bool(nvl, "replace-allowedips") &&
2267 		nvlist_get_bool(nvl, "replace-allowedips") &&
2268 	    peer != NULL) {
2269 
2270 		wg_aip_remove_all(sc, peer);
2271 	}
2272 	if (peer == NULL) {
2273 		peer = wg_peer_alloc(sc, pub_key);
2274 		need_insert = true;
2275 	}
2276 	if (nvlist_exists_binary(nvl, "endpoint")) {
2277 		endpoint = nvlist_get_binary(nvl, "endpoint", &size);
2278 		if (size > sizeof(peer->p_endpoint.e_remote)) {
2279 			err = EINVAL;
2280 			goto out;
2281 		}
2282 		memcpy(&peer->p_endpoint.e_remote, endpoint, size);
2283 	}
2284 	if (nvlist_exists_binary(nvl, "preshared-key")) {
2285 		preshared_key = nvlist_get_binary(nvl, "preshared-key", &size);
2286 		if (size != WG_KEY_SIZE) {
2287 			err = EINVAL;
2288 			goto out;
2289 		}
2290 		noise_remote_set_psk(peer->p_remote, preshared_key);
2291 	}
2292 	if (nvlist_exists_number(nvl, "persistent-keepalive-interval")) {
2293 		uint64_t pki = nvlist_get_number(nvl, "persistent-keepalive-interval");
2294 		if (pki > UINT16_MAX) {
2295 			err = EINVAL;
2296 			goto out;
2297 		}
2298 		wg_timers_set_persistent_keepalive(peer, pki);
2299 	}
2300 	if (nvlist_exists_nvlist_array(nvl, "allowed-ips")) {
2301 		const void *addr;
2302 		uint64_t cidr;
2303 		const nvlist_t * const * aipl;
2304 		size_t allowedip_count;
2305 
2306 		aipl = nvlist_get_nvlist_array(nvl, "allowed-ips", &allowedip_count);
2307 		for (size_t idx = 0; idx < allowedip_count; idx++) {
2308 			if (!nvlist_exists_number(aipl[idx], "cidr"))
2309 				continue;
2310 			cidr = nvlist_get_number(aipl[idx], "cidr");
2311 			if (nvlist_exists_binary(aipl[idx], "ipv4")) {
2312 				addr = nvlist_get_binary(aipl[idx], "ipv4", &size);
2313 				if (addr == NULL || cidr > 32 || size != sizeof(struct in_addr)) {
2314 					err = EINVAL;
2315 					goto out;
2316 				}
2317 				if ((err = wg_aip_add(sc, peer, AF_INET, addr, cidr)) != 0)
2318 					goto out;
2319 			} else if (nvlist_exists_binary(aipl[idx], "ipv6")) {
2320 				addr = nvlist_get_binary(aipl[idx], "ipv6", &size);
2321 				if (addr == NULL || cidr > 128 || size != sizeof(struct in6_addr)) {
2322 					err = EINVAL;
2323 					goto out;
2324 				}
2325 				if ((err = wg_aip_add(sc, peer, AF_INET6, addr, cidr)) != 0)
2326 					goto out;
2327 			} else {
2328 				continue;
2329 			}
2330 		}
2331 	}
2332 	if (need_insert) {
2333 		if ((err = noise_remote_enable(peer->p_remote)) != 0)
2334 			goto out;
2335 		TAILQ_INSERT_TAIL(&sc->sc_peers, peer, p_entry);
2336 		sc->sc_peers_num++;
2337 		if (sc->sc_ifp->if_link_state == LINK_STATE_UP)
2338 			wg_timers_enable(peer);
2339 	}
2340 	if (remote != NULL)
2341 		noise_remote_put(remote);
2342 	return (0);
2343 out:
2344 	if (need_insert) /* If we fail, only destroy if it was new. */
2345 		wg_peer_destroy(peer);
2346 	if (remote != NULL)
2347 		noise_remote_put(remote);
2348 	return (err);
2349 }
2350 
2351 static int
wgc_set(struct wg_softc * sc,struct wg_data_io * wgd)2352 wgc_set(struct wg_softc *sc, struct wg_data_io *wgd)
2353 {
2354 	uint8_t public[WG_KEY_SIZE], private[WG_KEY_SIZE];
2355 	struct ifnet *ifp;
2356 	void *nvlpacked;
2357 	nvlist_t *nvl;
2358 	ssize_t size;
2359 	int err;
2360 
2361 	ifp = sc->sc_ifp;
2362 	if (wgd->wgd_size == 0 || wgd->wgd_data == NULL)
2363 		return (EFAULT);
2364 
2365 	/* Can nvlists be streamed in? It's not nice to impose arbitrary limits like that but
2366 	 * there needs to be _some_ limitation. */
2367 	if (wgd->wgd_size >= UINT32_MAX / 2)
2368 		return (E2BIG);
2369 
2370 	nvlpacked = malloc(wgd->wgd_size, M_TEMP, M_WAITOK | M_ZERO);
2371 
2372 	err = copyin(wgd->wgd_data, nvlpacked, wgd->wgd_size);
2373 	if (err)
2374 		goto out;
2375 	nvl = nvlist_unpack(nvlpacked, wgd->wgd_size, 0);
2376 	if (nvl == NULL) {
2377 		err = EBADMSG;
2378 		goto out;
2379 	}
2380 	sx_xlock(&sc->sc_lock);
2381 	if (nvlist_exists_bool(nvl, "replace-peers") &&
2382 		nvlist_get_bool(nvl, "replace-peers"))
2383 		wg_peer_destroy_all(sc);
2384 	if (nvlist_exists_number(nvl, "listen-port")) {
2385 		uint64_t new_port = nvlist_get_number(nvl, "listen-port");
2386 		if (new_port > UINT16_MAX) {
2387 			err = EINVAL;
2388 			goto out_locked;
2389 		}
2390 		if (new_port != sc->sc_socket.so_port) {
2391 			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) {
2392 				if ((err = wg_socket_init(sc, new_port)) != 0)
2393 					goto out_locked;
2394 			} else
2395 				sc->sc_socket.so_port = new_port;
2396 		}
2397 	}
2398 	if (nvlist_exists_binary(nvl, "private-key")) {
2399 		const void *key = nvlist_get_binary(nvl, "private-key", &size);
2400 		if (size != WG_KEY_SIZE) {
2401 			err = EINVAL;
2402 			goto out_locked;
2403 		}
2404 
2405 		if (noise_local_keys(sc->sc_local, NULL, private) != 0 ||
2406 		    timingsafe_bcmp(private, key, WG_KEY_SIZE) != 0) {
2407 			struct wg_peer *peer;
2408 
2409 			if (curve25519_generate_public(public, key)) {
2410 				/* Peer conflict: remove conflicting peer. */
2411 				struct noise_remote *remote;
2412 				if ((remote = noise_remote_lookup(sc->sc_local,
2413 				    public)) != NULL) {
2414 					peer = noise_remote_arg(remote);
2415 					wg_peer_destroy(peer);
2416 					noise_remote_put(remote);
2417 				}
2418 			}
2419 
2420 			/*
2421 			 * Set the private key and invalidate all existing
2422 			 * handshakes.
2423 			 */
2424 			/* Note: we might be removing the private key. */
2425 			noise_local_private(sc->sc_local, key);
2426 			if (noise_local_keys(sc->sc_local, NULL, NULL) == 0)
2427 				cookie_checker_update(&sc->sc_cookie, public);
2428 			else
2429 				cookie_checker_update(&sc->sc_cookie, NULL);
2430 		}
2431 	}
2432 	if (nvlist_exists_number(nvl, "user-cookie")) {
2433 		uint64_t user_cookie = nvlist_get_number(nvl, "user-cookie");
2434 		if (user_cookie > UINT32_MAX) {
2435 			err = EINVAL;
2436 			goto out_locked;
2437 		}
2438 		err = wg_socket_set_cookie(sc, user_cookie);
2439 		if (err)
2440 			goto out_locked;
2441 	}
2442 	if (nvlist_exists_nvlist_array(nvl, "peers")) {
2443 		size_t peercount;
2444 		const nvlist_t * const*nvl_peers;
2445 
2446 		nvl_peers = nvlist_get_nvlist_array(nvl, "peers", &peercount);
2447 		for (int i = 0; i < peercount; i++) {
2448 			err = wg_peer_add(sc, nvl_peers[i]);
2449 			if (err != 0)
2450 				goto out_locked;
2451 		}
2452 	}
2453 
2454 out_locked:
2455 	sx_xunlock(&sc->sc_lock);
2456 	nvlist_destroy(nvl);
2457 out:
2458 	zfree(nvlpacked, M_TEMP);
2459 	return (err);
2460 }
2461 
2462 static int
wgc_get(struct wg_softc * sc,struct wg_data_io * wgd)2463 wgc_get(struct wg_softc *sc, struct wg_data_io *wgd)
2464 {
2465 	uint8_t public_key[WG_KEY_SIZE] = { 0 };
2466 	uint8_t private_key[WG_KEY_SIZE] = { 0 };
2467 	uint8_t preshared_key[NOISE_SYMMETRIC_KEY_LEN] = { 0 };
2468 	nvlist_t *nvl, *nvl_peer, *nvl_aip, **nvl_peers, **nvl_aips;
2469 	size_t size, peer_count, aip_count, i, j;
2470 	struct wg_timespec64 ts64;
2471 	struct wg_peer *peer;
2472 	struct wg_aip *aip;
2473 	void *packed;
2474 	int err = 0;
2475 
2476 	nvl = nvlist_create(0);
2477 	if (!nvl)
2478 		return (ENOMEM);
2479 
2480 	sx_slock(&sc->sc_lock);
2481 
2482 	if (sc->sc_socket.so_port != 0)
2483 		nvlist_add_number(nvl, "listen-port", sc->sc_socket.so_port);
2484 	if (sc->sc_socket.so_user_cookie != 0)
2485 		nvlist_add_number(nvl, "user-cookie", sc->sc_socket.so_user_cookie);
2486 	if (noise_local_keys(sc->sc_local, public_key, private_key) == 0) {
2487 		nvlist_add_binary(nvl, "public-key", public_key, WG_KEY_SIZE);
2488 		if (wgc_privileged(sc))
2489 			nvlist_add_binary(nvl, "private-key", private_key, WG_KEY_SIZE);
2490 		explicit_bzero(private_key, sizeof(private_key));
2491 	}
2492 	peer_count = sc->sc_peers_num;
2493 	if (peer_count) {
2494 		nvl_peers = mallocarray(peer_count, sizeof(void *), M_NVLIST, M_WAITOK | M_ZERO);
2495 		i = 0;
2496 		TAILQ_FOREACH(peer, &sc->sc_peers, p_entry) {
2497 			if (i >= peer_count)
2498 				panic("peers changed from under us");
2499 
2500 			nvl_peers[i++] = nvl_peer = nvlist_create(0);
2501 			if (!nvl_peer) {
2502 				err = ENOMEM;
2503 				goto err_peer;
2504 			}
2505 
2506 			(void)noise_remote_keys(peer->p_remote, public_key, preshared_key);
2507 			nvlist_add_binary(nvl_peer, "public-key", public_key, sizeof(public_key));
2508 			if (wgc_privileged(sc))
2509 				nvlist_add_binary(nvl_peer, "preshared-key", preshared_key, sizeof(preshared_key));
2510 			explicit_bzero(preshared_key, sizeof(preshared_key));
2511 			if (peer->p_endpoint.e_remote.r_sa.sa_family == AF_INET)
2512 				nvlist_add_binary(nvl_peer, "endpoint", &peer->p_endpoint.e_remote, sizeof(struct sockaddr_in));
2513 			else if (peer->p_endpoint.e_remote.r_sa.sa_family == AF_INET6)
2514 				nvlist_add_binary(nvl_peer, "endpoint", &peer->p_endpoint.e_remote, sizeof(struct sockaddr_in6));
2515 			wg_timers_get_last_handshake(peer, &ts64);
2516 			nvlist_add_binary(nvl_peer, "last-handshake-time", &ts64, sizeof(ts64));
2517 			nvlist_add_number(nvl_peer, "persistent-keepalive-interval", peer->p_persistent_keepalive_interval);
2518 			nvlist_add_number(nvl_peer, "rx-bytes", counter_u64_fetch(peer->p_rx_bytes));
2519 			nvlist_add_number(nvl_peer, "tx-bytes", counter_u64_fetch(peer->p_tx_bytes));
2520 
2521 			aip_count = peer->p_aips_num;
2522 			if (aip_count) {
2523 				nvl_aips = mallocarray(aip_count, sizeof(void *), M_NVLIST, M_WAITOK | M_ZERO);
2524 				j = 0;
2525 				LIST_FOREACH(aip, &peer->p_aips, a_entry) {
2526 					if (j >= aip_count)
2527 						panic("aips changed from under us");
2528 
2529 					nvl_aips[j++] = nvl_aip = nvlist_create(0);
2530 					if (!nvl_aip) {
2531 						err = ENOMEM;
2532 						goto err_aip;
2533 					}
2534 					if (aip->a_af == AF_INET) {
2535 						nvlist_add_binary(nvl_aip, "ipv4", &aip->a_addr.in, sizeof(aip->a_addr.in));
2536 						nvlist_add_number(nvl_aip, "cidr", bitcount32(aip->a_mask.ip));
2537 					}
2538 #ifdef INET6
2539 					else if (aip->a_af == AF_INET6) {
2540 						nvlist_add_binary(nvl_aip, "ipv6", &aip->a_addr.in6, sizeof(aip->a_addr.in6));
2541 						nvlist_add_number(nvl_aip, "cidr", in6_mask2len(&aip->a_mask.in6, NULL));
2542 					}
2543 #endif
2544 				}
2545 				nvlist_add_nvlist_array(nvl_peer, "allowed-ips", (const nvlist_t *const *)nvl_aips, aip_count);
2546 			err_aip:
2547 				for (j = 0; j < aip_count; ++j)
2548 					nvlist_destroy(nvl_aips[j]);
2549 				free(nvl_aips, M_NVLIST);
2550 				if (err)
2551 					goto err_peer;
2552 			}
2553 		}
2554 		nvlist_add_nvlist_array(nvl, "peers", (const nvlist_t * const *)nvl_peers, peer_count);
2555 	err_peer:
2556 		for (i = 0; i < peer_count; ++i)
2557 			nvlist_destroy(nvl_peers[i]);
2558 		free(nvl_peers, M_NVLIST);
2559 		if (err) {
2560 			sx_sunlock(&sc->sc_lock);
2561 			goto err;
2562 		}
2563 	}
2564 	sx_sunlock(&sc->sc_lock);
2565 	packed = nvlist_pack(nvl, &size);
2566 	if (!packed) {
2567 		err = ENOMEM;
2568 		goto err;
2569 	}
2570 	if (!wgd->wgd_size) {
2571 		wgd->wgd_size = size;
2572 		goto out;
2573 	}
2574 	if (wgd->wgd_size < size) {
2575 		err = ENOSPC;
2576 		goto out;
2577 	}
2578 	err = copyout(packed, wgd->wgd_data, size);
2579 	wgd->wgd_size = size;
2580 
2581 out:
2582 	zfree(packed, M_NVLIST);
2583 err:
2584 	nvlist_destroy(nvl);
2585 	return (err);
2586 }
2587 
2588 static int
wg_ioctl(struct ifnet * ifp,u_long cmd,caddr_t data)2589 wg_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2590 {
2591 	struct wg_data_io *wgd = (struct wg_data_io *)data;
2592 	struct ifreq *ifr = (struct ifreq *)data;
2593 	struct wg_softc *sc;
2594 	int ret = 0;
2595 
2596 	sx_slock(&wg_sx);
2597 	sc = ifp->if_softc;
2598 	if (!sc) {
2599 		ret = ENXIO;
2600 		goto out;
2601 	}
2602 
2603 	switch (cmd) {
2604 	case SIOCSWG:
2605 		ret = priv_check(curthread, PRIV_NET_WG);
2606 		if (ret == 0)
2607 			ret = wgc_set(sc, wgd);
2608 		break;
2609 	case SIOCGWG:
2610 		ret = wgc_get(sc, wgd);
2611 		break;
2612 	/* Interface IOCTLs */
2613 	case SIOCSIFADDR:
2614 		/*
2615 		 * This differs from *BSD norms, but is more uniform with how
2616 		 * WireGuard behaves elsewhere.
2617 		 */
2618 		break;
2619 	case SIOCSIFFLAGS:
2620 		if (ifp->if_flags & IFF_UP)
2621 			ret = wg_up(sc);
2622 		else
2623 			wg_down(sc);
2624 		break;
2625 	case SIOCSIFMTU:
2626 		if (ifr->ifr_mtu <= 0 || ifr->ifr_mtu > MAX_MTU)
2627 			ret = EINVAL;
2628 		else
2629 			ifp->if_mtu = ifr->ifr_mtu;
2630 		break;
2631 	case SIOCADDMULTI:
2632 	case SIOCDELMULTI:
2633 		break;
2634 	case SIOCGTUNFIB:
2635 		ifr->ifr_fib = sc->sc_socket.so_fibnum;
2636 		break;
2637 	case SIOCSTUNFIB:
2638 		ret = priv_check(curthread, PRIV_NET_WG);
2639 		if (ret)
2640 			break;
2641 		ret = priv_check(curthread, PRIV_NET_SETIFFIB);
2642 		if (ret)
2643 			break;
2644 		sx_xlock(&sc->sc_lock);
2645 		ret = wg_socket_set_fibnum(sc, ifr->ifr_fib);
2646 		sx_xunlock(&sc->sc_lock);
2647 		break;
2648 	default:
2649 		ret = ENOTTY;
2650 	}
2651 
2652 out:
2653 	sx_sunlock(&wg_sx);
2654 	return (ret);
2655 }
2656 
2657 static int
wg_up(struct wg_softc * sc)2658 wg_up(struct wg_softc *sc)
2659 {
2660 	struct ifnet *ifp = sc->sc_ifp;
2661 	struct wg_peer *peer;
2662 	int rc = EBUSY;
2663 
2664 	sx_xlock(&sc->sc_lock);
2665 	/* Jail's being removed, no more wg_up(). */
2666 	if ((sc->sc_flags & WGF_DYING) != 0)
2667 		goto out;
2668 
2669 	/* Silent success if we're already running. */
2670 	rc = 0;
2671 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2672 		goto out;
2673 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2674 
2675 	rc = wg_socket_init(sc, sc->sc_socket.so_port);
2676 	if (rc == 0) {
2677 		TAILQ_FOREACH(peer, &sc->sc_peers, p_entry)
2678 			wg_timers_enable(peer);
2679 		if_link_state_change(sc->sc_ifp, LINK_STATE_UP);
2680 	} else {
2681 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2682 		DPRINTF(sc, "Unable to initialize sockets: %d\n", rc);
2683 	}
2684 out:
2685 	sx_xunlock(&sc->sc_lock);
2686 	return (rc);
2687 }
2688 
2689 static void
wg_down(struct wg_softc * sc)2690 wg_down(struct wg_softc *sc)
2691 {
2692 	struct ifnet *ifp = sc->sc_ifp;
2693 	struct wg_peer *peer;
2694 
2695 	sx_xlock(&sc->sc_lock);
2696 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2697 		sx_xunlock(&sc->sc_lock);
2698 		return;
2699 	}
2700 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2701 
2702 	TAILQ_FOREACH(peer, &sc->sc_peers, p_entry) {
2703 		wg_queue_purge(&peer->p_stage_queue);
2704 		wg_timers_disable(peer);
2705 	}
2706 
2707 	wg_queue_purge(&sc->sc_handshake_queue);
2708 
2709 	TAILQ_FOREACH(peer, &sc->sc_peers, p_entry) {
2710 		noise_remote_handshake_clear(peer->p_remote);
2711 		noise_remote_keypairs_clear(peer->p_remote);
2712 	}
2713 
2714 	if_link_state_change(sc->sc_ifp, LINK_STATE_DOWN);
2715 	wg_socket_uninit(sc);
2716 
2717 	sx_xunlock(&sc->sc_lock);
2718 }
2719 
2720 static int
wg_clone_create(struct if_clone * ifc,char * name,size_t len,struct ifc_data * ifd,struct ifnet ** ifpp)2721 wg_clone_create(struct if_clone *ifc, char *name, size_t len,
2722     struct ifc_data *ifd, struct ifnet **ifpp)
2723 {
2724 	struct wg_softc *sc;
2725 	struct ifnet *ifp;
2726 
2727 	sc = malloc(sizeof(*sc), M_WG, M_WAITOK | M_ZERO);
2728 
2729 	sc->sc_local = noise_local_alloc(sc);
2730 
2731 	sc->sc_encrypt = mallocarray(sizeof(struct grouptask), mp_ncpus, M_WG, M_WAITOK | M_ZERO);
2732 
2733 	sc->sc_decrypt = mallocarray(sizeof(struct grouptask), mp_ncpus, M_WG, M_WAITOK | M_ZERO);
2734 
2735 	if (!rn_inithead((void **)&sc->sc_aip4, offsetof(struct aip_addr, in) * NBBY))
2736 		goto free_decrypt;
2737 
2738 	if (!rn_inithead((void **)&sc->sc_aip6, offsetof(struct aip_addr, in6) * NBBY))
2739 		goto free_aip4;
2740 
2741 	atomic_add_int(&clone_count, 1);
2742 	ifp = sc->sc_ifp = if_alloc(IFT_WIREGUARD);
2743 
2744 	sc->sc_ucred = crhold(curthread->td_ucred);
2745 	sc->sc_socket.so_fibnum = curthread->td_proc->p_fibnum;
2746 	sc->sc_socket.so_port = 0;
2747 
2748 	TAILQ_INIT(&sc->sc_peers);
2749 	sc->sc_peers_num = 0;
2750 
2751 	cookie_checker_init(&sc->sc_cookie);
2752 
2753 	RADIX_NODE_HEAD_LOCK_INIT(sc->sc_aip4);
2754 	RADIX_NODE_HEAD_LOCK_INIT(sc->sc_aip6);
2755 
2756 	GROUPTASK_INIT(&sc->sc_handshake, 0, (gtask_fn_t *)wg_softc_handshake_receive, sc);
2757 	taskqgroup_attach(qgroup_wg_tqg, &sc->sc_handshake, sc, NULL, NULL, "wg tx initiation");
2758 	wg_queue_init(&sc->sc_handshake_queue, "hsq");
2759 
2760 	for (int i = 0; i < mp_ncpus; i++) {
2761 		GROUPTASK_INIT(&sc->sc_encrypt[i], 0,
2762 		     (gtask_fn_t *)wg_softc_encrypt, sc);
2763 		taskqgroup_attach_cpu(qgroup_wg_tqg, &sc->sc_encrypt[i], sc, i, NULL, NULL, "wg encrypt");
2764 		GROUPTASK_INIT(&sc->sc_decrypt[i], 0,
2765 		    (gtask_fn_t *)wg_softc_decrypt, sc);
2766 		taskqgroup_attach_cpu(qgroup_wg_tqg, &sc->sc_decrypt[i], sc, i, NULL, NULL, "wg decrypt");
2767 	}
2768 
2769 	wg_queue_init(&sc->sc_encrypt_parallel, "encp");
2770 	wg_queue_init(&sc->sc_decrypt_parallel, "decp");
2771 
2772 	sx_init(&sc->sc_lock, "wg softc lock");
2773 
2774 	ifp->if_softc = sc;
2775 	ifp->if_capabilities = ifp->if_capenable = WG_CAPS;
2776 	if_initname(ifp, wgname, ifd->unit);
2777 
2778 	if_setmtu(ifp, DEFAULT_MTU);
2779 	ifp->if_flags = IFF_NOARP | IFF_MULTICAST;
2780 	ifp->if_init = wg_init;
2781 	ifp->if_reassign = wg_reassign;
2782 	ifp->if_qflush = wg_qflush;
2783 	ifp->if_transmit = wg_transmit;
2784 	ifp->if_output = wg_output;
2785 	ifp->if_ioctl = wg_ioctl;
2786 	if_attach(ifp);
2787 	bpfattach(ifp, DLT_NULL, sizeof(uint32_t));
2788 #ifdef INET6
2789 	ND_IFINFO(ifp)->flags &= ~ND6_IFF_AUTO_LINKLOCAL;
2790 	ND_IFINFO(ifp)->flags |= ND6_IFF_NO_DAD;
2791 #endif
2792 	sx_xlock(&wg_sx);
2793 	LIST_INSERT_HEAD(&wg_list, sc, sc_entry);
2794 	sx_xunlock(&wg_sx);
2795 	*ifpp = ifp;
2796 	return (0);
2797 free_aip4:
2798 	RADIX_NODE_HEAD_DESTROY(sc->sc_aip4);
2799 	free(sc->sc_aip4, M_RTABLE);
2800 free_decrypt:
2801 	free(sc->sc_decrypt, M_WG);
2802 	free(sc->sc_encrypt, M_WG);
2803 	noise_local_free(sc->sc_local, NULL);
2804 	free(sc, M_WG);
2805 	return (ENOMEM);
2806 }
2807 
2808 static void
wg_clone_deferred_free(struct noise_local * l)2809 wg_clone_deferred_free(struct noise_local *l)
2810 {
2811 	struct wg_softc *sc = noise_local_arg(l);
2812 
2813 	free(sc, M_WG);
2814 	atomic_add_int(&clone_count, -1);
2815 }
2816 
2817 static int
wg_clone_destroy(struct if_clone * ifc,struct ifnet * ifp,uint32_t flags)2818 wg_clone_destroy(struct if_clone *ifc, struct ifnet *ifp, uint32_t flags)
2819 {
2820 	struct wg_softc *sc = ifp->if_softc;
2821 	struct ucred *cred;
2822 
2823 	sx_xlock(&wg_sx);
2824 	ifp->if_softc = NULL;
2825 	sx_xlock(&sc->sc_lock);
2826 	sc->sc_flags |= WGF_DYING;
2827 	cred = sc->sc_ucred;
2828 	sc->sc_ucred = NULL;
2829 	sx_xunlock(&sc->sc_lock);
2830 	LIST_REMOVE(sc, sc_entry);
2831 	sx_xunlock(&wg_sx);
2832 
2833 	if_link_state_change(sc->sc_ifp, LINK_STATE_DOWN);
2834 	CURVNET_SET(sc->sc_ifp->if_vnet);
2835 	if_purgeaddrs(sc->sc_ifp);
2836 	CURVNET_RESTORE();
2837 
2838 	sx_xlock(&sc->sc_lock);
2839 	wg_socket_uninit(sc);
2840 	sx_xunlock(&sc->sc_lock);
2841 
2842 	/*
2843 	 * No guarantees that all traffic have passed until the epoch has
2844 	 * elapsed with the socket closed.
2845 	 */
2846 	NET_EPOCH_WAIT();
2847 
2848 	taskqgroup_drain_all(qgroup_wg_tqg);
2849 	sx_xlock(&sc->sc_lock);
2850 	wg_peer_destroy_all(sc);
2851 	NET_EPOCH_DRAIN_CALLBACKS();
2852 	sx_xunlock(&sc->sc_lock);
2853 	sx_destroy(&sc->sc_lock);
2854 	taskqgroup_detach(qgroup_wg_tqg, &sc->sc_handshake);
2855 	for (int i = 0; i < mp_ncpus; i++) {
2856 		taskqgroup_detach(qgroup_wg_tqg, &sc->sc_encrypt[i]);
2857 		taskqgroup_detach(qgroup_wg_tqg, &sc->sc_decrypt[i]);
2858 	}
2859 	free(sc->sc_encrypt, M_WG);
2860 	free(sc->sc_decrypt, M_WG);
2861 	wg_queue_deinit(&sc->sc_handshake_queue);
2862 	wg_queue_deinit(&sc->sc_encrypt_parallel);
2863 	wg_queue_deinit(&sc->sc_decrypt_parallel);
2864 
2865 	RADIX_NODE_HEAD_DESTROY(sc->sc_aip4);
2866 	RADIX_NODE_HEAD_DESTROY(sc->sc_aip6);
2867 	rn_detachhead((void **)&sc->sc_aip4);
2868 	rn_detachhead((void **)&sc->sc_aip6);
2869 
2870 	cookie_checker_free(&sc->sc_cookie);
2871 
2872 	if (cred != NULL)
2873 		crfree(cred);
2874 	bpfdetach(sc->sc_ifp);
2875 	if_detach(sc->sc_ifp);
2876 	if_free(sc->sc_ifp);
2877 
2878 	noise_local_free(sc->sc_local, wg_clone_deferred_free);
2879 
2880 	return (0);
2881 }
2882 
2883 static void
wg_qflush(struct ifnet * ifp __unused)2884 wg_qflush(struct ifnet *ifp __unused)
2885 {
2886 }
2887 
2888 /*
2889  * Privileged information (private-key, preshared-key) are only exported for
2890  * root and jailed root by default.
2891  */
2892 static bool
wgc_privileged(struct wg_softc * sc)2893 wgc_privileged(struct wg_softc *sc)
2894 {
2895 	struct thread *td;
2896 
2897 	td = curthread;
2898 	return (priv_check(td, PRIV_NET_WG) == 0);
2899 }
2900 
2901 static void
wg_reassign(struct ifnet * ifp,struct vnet * new_vnet __unused,char * unused __unused)2902 wg_reassign(struct ifnet *ifp, struct vnet *new_vnet __unused,
2903     char *unused __unused)
2904 {
2905 	struct wg_softc *sc;
2906 
2907 	sc = ifp->if_softc;
2908 	wg_down(sc);
2909 }
2910 
2911 static void
wg_init(void * xsc)2912 wg_init(void *xsc)
2913 {
2914 	struct wg_softc *sc;
2915 
2916 	sc = xsc;
2917 	wg_up(sc);
2918 }
2919 
2920 static void
vnet_wg_init(const void * unused __unused)2921 vnet_wg_init(const void *unused __unused)
2922 {
2923 	struct if_clone_addreq req = {
2924 		.create_f = wg_clone_create,
2925 		.destroy_f = wg_clone_destroy,
2926 		.flags = IFC_F_AUTOUNIT,
2927 	};
2928 	V_wg_cloner = ifc_attach_cloner(wgname, &req);
2929 }
2930 VNET_SYSINIT(vnet_wg_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
2931 	     vnet_wg_init, NULL);
2932 
2933 static void
vnet_wg_uninit(const void * unused __unused)2934 vnet_wg_uninit(const void *unused __unused)
2935 {
2936 	if (V_wg_cloner)
2937 		ifc_detach_cloner(V_wg_cloner);
2938 }
2939 VNET_SYSUNINIT(vnet_wg_uninit, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
2940 	       vnet_wg_uninit, NULL);
2941 
2942 static int
wg_prison_remove(void * obj,void * data __unused)2943 wg_prison_remove(void *obj, void *data __unused)
2944 {
2945 	const struct prison *pr = obj;
2946 	struct wg_softc *sc;
2947 
2948 	/*
2949 	 * Do a pass through all if_wg interfaces and release creds on any from
2950 	 * the jail that are supposed to be going away.  This will, in turn, let
2951 	 * the jail die so that we don't end up with Schrödinger's jail.
2952 	 */
2953 	sx_slock(&wg_sx);
2954 	LIST_FOREACH(sc, &wg_list, sc_entry) {
2955 		sx_xlock(&sc->sc_lock);
2956 		if (!(sc->sc_flags & WGF_DYING) && sc->sc_ucred && sc->sc_ucred->cr_prison == pr) {
2957 			struct ucred *cred = sc->sc_ucred;
2958 			DPRINTF(sc, "Creating jail exiting\n");
2959 			if_link_state_change(sc->sc_ifp, LINK_STATE_DOWN);
2960 			wg_socket_uninit(sc);
2961 			sc->sc_ucred = NULL;
2962 			crfree(cred);
2963 			sc->sc_flags |= WGF_DYING;
2964 		}
2965 		sx_xunlock(&sc->sc_lock);
2966 	}
2967 	sx_sunlock(&wg_sx);
2968 
2969 	return (0);
2970 }
2971 
2972 #ifdef SELFTESTS
2973 #include "selftest/allowedips.c"
wg_run_selftests(void)2974 static bool wg_run_selftests(void)
2975 {
2976 	bool ret = true;
2977 	ret &= wg_allowedips_selftest();
2978 	ret &= noise_counter_selftest();
2979 	ret &= cookie_selftest();
2980 	return ret;
2981 }
2982 #else
wg_run_selftests(void)2983 static inline bool wg_run_selftests(void) { return true; }
2984 #endif
2985 
2986 static int
wg_module_init(void)2987 wg_module_init(void)
2988 {
2989 	int ret;
2990 	osd_method_t methods[PR_MAXMETHOD] = {
2991 		[PR_METHOD_REMOVE] = wg_prison_remove,
2992 	};
2993 
2994 	if ((wg_packet_zone = uma_zcreate("wg packet", sizeof(struct wg_packet),
2995 	     NULL, NULL, NULL, NULL, 0, 0)) == NULL)
2996 		return (ENOMEM);
2997 	ret = crypto_init();
2998 	if (ret != 0)
2999 		return (ret);
3000 	ret = cookie_init();
3001 	if (ret != 0)
3002 		return (ret);
3003 
3004 	wg_osd_jail_slot = osd_jail_register(NULL, methods);
3005 
3006 	if (!wg_run_selftests())
3007 		return (ENOTRECOVERABLE);
3008 
3009 	return (0);
3010 }
3011 
3012 static void
wg_module_deinit(void)3013 wg_module_deinit(void)
3014 {
3015 	VNET_ITERATOR_DECL(vnet_iter);
3016 	VNET_LIST_RLOCK();
3017 	VNET_FOREACH(vnet_iter) {
3018 		struct if_clone *clone = VNET_VNET(vnet_iter, wg_cloner);
3019 		if (clone) {
3020 			ifc_detach_cloner(clone);
3021 			VNET_VNET(vnet_iter, wg_cloner) = NULL;
3022 		}
3023 	}
3024 	VNET_LIST_RUNLOCK();
3025 	NET_EPOCH_WAIT();
3026 	MPASS(LIST_EMPTY(&wg_list));
3027 	if (wg_osd_jail_slot != 0)
3028 		osd_jail_deregister(wg_osd_jail_slot);
3029 	cookie_deinit();
3030 	crypto_deinit();
3031 	if (wg_packet_zone != NULL)
3032 		uma_zdestroy(wg_packet_zone);
3033 }
3034 
3035 static int
wg_module_event_handler(module_t mod,int what,void * arg)3036 wg_module_event_handler(module_t mod, int what, void *arg)
3037 {
3038 	switch (what) {
3039 		case MOD_LOAD:
3040 			return wg_module_init();
3041 		case MOD_UNLOAD:
3042 			wg_module_deinit();
3043 			break;
3044 		default:
3045 			return (EOPNOTSUPP);
3046 	}
3047 	return (0);
3048 }
3049 
3050 static moduledata_t wg_moduledata = {
3051 	wgname,
3052 	wg_module_event_handler,
3053 	NULL
3054 };
3055 
3056 DECLARE_MODULE(wg, wg_moduledata, SI_SUB_PSEUDO, SI_ORDER_ANY);
3057 MODULE_VERSION(wg, WIREGUARD_VERSION);
3058 MODULE_DEPEND(wg, crypto, 1, 1, 1);
3059