if_wg.c revision 1.116 1 /* $NetBSD: if_wg.c,v 1.116 2024/07/29 02:33:44 riastradh Exp $ */
2
3 /*
4 * Copyright (C) Ryota Ozaki <ozaki.ryota (at) gmail.com>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 /*
33 * This network interface aims to implement the WireGuard protocol.
34 * The implementation is based on the paper of WireGuard as of
35 * 2018-06-30 [1]. The paper is referred in the source code with label
36 * [W]. Also the specification of the Noise protocol framework as of
37 * 2018-07-11 [2] is referred with label [N].
38 *
39 * [1] https://www.wireguard.com/papers/wireguard.pdf
40 * [2] http://noiseprotocol.org/noise.pdf
41 */
42
43 #include <sys/cdefs.h>
44 __KERNEL_RCSID(0, "$NetBSD: if_wg.c,v 1.116 2024/07/29 02:33:44 riastradh Exp $");
45
46 #ifdef _KERNEL_OPT
47 #include "opt_altq_enabled.h"
48 #include "opt_inet.h"
49 #endif
50
51 #include <sys/param.h>
52 #include <sys/types.h>
53
54 #include <sys/atomic.h>
55 #include <sys/callout.h>
56 #include <sys/cprng.h>
57 #include <sys/cpu.h>
58 #include <sys/device.h>
59 #include <sys/domain.h>
60 #include <sys/errno.h>
61 #include <sys/intr.h>
62 #include <sys/ioctl.h>
63 #include <sys/kernel.h>
64 #include <sys/kmem.h>
65 #include <sys/mbuf.h>
66 #include <sys/module.h>
67 #include <sys/mutex.h>
68 #include <sys/once.h>
69 #include <sys/percpu.h>
70 #include <sys/pserialize.h>
71 #include <sys/psref.h>
72 #include <sys/queue.h>
73 #include <sys/rwlock.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sockio.h>
77 #include <sys/sysctl.h>
78 #include <sys/syslog.h>
79 #include <sys/systm.h>
80 #include <sys/thmap.h>
81 #include <sys/threadpool.h>
82 #include <sys/time.h>
83 #include <sys/timespec.h>
84 #include <sys/workqueue.h>
85
86 #include <lib/libkern/libkern.h>
87
88 #include <net/bpf.h>
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/if_wg.h>
92 #include <net/pktqueue.h>
93 #include <net/route.h>
94
95 #ifdef INET
96 #include <netinet/in.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/in_var.h>
99 #include <netinet/ip.h>
100 #include <netinet/ip_var.h>
101 #include <netinet/udp.h>
102 #include <netinet/udp_var.h>
103 #endif /* INET */
104
105 #ifdef INET6
106 #include <netinet/ip6.h>
107 #include <netinet6/in6_pcb.h>
108 #include <netinet6/in6_var.h>
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/udp6_var.h>
111 #endif /* INET6 */
112
113 #include <prop/proplib.h>
114
115 #include <crypto/blake2/blake2s.h>
116 #include <crypto/sodium/crypto_aead_chacha20poly1305.h>
117 #include <crypto/sodium/crypto_aead_xchacha20poly1305.h>
118 #include <crypto/sodium/crypto_scalarmult.h>
119
120 #include "ioconf.h"
121
122 #ifdef WG_RUMPKERNEL
123 #include "wg_user.h"
124 #endif
125
126 #ifndef time_uptime32
127 #define time_uptime32 ((uint32_t)time_uptime)
128 #endif
129
130 /*
131 * Data structures
132 * - struct wg_softc is an instance of wg interfaces
133 * - It has a list of peers (struct wg_peer)
134 * - It has a threadpool job that sends/receives handshake messages and
135 * runs event handlers
136 * - It has its own two routing tables: one is for IPv4 and the other IPv6
137 * - struct wg_peer is a representative of a peer
138 * - It has a struct work to handle handshakes and timer tasks
139 * - It has a pair of session instances (struct wg_session)
140 * - It has a pair of endpoint instances (struct wg_sockaddr)
141 * - Normally one endpoint is used and the second one is used only on
142 * a peer migration (a change of peer's IP address)
143 * - It has a list of IP addresses and sub networks called allowedips
144 * (struct wg_allowedip)
145 * - A packets sent over a session is allowed if its destination matches
146 * any IP addresses or sub networks of the list
147 * - struct wg_session represents a session of a secure tunnel with a peer
148 * - Two instances of sessions belong to a peer; a stable session and a
149 * unstable session
150 * - A handshake process of a session always starts with a unstable instance
151 * - Once a session is established, its instance becomes stable and the
152 * other becomes unstable instead
153 * - Data messages are always sent via a stable session
154 *
155 * Locking notes:
156 * - Each wg has a mutex(9) wg_lock, and a rwlock(9) wg_rwlock
157 * - Changes to the peer list are serialized by wg_lock
158 * - The peer list may be read with pserialize(9) and psref(9)
159 * - The rwlock (wg_rwlock) protects the routing tables (wg_rtable_ipv[46])
160 * => XXX replace by pserialize when routing table is psz-safe
161 * - Each peer (struct wg_peer, wgp) has a mutex wgp_lock, which can be taken
162 * only in thread context and serializes:
163 * - the stable and unstable session pointers
164 * - all unstable session state
165 * - Packet processing may be done in softint context:
166 * - The stable session can be read under pserialize(9) or psref(9)
167 * - The stable session is always ESTABLISHED
168 * - On a session swap, we must wait for all readers to release a
169 * reference to a stable session before changing wgs_state and
170 * session states
171 * - Lock order: wg_lock -> wgp_lock
172 */
173
174
175 #define WGLOG(level, fmt, args...) \
176 log(level, "%s: " fmt, __func__, ##args)
177
178 #define WG_DEBUG
179
180 /* Debug options */
181 #ifdef WG_DEBUG
182 /* Output debug logs */
183 #ifndef WG_DEBUG_LOG
184 #define WG_DEBUG_LOG
185 #endif
186 /* Output trace logs */
187 #ifndef WG_DEBUG_TRACE
188 #define WG_DEBUG_TRACE
189 #endif
190 /* Output hash values, etc. */
191 #ifndef WG_DEBUG_DUMP
192 #define WG_DEBUG_DUMP
193 #endif
194 /* Make some internal parameters configurable for testing and debugging */
195 #ifndef WG_DEBUG_PARAMS
196 #define WG_DEBUG_PARAMS
197 #endif
198 #endif /* WG_DEBUG */
199
200 #ifndef WG_DEBUG
201 # if defined(WG_DEBUG_LOG) || defined(WG_DEBUG_TRACE) || \
202 defined(WG_DEBUG_DUMP) || defined(WG_DEBUG_PARAMS)
203 # define WG_DEBUG
204 # endif
205 #endif
206
207 #ifdef WG_DEBUG
208 int wg_debug;
209 #define WG_DEBUG_FLAGS_LOG 1
210 #define WG_DEBUG_FLAGS_TRACE 2
211 #define WG_DEBUG_FLAGS_DUMP 4
212 #endif
213
214 #ifdef WG_DEBUG_TRACE
215 #define WG_TRACE(msg) do { \
216 if (wg_debug & WG_DEBUG_FLAGS_TRACE) \
217 log(LOG_DEBUG, "%s:%d: %s\n", __func__, __LINE__, (msg)); \
218 } while (0)
219 #else
220 #define WG_TRACE(msg) __nothing
221 #endif
222
223 #ifdef WG_DEBUG_LOG
224 #define WG_DLOG(fmt, args...) do { \
225 if (wg_debug & WG_DEBUG_FLAGS_LOG) \
226 log(LOG_DEBUG, "%s: " fmt, __func__, ##args); \
227 } while (0)
228 #else
229 #define WG_DLOG(fmt, args...) __nothing
230 #endif
231
232 #define WG_LOG_RATECHECK(wgprc, level, fmt, args...) do { \
233 if (ppsratecheck(&(wgprc)->wgprc_lasttime, \
234 &(wgprc)->wgprc_curpps, 1)) { \
235 log(level, fmt, ##args); \
236 } \
237 } while (0)
238
239 #ifdef WG_DEBUG_PARAMS
240 static bool wg_force_underload = false;
241 #endif
242
243 #ifdef WG_DEBUG_DUMP
244
245 static char enomem[10] = "[enomem]";
246
247 #define MAX_HDUMP_LEN 10000 /* large enough */
248
249 /*
250 * gethexdump(p, n)
251 *
252 * Allocate a string returning a hexdump of bytes p[0..n),
253 * truncated to MAX_HDUMP_LEN. Must be freed with puthexdump.
254 *
255 * We use this instead of libkern hexdump() because the result is
256 * logged with log(LOG_DEBUG, ...), which puts a priority tag on
257 * every message, so it can't be done incrementally.
258 */
259 static char *
260 gethexdump(const void *vp, size_t n)
261 {
262 char *buf;
263 const uint8_t *p = vp;
264 size_t i, alloc;
265
266 alloc = n;
267 if (n > MAX_HDUMP_LEN)
268 alloc = MAX_HDUMP_LEN;
269 buf = kmem_alloc(3*alloc + 5, KM_NOSLEEP);
270 if (buf == NULL)
271 return enomem;
272 for (i = 0; i < alloc; i++)
273 snprintf(buf + 3*i, 3 + 1, " %02hhx", p[i]);
274 if (alloc != n)
275 snprintf(buf + 3*i, 4 + 1, " ...");
276 return buf;
277 }
278
279 static void
280 puthexdump(char *buf, const void *p, size_t n)
281 {
282
283 if (buf == NULL || buf == enomem)
284 return;
285 if (n > MAX_HDUMP_LEN)
286 n = MAX_HDUMP_LEN;
287 kmem_free(buf, 3*n + 5);
288 }
289
290 #ifdef WG_RUMPKERNEL
291 static void
292 wg_dump_buf(const char *func, const char *buf, const size_t size)
293 {
294 if ((wg_debug & WG_DEBUG_FLAGS_DUMP) == 0)
295 return;
296
297 char *hex = gethexdump(buf, size);
298
299 log(LOG_DEBUG, "%s: %s\n", func, hex);
300 puthexdump(hex, buf, size);
301 }
302 #endif
303
304 static void
305 wg_dump_hash(const uint8_t *func, const uint8_t *name, const uint8_t *hash,
306 const size_t size)
307 {
308 if ((wg_debug & WG_DEBUG_FLAGS_DUMP) == 0)
309 return;
310
311 char *hex = gethexdump(hash, size);
312
313 log(LOG_DEBUG, "%s: %s: %s\n", func, name, hex);
314 puthexdump(hex, hash, size);
315 }
316
317 #define WG_DUMP_HASH(name, hash) \
318 wg_dump_hash(__func__, name, hash, WG_HASH_LEN)
319 #define WG_DUMP_HASH48(name, hash) \
320 wg_dump_hash(__func__, name, hash, 48)
321 #define WG_DUMP_BUF(buf, size) \
322 wg_dump_buf(__func__, buf, size)
323 #else
324 #define WG_DUMP_HASH(name, hash) __nothing
325 #define WG_DUMP_HASH48(name, hash) __nothing
326 #define WG_DUMP_BUF(buf, size) __nothing
327 #endif /* WG_DEBUG_DUMP */
328
329 /* chosen somewhat arbitrarily -- fits in signed 16 bits NUL-terminated */
330 #define WG_MAX_PROPLEN 32766
331
332 #define WG_MTU 1420
333 #define WG_ALLOWEDIPS 16
334
335 #define CURVE25519_KEY_LEN 32
336 #define TAI64N_LEN (sizeof(uint32_t) * 3)
337 #define POLY1305_AUTHTAG_LEN 16
338 #define HMAC_BLOCK_LEN 64
339
340 /* [N] 4.1: "DHLEN must be 32 or greater." WireGuard chooses 32. */
341 /* [N] 4.3: Hash functions */
342 #define NOISE_DHLEN 32
343 /* [N] 4.3: "Must be 32 or 64." WireGuard chooses 32. */
344 #define NOISE_HASHLEN 32
345 #define NOISE_BLOCKLEN 64
346 #define NOISE_HKDF_OUTPUT_LEN NOISE_HASHLEN
347 /* [N] 5.1: "k" */
348 #define NOISE_CIPHER_KEY_LEN 32
349 /*
350 * [N] 9.2: "psk"
351 * "... psk is a 32-byte secret value provided by the application."
352 */
353 #define NOISE_PRESHARED_KEY_LEN 32
354
355 #define WG_STATIC_KEY_LEN CURVE25519_KEY_LEN
356 #define WG_TIMESTAMP_LEN TAI64N_LEN
357
358 #define WG_PRESHARED_KEY_LEN NOISE_PRESHARED_KEY_LEN
359
360 #define WG_COOKIE_LEN 16
361 #define WG_MAC_LEN 16
362 #define WG_COOKIESECRET_LEN 32
363
364 #define WG_EPHEMERAL_KEY_LEN CURVE25519_KEY_LEN
365 /* [N] 5.2: "ck: A chaining key of HASHLEN bytes" */
366 #define WG_CHAINING_KEY_LEN NOISE_HASHLEN
367 /* [N] 5.2: "h: A hash output of HASHLEN bytes" */
368 #define WG_HASH_LEN NOISE_HASHLEN
369 #define WG_CIPHER_KEY_LEN NOISE_CIPHER_KEY_LEN
370 #define WG_DH_OUTPUT_LEN NOISE_DHLEN
371 #define WG_KDF_OUTPUT_LEN NOISE_HKDF_OUTPUT_LEN
372 #define WG_AUTHTAG_LEN POLY1305_AUTHTAG_LEN
373 #define WG_DATA_KEY_LEN 32
374 #define WG_SALT_LEN 24
375
376 /*
377 * The protocol messages
378 */
379 struct wg_msg {
380 uint32_t wgm_type;
381 } __packed;
382
383 /* [W] 5.4.2 First Message: Initiator to Responder */
384 struct wg_msg_init {
385 uint32_t wgmi_type;
386 uint32_t wgmi_sender;
387 uint8_t wgmi_ephemeral[WG_EPHEMERAL_KEY_LEN];
388 uint8_t wgmi_static[WG_STATIC_KEY_LEN + WG_AUTHTAG_LEN];
389 uint8_t wgmi_timestamp[WG_TIMESTAMP_LEN + WG_AUTHTAG_LEN];
390 uint8_t wgmi_mac1[WG_MAC_LEN];
391 uint8_t wgmi_mac2[WG_MAC_LEN];
392 } __packed;
393
394 /* [W] 5.4.3 Second Message: Responder to Initiator */
395 struct wg_msg_resp {
396 uint32_t wgmr_type;
397 uint32_t wgmr_sender;
398 uint32_t wgmr_receiver;
399 uint8_t wgmr_ephemeral[WG_EPHEMERAL_KEY_LEN];
400 uint8_t wgmr_empty[0 + WG_AUTHTAG_LEN];
401 uint8_t wgmr_mac1[WG_MAC_LEN];
402 uint8_t wgmr_mac2[WG_MAC_LEN];
403 } __packed;
404
405 /* [W] 5.4.6 Subsequent Messages: Transport Data Messages */
406 struct wg_msg_data {
407 uint32_t wgmd_type;
408 uint32_t wgmd_receiver;
409 uint64_t wgmd_counter;
410 uint32_t wgmd_packet[];
411 } __packed;
412
413 /* [W] 5.4.7 Under Load: Cookie Reply Message */
414 struct wg_msg_cookie {
415 uint32_t wgmc_type;
416 uint32_t wgmc_receiver;
417 uint8_t wgmc_salt[WG_SALT_LEN];
418 uint8_t wgmc_cookie[WG_COOKIE_LEN + WG_AUTHTAG_LEN];
419 } __packed;
420
421 #define WG_MSG_TYPE_INIT 1
422 #define WG_MSG_TYPE_RESP 2
423 #define WG_MSG_TYPE_COOKIE 3
424 #define WG_MSG_TYPE_DATA 4
425 #define WG_MSG_TYPE_MAX WG_MSG_TYPE_DATA
426
427 /* Sliding windows */
428
429 #define SLIWIN_BITS 2048u
430 #define SLIWIN_TYPE uint32_t
431 #define SLIWIN_BPW (NBBY*sizeof(SLIWIN_TYPE))
432 #define SLIWIN_WORDS howmany(SLIWIN_BITS, SLIWIN_BPW)
433 #define SLIWIN_NPKT (SLIWIN_BITS - NBBY*sizeof(SLIWIN_TYPE))
434
435 struct sliwin {
436 SLIWIN_TYPE B[SLIWIN_WORDS];
437 uint64_t T;
438 };
439
440 static void
441 sliwin_reset(struct sliwin *W)
442 {
443
444 memset(W, 0, sizeof(*W));
445 }
446
447 static int
448 sliwin_check_fast(const volatile struct sliwin *W, uint64_t S)
449 {
450
451 /*
452 * If it's more than one window older than the highest sequence
453 * number we've seen, reject.
454 */
455 #ifdef __HAVE_ATOMIC64_LOADSTORE
456 if (S + SLIWIN_NPKT < atomic_load_relaxed(&W->T))
457 return EAUTH;
458 #endif
459
460 /*
461 * Otherwise, we need to take the lock to decide, so don't
462 * reject just yet. Caller must serialize a call to
463 * sliwin_update in this case.
464 */
465 return 0;
466 }
467
468 static int
469 sliwin_update(struct sliwin *W, uint64_t S)
470 {
471 unsigned word, bit;
472
473 /*
474 * If it's more than one window older than the highest sequence
475 * number we've seen, reject.
476 */
477 if (S + SLIWIN_NPKT < W->T)
478 return EAUTH;
479
480 /*
481 * If it's higher than the highest sequence number we've seen,
482 * advance the window.
483 */
484 if (S > W->T) {
485 uint64_t i = W->T / SLIWIN_BPW;
486 uint64_t j = S / SLIWIN_BPW;
487 unsigned k;
488
489 for (k = 0; k < MIN(j - i, SLIWIN_WORDS); k++)
490 W->B[(i + k + 1) % SLIWIN_WORDS] = 0;
491 #ifdef __HAVE_ATOMIC64_LOADSTORE
492 atomic_store_relaxed(&W->T, S);
493 #else
494 W->T = S;
495 #endif
496 }
497
498 /* Test and set the bit -- if already set, reject. */
499 word = (S / SLIWIN_BPW) % SLIWIN_WORDS;
500 bit = S % SLIWIN_BPW;
501 if (W->B[word] & (1UL << bit))
502 return EAUTH;
503 W->B[word] |= 1U << bit;
504
505 /* Accept! */
506 return 0;
507 }
508
509 struct wg_session {
510 struct wg_peer *wgs_peer;
511 struct psref_target
512 wgs_psref;
513
514 int wgs_state;
515 #define WGS_STATE_UNKNOWN 0
516 #define WGS_STATE_INIT_ACTIVE 1
517 #define WGS_STATE_INIT_PASSIVE 2
518 #define WGS_STATE_ESTABLISHED 3
519 #define WGS_STATE_DESTROYING 4
520
521 volatile uint32_t
522 wgs_time_established;
523 volatile uint32_t
524 wgs_time_last_data_sent;
525 volatile bool wgs_force_rekey;
526 bool wgs_is_initiator;
527
528 uint32_t wgs_local_index;
529 uint32_t wgs_remote_index;
530 #ifdef __HAVE_ATOMIC64_LOADSTORE
531 volatile uint64_t
532 wgs_send_counter;
533 #else
534 kmutex_t wgs_send_counter_lock;
535 uint64_t wgs_send_counter;
536 #endif
537
538 struct {
539 kmutex_t lock;
540 struct sliwin window;
541 } *wgs_recvwin;
542
543 uint8_t wgs_handshake_hash[WG_HASH_LEN];
544 uint8_t wgs_chaining_key[WG_CHAINING_KEY_LEN];
545 uint8_t wgs_ephemeral_key_pub[WG_EPHEMERAL_KEY_LEN];
546 uint8_t wgs_ephemeral_key_priv[WG_EPHEMERAL_KEY_LEN];
547 uint8_t wgs_ephemeral_key_peer[WG_EPHEMERAL_KEY_LEN];
548 uint8_t wgs_tkey_send[WG_DATA_KEY_LEN];
549 uint8_t wgs_tkey_recv[WG_DATA_KEY_LEN];
550 };
551
552 struct wg_sockaddr {
553 union {
554 struct sockaddr_storage _ss;
555 struct sockaddr _sa;
556 struct sockaddr_in _sin;
557 struct sockaddr_in6 _sin6;
558 };
559 struct psref_target wgsa_psref;
560 };
561
562 #define wgsatoss(wgsa) (&(wgsa)->_ss)
563 #define wgsatosa(wgsa) (&(wgsa)->_sa)
564 #define wgsatosin(wgsa) (&(wgsa)->_sin)
565 #define wgsatosin6(wgsa) (&(wgsa)->_sin6)
566
567 #define wgsa_family(wgsa) (wgsatosa(wgsa)->sa_family)
568
569 struct wg_peer;
570 struct wg_allowedip {
571 struct radix_node wga_nodes[2];
572 struct wg_sockaddr _wga_sa_addr;
573 struct wg_sockaddr _wga_sa_mask;
574 #define wga_sa_addr _wga_sa_addr._sa
575 #define wga_sa_mask _wga_sa_mask._sa
576
577 int wga_family;
578 uint8_t wga_cidr;
579 union {
580 struct in_addr _ip4;
581 struct in6_addr _ip6;
582 } wga_addr;
583 #define wga_addr4 wga_addr._ip4
584 #define wga_addr6 wga_addr._ip6
585
586 struct wg_peer *wga_peer;
587 };
588
589 typedef uint8_t wg_timestamp_t[WG_TIMESTAMP_LEN];
590
591 struct wg_ppsratecheck {
592 struct timeval wgprc_lasttime;
593 int wgprc_curpps;
594 };
595
596 struct wg_softc;
597 struct wg_peer {
598 struct wg_softc *wgp_sc;
599 char wgp_name[WG_PEER_NAME_MAXLEN + 1];
600 struct pslist_entry wgp_peerlist_entry;
601 pserialize_t wgp_psz;
602 struct psref_target wgp_psref;
603 kmutex_t *wgp_lock;
604 kmutex_t *wgp_intr_lock;
605
606 uint8_t wgp_pubkey[WG_STATIC_KEY_LEN];
607 struct wg_sockaddr *wgp_endpoint;
608 struct wg_sockaddr *wgp_endpoint0;
609 volatile unsigned wgp_endpoint_changing;
610 bool wgp_endpoint_available;
611
612 /* The preshared key (optional) */
613 uint8_t wgp_psk[WG_PRESHARED_KEY_LEN];
614
615 struct wg_session *wgp_session_stable;
616 struct wg_session *wgp_session_unstable;
617
618 /* first outgoing packet awaiting session initiation */
619 struct mbuf *volatile wgp_pending;
620
621 /* timestamp in big-endian */
622 wg_timestamp_t wgp_timestamp_latest_init;
623
624 struct timespec wgp_last_handshake_time;
625
626 callout_t wgp_handshake_timeout_timer;
627 callout_t wgp_session_dtor_timer;
628
629 time_t wgp_handshake_start_time;
630
631 int wgp_n_allowedips;
632 struct wg_allowedip wgp_allowedips[WG_ALLOWEDIPS];
633
634 time_t wgp_latest_cookie_time;
635 uint8_t wgp_latest_cookie[WG_COOKIE_LEN];
636 uint8_t wgp_last_sent_mac1[WG_MAC_LEN];
637 bool wgp_last_sent_mac1_valid;
638 uint8_t wgp_last_sent_cookie[WG_COOKIE_LEN];
639 bool wgp_last_sent_cookie_valid;
640
641 time_t wgp_last_msg_received_time[WG_MSG_TYPE_MAX];
642
643 time_t wgp_last_cookiesecret_time;
644 uint8_t wgp_cookiesecret[WG_COOKIESECRET_LEN];
645
646 struct wg_ppsratecheck wgp_ppsratecheck;
647
648 struct work wgp_work;
649 unsigned int wgp_tasks;
650 #define WGP_TASK_SEND_INIT_MESSAGE __BIT(0)
651 #define WGP_TASK_RETRY_HANDSHAKE __BIT(1)
652 #define WGP_TASK_ESTABLISH_SESSION __BIT(2)
653 #define WGP_TASK_ENDPOINT_CHANGED __BIT(3)
654 #define WGP_TASK_SEND_KEEPALIVE_MESSAGE __BIT(4)
655 #define WGP_TASK_DESTROY_PREV_SESSION __BIT(5)
656 };
657
658 struct wg_ops;
659
660 struct wg_softc {
661 struct ifnet wg_if;
662 LIST_ENTRY(wg_softc) wg_list;
663 kmutex_t *wg_lock;
664 kmutex_t *wg_intr_lock;
665 krwlock_t *wg_rwlock;
666
667 uint8_t wg_privkey[WG_STATIC_KEY_LEN];
668 uint8_t wg_pubkey[WG_STATIC_KEY_LEN];
669
670 int wg_npeers;
671 struct pslist_head wg_peers;
672 struct thmap *wg_peers_bypubkey;
673 struct thmap *wg_peers_byname;
674 struct thmap *wg_sessions_byindex;
675 uint16_t wg_listen_port;
676
677 struct threadpool *wg_threadpool;
678
679 struct threadpool_job wg_job;
680 int wg_upcalls;
681 #define WG_UPCALL_INET __BIT(0)
682 #define WG_UPCALL_INET6 __BIT(1)
683
684 #ifdef INET
685 struct socket *wg_so4;
686 struct radix_node_head *wg_rtable_ipv4;
687 #endif
688 #ifdef INET6
689 struct socket *wg_so6;
690 struct radix_node_head *wg_rtable_ipv6;
691 #endif
692
693 struct wg_ppsratecheck wg_ppsratecheck;
694
695 struct wg_ops *wg_ops;
696
697 #ifdef WG_RUMPKERNEL
698 struct wg_user *wg_user;
699 #endif
700 };
701
702 /* [W] 6.1 Preliminaries */
703 #define WG_REKEY_AFTER_MESSAGES (1ULL << 60)
704 #define WG_REJECT_AFTER_MESSAGES (UINT64_MAX - (1 << 13))
705 #define WG_REKEY_AFTER_TIME 120
706 #define WG_REJECT_AFTER_TIME 180
707 #define WG_REKEY_ATTEMPT_TIME 90
708 #define WG_REKEY_TIMEOUT 5
709 #define WG_KEEPALIVE_TIMEOUT 10
710
711 #define WG_COOKIE_TIME 120
712 #define WG_COOKIESECRET_TIME (2 * 60)
713
714 static uint64_t wg_rekey_after_messages = WG_REKEY_AFTER_MESSAGES;
715 static uint64_t wg_reject_after_messages = WG_REJECT_AFTER_MESSAGES;
716 static unsigned wg_rekey_after_time = WG_REKEY_AFTER_TIME;
717 static unsigned wg_reject_after_time = WG_REJECT_AFTER_TIME;
718 static unsigned wg_rekey_attempt_time = WG_REKEY_ATTEMPT_TIME;
719 static unsigned wg_rekey_timeout = WG_REKEY_TIMEOUT;
720 static unsigned wg_keepalive_timeout = WG_KEEPALIVE_TIMEOUT;
721
722 static struct mbuf *
723 wg_get_mbuf(size_t, size_t);
724
725 static void wg_send_data_msg(struct wg_peer *, struct wg_session *,
726 struct mbuf *);
727 static void wg_send_cookie_msg(struct wg_softc *, struct wg_peer *,
728 const uint32_t, const uint8_t[static WG_MAC_LEN],
729 const struct sockaddr *);
730 static void wg_send_handshake_msg_resp(struct wg_softc *, struct wg_peer *,
731 struct wg_session *, const struct wg_msg_init *);
732 static void wg_send_keepalive_msg(struct wg_peer *, struct wg_session *);
733
734 static struct wg_peer *
735 wg_pick_peer_by_sa(struct wg_softc *, const struct sockaddr *,
736 struct psref *);
737 static struct wg_peer *
738 wg_lookup_peer_by_pubkey(struct wg_softc *,
739 const uint8_t[static WG_STATIC_KEY_LEN], struct psref *);
740
741 static struct wg_session *
742 wg_lookup_session_by_index(struct wg_softc *,
743 const uint32_t, struct psref *);
744
745 static void wg_update_endpoint_if_necessary(struct wg_peer *,
746 const struct sockaddr *);
747
748 static void wg_schedule_session_dtor_timer(struct wg_peer *);
749
750 static bool wg_is_underload(struct wg_softc *, struct wg_peer *, int);
751 static void wg_calculate_keys(struct wg_session *, const bool);
752
753 static void wg_clear_states(struct wg_session *);
754
755 static void wg_get_peer(struct wg_peer *, struct psref *);
756 static void wg_put_peer(struct wg_peer *, struct psref *);
757
758 static int wg_send_so(struct wg_peer *, struct mbuf *);
759 static int wg_send_udp(struct wg_peer *, struct mbuf *);
760 static int wg_output(struct ifnet *, struct mbuf *,
761 const struct sockaddr *, const struct rtentry *);
762 static void wg_input(struct ifnet *, struct mbuf *, const int);
763 static int wg_ioctl(struct ifnet *, u_long, void *);
764 static int wg_bind_port(struct wg_softc *, const uint16_t);
765 static int wg_init(struct ifnet *);
766 #ifdef ALTQ
767 static void wg_start(struct ifnet *);
768 #endif
769 static void wg_stop(struct ifnet *, int);
770
771 static void wg_peer_work(struct work *, void *);
772 static void wg_job(struct threadpool_job *);
773 static void wgintr(void *);
774 static void wg_purge_pending_packets(struct wg_peer *);
775
776 static int wg_clone_create(struct if_clone *, int);
777 static int wg_clone_destroy(struct ifnet *);
778
779 struct wg_ops {
780 int (*send_hs_msg)(struct wg_peer *, struct mbuf *);
781 int (*send_data_msg)(struct wg_peer *, struct mbuf *);
782 void (*input)(struct ifnet *, struct mbuf *, const int);
783 int (*bind_port)(struct wg_softc *, const uint16_t);
784 };
785
786 struct wg_ops wg_ops_rumpkernel = {
787 .send_hs_msg = wg_send_so,
788 .send_data_msg = wg_send_udp,
789 .input = wg_input,
790 .bind_port = wg_bind_port,
791 };
792
793 #ifdef WG_RUMPKERNEL
794 static bool wg_user_mode(struct wg_softc *);
795 static int wg_ioctl_linkstr(struct wg_softc *, struct ifdrv *);
796
797 static int wg_send_user(struct wg_peer *, struct mbuf *);
798 static void wg_input_user(struct ifnet *, struct mbuf *, const int);
799 static int wg_bind_port_user(struct wg_softc *, const uint16_t);
800
801 struct wg_ops wg_ops_rumpuser = {
802 .send_hs_msg = wg_send_user,
803 .send_data_msg = wg_send_user,
804 .input = wg_input_user,
805 .bind_port = wg_bind_port_user,
806 };
807 #endif
808
809 #define WG_PEER_READER_FOREACH(wgp, wg) \
810 PSLIST_READER_FOREACH((wgp), &(wg)->wg_peers, struct wg_peer, \
811 wgp_peerlist_entry)
812 #define WG_PEER_WRITER_FOREACH(wgp, wg) \
813 PSLIST_WRITER_FOREACH((wgp), &(wg)->wg_peers, struct wg_peer, \
814 wgp_peerlist_entry)
815 #define WG_PEER_WRITER_INSERT_HEAD(wgp, wg) \
816 PSLIST_WRITER_INSERT_HEAD(&(wg)->wg_peers, (wgp), wgp_peerlist_entry)
817 #define WG_PEER_WRITER_REMOVE(wgp) \
818 PSLIST_WRITER_REMOVE((wgp), wgp_peerlist_entry)
819
820 struct wg_route {
821 struct radix_node wgr_nodes[2];
822 struct wg_peer *wgr_peer;
823 };
824
825 static struct radix_node_head *
826 wg_rnh(struct wg_softc *wg, const int family)
827 {
828
829 switch (family) {
830 #ifdef INET
831 case AF_INET:
832 return wg->wg_rtable_ipv4;
833 #endif
834 #ifdef INET6
835 case AF_INET6:
836 return wg->wg_rtable_ipv6;
837 #endif
838 default:
839 return NULL;
840 }
841 }
842
843
844 /*
845 * Global variables
846 */
847 static volatile unsigned wg_count __cacheline_aligned;
848
849 struct psref_class *wg_psref_class __read_mostly;
850
851 static struct if_clone wg_cloner =
852 IF_CLONE_INITIALIZER("wg", wg_clone_create, wg_clone_destroy);
853
854 static struct pktqueue *wg_pktq __read_mostly;
855 static struct workqueue *wg_wq __read_mostly;
856
857 void wgattach(int);
858 /* ARGSUSED */
859 void
860 wgattach(int count)
861 {
862 /*
863 * Nothing to do here, initialization is handled by the
864 * module initialization code in wginit() below).
865 */
866 }
867
868 static void
869 wginit(void)
870 {
871
872 wg_psref_class = psref_class_create("wg", IPL_SOFTNET);
873
874 if_clone_attach(&wg_cloner);
875 }
876
877 /*
878 * XXX Kludge: This should just happen in wginit, but workqueue_create
879 * cannot be run until after CPUs have been detected, and wginit runs
880 * before configure.
881 */
882 static int
883 wginitqueues(void)
884 {
885 int error __diagused;
886
887 wg_pktq = pktq_create(IFQ_MAXLEN, wgintr, NULL);
888 KASSERT(wg_pktq != NULL);
889
890 error = workqueue_create(&wg_wq, "wgpeer", wg_peer_work, NULL,
891 PRI_NONE, IPL_SOFTNET, WQ_MPSAFE|WQ_PERCPU);
892 KASSERTMSG(error == 0, "error=%d", error);
893
894 return 0;
895 }
896
897 static void
898 wg_guarantee_initialized(void)
899 {
900 static ONCE_DECL(init);
901 int error __diagused;
902
903 error = RUN_ONCE(&init, wginitqueues);
904 KASSERTMSG(error == 0, "error=%d", error);
905 }
906
907 static int
908 wg_count_inc(void)
909 {
910 unsigned o, n;
911
912 do {
913 o = atomic_load_relaxed(&wg_count);
914 if (o == UINT_MAX)
915 return ENFILE;
916 n = o + 1;
917 } while (atomic_cas_uint(&wg_count, o, n) != o);
918
919 return 0;
920 }
921
922 static void
923 wg_count_dec(void)
924 {
925 unsigned c __diagused;
926
927 c = atomic_dec_uint_nv(&wg_count);
928 KASSERT(c != UINT_MAX);
929 }
930
931 static int
932 wgdetach(void)
933 {
934
935 /* Prevent new interface creation. */
936 if_clone_detach(&wg_cloner);
937
938 /* Check whether there are any existing interfaces. */
939 if (atomic_load_relaxed(&wg_count)) {
940 /* Back out -- reattach the cloner. */
941 if_clone_attach(&wg_cloner);
942 return EBUSY;
943 }
944
945 /* No interfaces left. Nuke it. */
946 if (wg_wq)
947 workqueue_destroy(wg_wq);
948 if (wg_pktq)
949 pktq_destroy(wg_pktq);
950 psref_class_destroy(wg_psref_class);
951
952 return 0;
953 }
954
955 static void
956 wg_init_key_and_hash(uint8_t ckey[static WG_CHAINING_KEY_LEN],
957 uint8_t hash[static WG_HASH_LEN])
958 {
959 /* [W] 5.4: CONSTRUCTION */
960 const char *signature = "Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s";
961 /* [W] 5.4: IDENTIFIER */
962 const char *id = "WireGuard v1 zx2c4 Jason (at) zx2c4.com";
963 struct blake2s state;
964
965 blake2s(ckey, WG_CHAINING_KEY_LEN, NULL, 0,
966 signature, strlen(signature));
967
968 CTASSERT(WG_HASH_LEN == WG_CHAINING_KEY_LEN);
969 memcpy(hash, ckey, WG_CHAINING_KEY_LEN);
970
971 blake2s_init(&state, WG_HASH_LEN, NULL, 0);
972 blake2s_update(&state, ckey, WG_CHAINING_KEY_LEN);
973 blake2s_update(&state, id, strlen(id));
974 blake2s_final(&state, hash);
975
976 WG_DUMP_HASH("ckey", ckey);
977 WG_DUMP_HASH("hash", hash);
978 }
979
980 static void
981 wg_algo_hash(uint8_t hash[static WG_HASH_LEN], const uint8_t input[],
982 const size_t inputsize)
983 {
984 struct blake2s state;
985
986 blake2s_init(&state, WG_HASH_LEN, NULL, 0);
987 blake2s_update(&state, hash, WG_HASH_LEN);
988 blake2s_update(&state, input, inputsize);
989 blake2s_final(&state, hash);
990 }
991
992 static void
993 wg_algo_mac(uint8_t out[], const size_t outsize,
994 const uint8_t key[], const size_t keylen,
995 const uint8_t input1[], const size_t input1len,
996 const uint8_t input2[], const size_t input2len)
997 {
998 struct blake2s state;
999
1000 blake2s_init(&state, outsize, key, keylen);
1001
1002 blake2s_update(&state, input1, input1len);
1003 if (input2 != NULL)
1004 blake2s_update(&state, input2, input2len);
1005 blake2s_final(&state, out);
1006 }
1007
1008 static void
1009 wg_algo_mac_mac1(uint8_t out[], const size_t outsize,
1010 const uint8_t input1[], const size_t input1len,
1011 const uint8_t input2[], const size_t input2len)
1012 {
1013 struct blake2s state;
1014 /* [W] 5.4: LABEL-MAC1 */
1015 const char *label = "mac1----";
1016 uint8_t key[WG_HASH_LEN];
1017
1018 blake2s_init(&state, sizeof(key), NULL, 0);
1019 blake2s_update(&state, label, strlen(label));
1020 blake2s_update(&state, input1, input1len);
1021 blake2s_final(&state, key);
1022
1023 blake2s_init(&state, outsize, key, sizeof(key));
1024 if (input2 != NULL)
1025 blake2s_update(&state, input2, input2len);
1026 blake2s_final(&state, out);
1027 }
1028
1029 static void
1030 wg_algo_mac_cookie(uint8_t out[], const size_t outsize,
1031 const uint8_t input1[], const size_t input1len)
1032 {
1033 struct blake2s state;
1034 /* [W] 5.4: LABEL-COOKIE */
1035 const char *label = "cookie--";
1036
1037 blake2s_init(&state, outsize, NULL, 0);
1038 blake2s_update(&state, label, strlen(label));
1039 blake2s_update(&state, input1, input1len);
1040 blake2s_final(&state, out);
1041 }
1042
1043 static void
1044 wg_algo_generate_keypair(uint8_t pubkey[static WG_EPHEMERAL_KEY_LEN],
1045 uint8_t privkey[static WG_EPHEMERAL_KEY_LEN])
1046 {
1047
1048 CTASSERT(WG_EPHEMERAL_KEY_LEN == crypto_scalarmult_curve25519_BYTES);
1049
1050 cprng_strong(kern_cprng, privkey, WG_EPHEMERAL_KEY_LEN, 0);
1051 crypto_scalarmult_base(pubkey, privkey);
1052 }
1053
1054 static void
1055 wg_algo_dh(uint8_t out[static WG_DH_OUTPUT_LEN],
1056 const uint8_t privkey[static WG_STATIC_KEY_LEN],
1057 const uint8_t pubkey[static WG_STATIC_KEY_LEN])
1058 {
1059
1060 CTASSERT(WG_STATIC_KEY_LEN == crypto_scalarmult_curve25519_BYTES);
1061
1062 int ret __diagused = crypto_scalarmult(out, privkey, pubkey);
1063 KASSERT(ret == 0);
1064 }
1065
1066 static void
1067 wg_algo_hmac(uint8_t out[], const size_t outlen,
1068 const uint8_t key[], const size_t keylen,
1069 const uint8_t in[], const size_t inlen)
1070 {
1071 #define IPAD 0x36
1072 #define OPAD 0x5c
1073 uint8_t hmackey[HMAC_BLOCK_LEN] = {0};
1074 uint8_t ipad[HMAC_BLOCK_LEN];
1075 uint8_t opad[HMAC_BLOCK_LEN];
1076 size_t i;
1077 struct blake2s state;
1078
1079 KASSERT(outlen == WG_HASH_LEN);
1080 KASSERT(keylen <= HMAC_BLOCK_LEN);
1081
1082 memcpy(hmackey, key, keylen);
1083
1084 for (i = 0; i < sizeof(hmackey); i++) {
1085 ipad[i] = hmackey[i] ^ IPAD;
1086 opad[i] = hmackey[i] ^ OPAD;
1087 }
1088
1089 blake2s_init(&state, WG_HASH_LEN, NULL, 0);
1090 blake2s_update(&state, ipad, sizeof(ipad));
1091 blake2s_update(&state, in, inlen);
1092 blake2s_final(&state, out);
1093
1094 blake2s_init(&state, WG_HASH_LEN, NULL, 0);
1095 blake2s_update(&state, opad, sizeof(opad));
1096 blake2s_update(&state, out, WG_HASH_LEN);
1097 blake2s_final(&state, out);
1098 #undef IPAD
1099 #undef OPAD
1100 }
1101
1102 static void
1103 wg_algo_kdf(uint8_t out1[static WG_KDF_OUTPUT_LEN],
1104 uint8_t out2[WG_KDF_OUTPUT_LEN],
1105 uint8_t out3[WG_KDF_OUTPUT_LEN],
1106 const uint8_t ckey[static WG_CHAINING_KEY_LEN],
1107 const uint8_t input[], const size_t inputlen)
1108 {
1109 uint8_t tmp1[WG_KDF_OUTPUT_LEN], tmp2[WG_KDF_OUTPUT_LEN + 1];
1110 uint8_t one[1];
1111
1112 /*
1113 * [N] 4.3: "an input_key_material byte sequence with length
1114 * either zero bytes, 32 bytes, or DHLEN bytes."
1115 */
1116 KASSERT(inputlen == 0 || inputlen == 32 || inputlen == NOISE_DHLEN);
1117
1118 WG_DUMP_HASH("ckey", ckey);
1119 if (input != NULL)
1120 WG_DUMP_HASH("input", input);
1121 wg_algo_hmac(tmp1, sizeof(tmp1), ckey, WG_CHAINING_KEY_LEN,
1122 input, inputlen);
1123 WG_DUMP_HASH("tmp1", tmp1);
1124 one[0] = 1;
1125 wg_algo_hmac(out1, WG_KDF_OUTPUT_LEN, tmp1, sizeof(tmp1),
1126 one, sizeof(one));
1127 WG_DUMP_HASH("out1", out1);
1128 if (out2 == NULL)
1129 return;
1130 memcpy(tmp2, out1, WG_KDF_OUTPUT_LEN);
1131 tmp2[WG_KDF_OUTPUT_LEN] = 2;
1132 wg_algo_hmac(out2, WG_KDF_OUTPUT_LEN, tmp1, sizeof(tmp1),
1133 tmp2, sizeof(tmp2));
1134 WG_DUMP_HASH("out2", out2);
1135 if (out3 == NULL)
1136 return;
1137 memcpy(tmp2, out2, WG_KDF_OUTPUT_LEN);
1138 tmp2[WG_KDF_OUTPUT_LEN] = 3;
1139 wg_algo_hmac(out3, WG_KDF_OUTPUT_LEN, tmp1, sizeof(tmp1),
1140 tmp2, sizeof(tmp2));
1141 WG_DUMP_HASH("out3", out3);
1142 }
1143
1144 static void __noinline
1145 wg_algo_dh_kdf(uint8_t ckey[static WG_CHAINING_KEY_LEN],
1146 uint8_t cipher_key[WG_CIPHER_KEY_LEN],
1147 const uint8_t local_key[static WG_STATIC_KEY_LEN],
1148 const uint8_t remote_key[static WG_STATIC_KEY_LEN])
1149 {
1150 uint8_t dhout[WG_DH_OUTPUT_LEN];
1151
1152 wg_algo_dh(dhout, local_key, remote_key);
1153 wg_algo_kdf(ckey, cipher_key, NULL, ckey, dhout, sizeof(dhout));
1154
1155 WG_DUMP_HASH("dhout", dhout);
1156 WG_DUMP_HASH("ckey", ckey);
1157 if (cipher_key != NULL)
1158 WG_DUMP_HASH("cipher_key", cipher_key);
1159 }
1160
1161 static void
1162 wg_algo_aead_enc(uint8_t out[], size_t expected_outsize,
1163 const uint8_t key[static crypto_aead_chacha20poly1305_ietf_KEYBYTES],
1164 const uint64_t counter,
1165 const uint8_t plain[], const size_t plainsize,
1166 const uint8_t auth[], size_t authlen)
1167 {
1168 uint8_t nonce[(32 + 64) / 8] = {0};
1169 long long unsigned int outsize;
1170 int error __diagused;
1171
1172 le64enc(&nonce[4], counter);
1173
1174 error = crypto_aead_chacha20poly1305_ietf_encrypt(out, &outsize, plain,
1175 plainsize, auth, authlen, NULL, nonce, key);
1176 KASSERT(error == 0);
1177 KASSERT(outsize == expected_outsize);
1178 }
1179
1180 static int
1181 wg_algo_aead_dec(uint8_t out[], size_t expected_outsize,
1182 const uint8_t key[static crypto_aead_chacha20poly1305_ietf_KEYBYTES],
1183 const uint64_t counter,
1184 const uint8_t encrypted[], const size_t encryptedsize,
1185 const uint8_t auth[], size_t authlen)
1186 {
1187 uint8_t nonce[(32 + 64) / 8] = {0};
1188 long long unsigned int outsize;
1189 int error;
1190
1191 le64enc(&nonce[4], counter);
1192
1193 error = crypto_aead_chacha20poly1305_ietf_decrypt(out, &outsize, NULL,
1194 encrypted, encryptedsize, auth, authlen, nonce, key);
1195 if (error == 0)
1196 KASSERT(outsize == expected_outsize);
1197 return error;
1198 }
1199
1200 static void
1201 wg_algo_xaead_enc(uint8_t out[], const size_t expected_outsize,
1202 const uint8_t key[static crypto_aead_xchacha20poly1305_ietf_KEYBYTES],
1203 const uint8_t plain[], const size_t plainsize,
1204 const uint8_t auth[], size_t authlen,
1205 const uint8_t nonce[static WG_SALT_LEN])
1206 {
1207 long long unsigned int outsize;
1208 int error __diagused;
1209
1210 CTASSERT(WG_SALT_LEN == crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
1211 error = crypto_aead_xchacha20poly1305_ietf_encrypt(out, &outsize,
1212 plain, plainsize, auth, authlen, NULL, nonce, key);
1213 KASSERT(error == 0);
1214 KASSERT(outsize == expected_outsize);
1215 }
1216
1217 static int
1218 wg_algo_xaead_dec(uint8_t out[], const size_t expected_outsize,
1219 const uint8_t key[static crypto_aead_xchacha20poly1305_ietf_KEYBYTES],
1220 const uint8_t encrypted[], const size_t encryptedsize,
1221 const uint8_t auth[], size_t authlen,
1222 const uint8_t nonce[static WG_SALT_LEN])
1223 {
1224 long long unsigned int outsize;
1225 int error;
1226
1227 error = crypto_aead_xchacha20poly1305_ietf_decrypt(out, &outsize, NULL,
1228 encrypted, encryptedsize, auth, authlen, nonce, key);
1229 if (error == 0)
1230 KASSERT(outsize == expected_outsize);
1231 return error;
1232 }
1233
1234 static void
1235 wg_algo_tai64n(wg_timestamp_t timestamp)
1236 {
1237 struct timespec ts;
1238
1239 /* FIXME strict TAI64N (https://cr.yp.to/libtai/tai64.html) */
1240 getnanotime(&ts);
1241 /* TAI64 label in external TAI64 format */
1242 be32enc(timestamp, 0x40000000U + (uint32_t)(ts.tv_sec >> 32));
1243 /* second beginning from 1970 TAI */
1244 be32enc(timestamp + 4, (uint32_t)(ts.tv_sec & 0xffffffffU));
1245 /* nanosecond in big-endian format */
1246 be32enc(timestamp + 8, (uint32_t)ts.tv_nsec);
1247 }
1248
1249 /*
1250 * wg_get_stable_session(wgp, psref)
1251 *
1252 * Get a passive reference to the current stable session, or
1253 * return NULL if there is no current stable session.
1254 *
1255 * The pointer is always there but the session is not necessarily
1256 * ESTABLISHED; if it is not ESTABLISHED, return NULL. However,
1257 * the session may transition from ESTABLISHED to DESTROYING while
1258 * holding the passive reference.
1259 */
1260 static struct wg_session *
1261 wg_get_stable_session(struct wg_peer *wgp, struct psref *psref)
1262 {
1263 int s;
1264 struct wg_session *wgs;
1265
1266 s = pserialize_read_enter();
1267 wgs = atomic_load_consume(&wgp->wgp_session_stable);
1268 if (__predict_false(wgs->wgs_state != WGS_STATE_ESTABLISHED))
1269 wgs = NULL;
1270 else
1271 psref_acquire(psref, &wgs->wgs_psref, wg_psref_class);
1272 pserialize_read_exit(s);
1273
1274 return wgs;
1275 }
1276
1277 static void
1278 wg_put_session(struct wg_session *wgs, struct psref *psref)
1279 {
1280
1281 psref_release(psref, &wgs->wgs_psref, wg_psref_class);
1282 }
1283
1284 static void
1285 wg_destroy_session(struct wg_softc *wg, struct wg_session *wgs)
1286 {
1287 struct wg_peer *wgp = wgs->wgs_peer;
1288 struct wg_session *wgs0 __diagused;
1289 void *garbage;
1290
1291 KASSERT(mutex_owned(wgp->wgp_lock));
1292 KASSERT(wgs->wgs_state != WGS_STATE_UNKNOWN);
1293
1294 /* Remove the session from the table. */
1295 wgs0 = thmap_del(wg->wg_sessions_byindex,
1296 &wgs->wgs_local_index, sizeof(wgs->wgs_local_index));
1297 KASSERT(wgs0 == wgs);
1298 garbage = thmap_stage_gc(wg->wg_sessions_byindex);
1299
1300 /* Wait for passive references to drain. */
1301 pserialize_perform(wgp->wgp_psz);
1302 psref_target_destroy(&wgs->wgs_psref, wg_psref_class);
1303
1304 /*
1305 * Free memory, zero state, and transition to UNKNOWN. We have
1306 * exclusive access to the session now, so there is no need for
1307 * an atomic store.
1308 */
1309 thmap_gc(wg->wg_sessions_byindex, garbage);
1310 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_UNKNOWN\n",
1311 wgs->wgs_local_index, wgs->wgs_remote_index);
1312 wgs->wgs_local_index = 0;
1313 wgs->wgs_remote_index = 0;
1314 wg_clear_states(wgs);
1315 wgs->wgs_state = WGS_STATE_UNKNOWN;
1316 wgs->wgs_force_rekey = false;
1317 }
1318
1319 /*
1320 * wg_get_session_index(wg, wgs)
1321 *
1322 * Choose a session index for wgs->wgs_local_index, and store it
1323 * in wg's table of sessions by index.
1324 *
1325 * wgs must be the unstable session of its peer, and must be
1326 * transitioning out of the UNKNOWN state.
1327 */
1328 static void
1329 wg_get_session_index(struct wg_softc *wg, struct wg_session *wgs)
1330 {
1331 struct wg_peer *wgp __diagused = wgs->wgs_peer;
1332 struct wg_session *wgs0;
1333 uint32_t index;
1334
1335 KASSERT(mutex_owned(wgp->wgp_lock));
1336 KASSERT(wgs == wgp->wgp_session_unstable);
1337 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1338 wgs->wgs_state);
1339
1340 do {
1341 /* Pick a uniform random index. */
1342 index = cprng_strong32();
1343
1344 /* Try to take it. */
1345 wgs->wgs_local_index = index;
1346 wgs0 = thmap_put(wg->wg_sessions_byindex,
1347 &wgs->wgs_local_index, sizeof wgs->wgs_local_index, wgs);
1348
1349 /* If someone else beat us, start over. */
1350 } while (__predict_false(wgs0 != wgs));
1351 }
1352
1353 /*
1354 * wg_put_session_index(wg, wgs)
1355 *
1356 * Remove wgs from the table of sessions by index, wait for any
1357 * passive references to drain, and transition the session to the
1358 * UNKNOWN state.
1359 *
1360 * wgs must be the unstable session of its peer, and must not be
1361 * UNKNOWN or ESTABLISHED.
1362 */
1363 static void
1364 wg_put_session_index(struct wg_softc *wg, struct wg_session *wgs)
1365 {
1366 struct wg_peer *wgp __diagused = wgs->wgs_peer;
1367
1368 KASSERT(mutex_owned(wgp->wgp_lock));
1369 KASSERT(wgs->wgs_state != WGS_STATE_UNKNOWN);
1370 KASSERT(wgs->wgs_state != WGS_STATE_ESTABLISHED);
1371
1372 wg_destroy_session(wg, wgs);
1373 psref_target_init(&wgs->wgs_psref, wg_psref_class);
1374 }
1375
1376 /*
1377 * Handshake patterns
1378 *
1379 * [W] 5: "These messages use the "IK" pattern from Noise"
1380 * [N] 7.5. Interactive handshake patterns (fundamental)
1381 * "The first character refers to the initiators static key:"
1382 * "I = Static key for initiator Immediately transmitted to responder,
1383 * despite reduced or absent identity hiding"
1384 * "The second character refers to the responders static key:"
1385 * "K = Static key for responder Known to initiator"
1386 * "IK:
1387 * <- s
1388 * ...
1389 * -> e, es, s, ss
1390 * <- e, ee, se"
1391 * [N] 9.4. Pattern modifiers
1392 * "IKpsk2:
1393 * <- s
1394 * ...
1395 * -> e, es, s, ss
1396 * <- e, ee, se, psk"
1397 */
1398 static void
1399 wg_fill_msg_init(struct wg_softc *wg, struct wg_peer *wgp,
1400 struct wg_session *wgs, struct wg_msg_init *wgmi)
1401 {
1402 uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.2: Ci */
1403 uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.2: Hi */
1404 uint8_t cipher_key[WG_CIPHER_KEY_LEN];
1405 uint8_t pubkey[WG_EPHEMERAL_KEY_LEN];
1406 uint8_t privkey[WG_EPHEMERAL_KEY_LEN];
1407
1408 KASSERT(mutex_owned(wgp->wgp_lock));
1409 KASSERT(wgs == wgp->wgp_session_unstable);
1410 KASSERTMSG(wgs->wgs_state == WGS_STATE_INIT_ACTIVE, "state=%d",
1411 wgs->wgs_state);
1412
1413 wgmi->wgmi_type = htole32(WG_MSG_TYPE_INIT);
1414 wgmi->wgmi_sender = wgs->wgs_local_index;
1415
1416 /* [W] 5.4.2: First Message: Initiator to Responder */
1417
1418 /* Ci := HASH(CONSTRUCTION) */
1419 /* Hi := HASH(Ci || IDENTIFIER) */
1420 wg_init_key_and_hash(ckey, hash);
1421 /* Hi := HASH(Hi || Sr^pub) */
1422 wg_algo_hash(hash, wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey));
1423
1424 WG_DUMP_HASH("hash", hash);
1425
1426 /* [N] 2.2: "e" */
1427 /* Ei^priv, Ei^pub := DH-GENERATE() */
1428 wg_algo_generate_keypair(pubkey, privkey);
1429 /* Ci := KDF1(Ci, Ei^pub) */
1430 wg_algo_kdf(ckey, NULL, NULL, ckey, pubkey, sizeof(pubkey));
1431 /* msg.ephemeral := Ei^pub */
1432 memcpy(wgmi->wgmi_ephemeral, pubkey, sizeof(wgmi->wgmi_ephemeral));
1433 /* Hi := HASH(Hi || msg.ephemeral) */
1434 wg_algo_hash(hash, pubkey, sizeof(pubkey));
1435
1436 WG_DUMP_HASH("ckey", ckey);
1437 WG_DUMP_HASH("hash", hash);
1438
1439 /* [N] 2.2: "es" */
1440 /* Ci, k := KDF2(Ci, DH(Ei^priv, Sr^pub)) */
1441 wg_algo_dh_kdf(ckey, cipher_key, privkey, wgp->wgp_pubkey);
1442
1443 /* [N] 2.2: "s" */
1444 /* msg.static := AEAD(k, 0, Si^pub, Hi) */
1445 wg_algo_aead_enc(wgmi->wgmi_static, sizeof(wgmi->wgmi_static),
1446 cipher_key, 0, wg->wg_pubkey, sizeof(wg->wg_pubkey),
1447 hash, sizeof(hash));
1448 /* Hi := HASH(Hi || msg.static) */
1449 wg_algo_hash(hash, wgmi->wgmi_static, sizeof(wgmi->wgmi_static));
1450
1451 WG_DUMP_HASH48("wgmi_static", wgmi->wgmi_static);
1452
1453 /* [N] 2.2: "ss" */
1454 /* Ci, k := KDF2(Ci, DH(Si^priv, Sr^pub)) */
1455 wg_algo_dh_kdf(ckey, cipher_key, wg->wg_privkey, wgp->wgp_pubkey);
1456
1457 /* msg.timestamp := AEAD(k, TIMESTAMP(), Hi) */
1458 wg_timestamp_t timestamp;
1459 wg_algo_tai64n(timestamp);
1460 wg_algo_aead_enc(wgmi->wgmi_timestamp, sizeof(wgmi->wgmi_timestamp),
1461 cipher_key, 0, timestamp, sizeof(timestamp), hash, sizeof(hash));
1462 /* Hi := HASH(Hi || msg.timestamp) */
1463 wg_algo_hash(hash, wgmi->wgmi_timestamp, sizeof(wgmi->wgmi_timestamp));
1464
1465 /* [W] 5.4.4 Cookie MACs */
1466 wg_algo_mac_mac1(wgmi->wgmi_mac1, sizeof(wgmi->wgmi_mac1),
1467 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey),
1468 (const uint8_t *)wgmi, offsetof(struct wg_msg_init, wgmi_mac1));
1469 /* Need mac1 to decrypt a cookie from a cookie message */
1470 memcpy(wgp->wgp_last_sent_mac1, wgmi->wgmi_mac1,
1471 sizeof(wgp->wgp_last_sent_mac1));
1472 wgp->wgp_last_sent_mac1_valid = true;
1473
1474 if (wgp->wgp_latest_cookie_time == 0 ||
1475 (time_uptime - wgp->wgp_latest_cookie_time) >= WG_COOKIE_TIME)
1476 memset(wgmi->wgmi_mac2, 0, sizeof(wgmi->wgmi_mac2));
1477 else {
1478 wg_algo_mac(wgmi->wgmi_mac2, sizeof(wgmi->wgmi_mac2),
1479 wgp->wgp_latest_cookie, WG_COOKIE_LEN,
1480 (const uint8_t *)wgmi,
1481 offsetof(struct wg_msg_init, wgmi_mac2),
1482 NULL, 0);
1483 }
1484
1485 memcpy(wgs->wgs_ephemeral_key_pub, pubkey, sizeof(pubkey));
1486 memcpy(wgs->wgs_ephemeral_key_priv, privkey, sizeof(privkey));
1487 memcpy(wgs->wgs_handshake_hash, hash, sizeof(hash));
1488 memcpy(wgs->wgs_chaining_key, ckey, sizeof(ckey));
1489 WG_DLOG("%s: sender=%x\n", __func__, wgs->wgs_local_index);
1490 }
1491
1492 static void __noinline
1493 wg_handle_msg_init(struct wg_softc *wg, const struct wg_msg_init *wgmi,
1494 const struct sockaddr *src)
1495 {
1496 uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.2: Ci */
1497 uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.2: Hi */
1498 uint8_t cipher_key[WG_CIPHER_KEY_LEN];
1499 uint8_t peer_pubkey[WG_STATIC_KEY_LEN];
1500 struct wg_peer *wgp;
1501 struct wg_session *wgs;
1502 int error, ret;
1503 struct psref psref_peer;
1504 uint8_t mac1[WG_MAC_LEN];
1505
1506 WG_TRACE("init msg received");
1507
1508 wg_algo_mac_mac1(mac1, sizeof(mac1),
1509 wg->wg_pubkey, sizeof(wg->wg_pubkey),
1510 (const uint8_t *)wgmi, offsetof(struct wg_msg_init, wgmi_mac1));
1511
1512 /*
1513 * [W] 5.3: Denial of Service Mitigation & Cookies
1514 * "the responder, ..., must always reject messages with an invalid
1515 * msg.mac1"
1516 */
1517 if (!consttime_memequal(mac1, wgmi->wgmi_mac1, sizeof(mac1))) {
1518 WG_DLOG("mac1 is invalid\n");
1519 return;
1520 }
1521
1522 /*
1523 * [W] 5.4.2: First Message: Initiator to Responder
1524 * "When the responder receives this message, it does the same
1525 * operations so that its final state variables are identical,
1526 * replacing the operands of the DH function to produce equivalent
1527 * values."
1528 * Note that the following comments of operations are just copies of
1529 * the initiator's ones.
1530 */
1531
1532 /* Ci := HASH(CONSTRUCTION) */
1533 /* Hi := HASH(Ci || IDENTIFIER) */
1534 wg_init_key_and_hash(ckey, hash);
1535 /* Hi := HASH(Hi || Sr^pub) */
1536 wg_algo_hash(hash, wg->wg_pubkey, sizeof(wg->wg_pubkey));
1537
1538 /* [N] 2.2: "e" */
1539 /* Ci := KDF1(Ci, Ei^pub) */
1540 wg_algo_kdf(ckey, NULL, NULL, ckey, wgmi->wgmi_ephemeral,
1541 sizeof(wgmi->wgmi_ephemeral));
1542 /* Hi := HASH(Hi || msg.ephemeral) */
1543 wg_algo_hash(hash, wgmi->wgmi_ephemeral, sizeof(wgmi->wgmi_ephemeral));
1544
1545 WG_DUMP_HASH("ckey", ckey);
1546
1547 /* [N] 2.2: "es" */
1548 /* Ci, k := KDF2(Ci, DH(Ei^priv, Sr^pub)) */
1549 wg_algo_dh_kdf(ckey, cipher_key, wg->wg_privkey, wgmi->wgmi_ephemeral);
1550
1551 WG_DUMP_HASH48("wgmi_static", wgmi->wgmi_static);
1552
1553 /* [N] 2.2: "s" */
1554 /* msg.static := AEAD(k, 0, Si^pub, Hi) */
1555 error = wg_algo_aead_dec(peer_pubkey, WG_STATIC_KEY_LEN, cipher_key, 0,
1556 wgmi->wgmi_static, sizeof(wgmi->wgmi_static), hash, sizeof(hash));
1557 if (error != 0) {
1558 WG_LOG_RATECHECK(&wg->wg_ppsratecheck, LOG_DEBUG,
1559 "%s: wg_algo_aead_dec for secret key failed\n",
1560 if_name(&wg->wg_if));
1561 return;
1562 }
1563 /* Hi := HASH(Hi || msg.static) */
1564 wg_algo_hash(hash, wgmi->wgmi_static, sizeof(wgmi->wgmi_static));
1565
1566 wgp = wg_lookup_peer_by_pubkey(wg, peer_pubkey, &psref_peer);
1567 if (wgp == NULL) {
1568 WG_DLOG("peer not found\n");
1569 return;
1570 }
1571
1572 /*
1573 * Lock the peer to serialize access to cookie state.
1574 *
1575 * XXX Can we safely avoid holding the lock across DH? Take it
1576 * just to verify mac2 and then unlock/DH/lock?
1577 */
1578 mutex_enter(wgp->wgp_lock);
1579
1580 if (__predict_false(wg_is_underload(wg, wgp, WG_MSG_TYPE_INIT))) {
1581 WG_TRACE("under load");
1582 /*
1583 * [W] 5.3: Denial of Service Mitigation & Cookies
1584 * "the responder, ..., and when under load may reject messages
1585 * with an invalid msg.mac2. If the responder receives a
1586 * message with a valid msg.mac1 yet with an invalid msg.mac2,
1587 * and is under load, it may respond with a cookie reply
1588 * message"
1589 */
1590 uint8_t zero[WG_MAC_LEN] = {0};
1591 if (consttime_memequal(wgmi->wgmi_mac2, zero, sizeof(zero))) {
1592 WG_TRACE("sending a cookie message: no cookie included");
1593 wg_send_cookie_msg(wg, wgp, wgmi->wgmi_sender,
1594 wgmi->wgmi_mac1, src);
1595 goto out;
1596 }
1597 if (!wgp->wgp_last_sent_cookie_valid) {
1598 WG_TRACE("sending a cookie message: no cookie sent ever");
1599 wg_send_cookie_msg(wg, wgp, wgmi->wgmi_sender,
1600 wgmi->wgmi_mac1, src);
1601 goto out;
1602 }
1603 uint8_t mac2[WG_MAC_LEN];
1604 wg_algo_mac(mac2, sizeof(mac2), wgp->wgp_last_sent_cookie,
1605 WG_COOKIE_LEN, (const uint8_t *)wgmi,
1606 offsetof(struct wg_msg_init, wgmi_mac2), NULL, 0);
1607 if (!consttime_memequal(mac2, wgmi->wgmi_mac2, sizeof(mac2))) {
1608 WG_DLOG("mac2 is invalid\n");
1609 goto out;
1610 }
1611 WG_TRACE("under load, but continue to sending");
1612 }
1613
1614 /* [N] 2.2: "ss" */
1615 /* Ci, k := KDF2(Ci, DH(Si^priv, Sr^pub)) */
1616 wg_algo_dh_kdf(ckey, cipher_key, wg->wg_privkey, wgp->wgp_pubkey);
1617
1618 /* msg.timestamp := AEAD(k, TIMESTAMP(), Hi) */
1619 wg_timestamp_t timestamp;
1620 error = wg_algo_aead_dec(timestamp, sizeof(timestamp), cipher_key, 0,
1621 wgmi->wgmi_timestamp, sizeof(wgmi->wgmi_timestamp),
1622 hash, sizeof(hash));
1623 if (error != 0) {
1624 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
1625 "%s: peer %s: wg_algo_aead_dec for timestamp failed\n",
1626 if_name(&wg->wg_if), wgp->wgp_name);
1627 goto out;
1628 }
1629 /* Hi := HASH(Hi || msg.timestamp) */
1630 wg_algo_hash(hash, wgmi->wgmi_timestamp, sizeof(wgmi->wgmi_timestamp));
1631
1632 /*
1633 * [W] 5.1 "The responder keeps track of the greatest timestamp
1634 * received per peer and discards packets containing
1635 * timestamps less than or equal to it."
1636 */
1637 ret = memcmp(timestamp, wgp->wgp_timestamp_latest_init,
1638 sizeof(timestamp));
1639 if (ret <= 0) {
1640 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
1641 "%s: peer %s: invalid init msg: timestamp is old\n",
1642 if_name(&wg->wg_if), wgp->wgp_name);
1643 goto out;
1644 }
1645 memcpy(wgp->wgp_timestamp_latest_init, timestamp, sizeof(timestamp));
1646
1647 /*
1648 * Message is good -- we're committing to handle it now, unless
1649 * we were already initiating a session.
1650 */
1651 wgs = wgp->wgp_session_unstable;
1652 switch (wgs->wgs_state) {
1653 case WGS_STATE_UNKNOWN: /* new session initiated by peer */
1654 break;
1655 case WGS_STATE_INIT_ACTIVE: /* we're already initiating, drop */
1656 /* XXX Who wins if both sides send INIT? */
1657 WG_TRACE("Session already initializing, ignoring the message");
1658 goto out;
1659 case WGS_STATE_INIT_PASSIVE: /* peer is retrying, start over */
1660 WG_TRACE("Session already initializing, destroying old states");
1661 /*
1662 * XXX Avoid this -- just resend our response -- if the
1663 * INIT message is identical to the previous one.
1664 */
1665 wg_put_session_index(wg, wgs);
1666 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1667 wgs->wgs_state);
1668 break;
1669 case WGS_STATE_ESTABLISHED: /* can't happen */
1670 panic("unstable session can't be established");
1671 case WGS_STATE_DESTROYING: /* rekey initiated by peer */
1672 WG_TRACE("Session destroying, but force to clear");
1673 wg_put_session_index(wg, wgs);
1674 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1675 wgs->wgs_state);
1676 break;
1677 default:
1678 panic("invalid session state: %d", wgs->wgs_state);
1679 }
1680
1681 /*
1682 * Assign a fresh session index.
1683 */
1684 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1685 wgs->wgs_state);
1686 wg_get_session_index(wg, wgs);
1687
1688 memcpy(wgs->wgs_handshake_hash, hash, sizeof(hash));
1689 memcpy(wgs->wgs_chaining_key, ckey, sizeof(ckey));
1690 memcpy(wgs->wgs_ephemeral_key_peer, wgmi->wgmi_ephemeral,
1691 sizeof(wgmi->wgmi_ephemeral));
1692
1693 wg_update_endpoint_if_necessary(wgp, src);
1694
1695 /*
1696 * Count the time of the INIT message as the time of
1697 * establishment -- this is used to decide when to erase keys,
1698 * and we want to start counting as soon as we have generated
1699 * keys.
1700 *
1701 * No need for atomic store because the session can't be used
1702 * in the rx or tx paths yet -- not until we transition to
1703 * INTI_PASSIVE.
1704 */
1705 wgs->wgs_time_established = time_uptime32;
1706 wg_schedule_session_dtor_timer(wgp);
1707
1708 /*
1709 * Respond to the initiator with our ephemeral public key.
1710 */
1711 wg_send_handshake_msg_resp(wg, wgp, wgs, wgmi);
1712
1713 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]:"
1714 " calculate keys as responder\n",
1715 wgs->wgs_local_index, wgs->wgs_remote_index);
1716 wg_calculate_keys(wgs, false);
1717 wg_clear_states(wgs);
1718
1719 /*
1720 * Session is ready to receive data now that we have received
1721 * the peer initiator's ephemeral key pair, generated our
1722 * responder's ephemeral key pair, and derived a session key.
1723 *
1724 * Transition from UNKNOWN to INIT_PASSIVE to publish it to the
1725 * data rx path, wg_handle_msg_data, where the
1726 * atomic_load_acquire matching this atomic_store_release
1727 * happens.
1728 *
1729 * (Session is not, however, ready to send data until the peer
1730 * has acknowledged our response by sending its first data
1731 * packet. So don't swap the sessions yet.)
1732 */
1733 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_INIT_PASSIVE\n",
1734 wgs->wgs_local_index, wgs->wgs_remote_index);
1735 atomic_store_release(&wgs->wgs_state, WGS_STATE_INIT_PASSIVE);
1736 WG_TRACE("WGS_STATE_INIT_PASSIVE");
1737
1738 out:
1739 mutex_exit(wgp->wgp_lock);
1740 wg_put_peer(wgp, &psref_peer);
1741 }
1742
1743 static struct socket *
1744 wg_get_so_by_af(struct wg_softc *wg, const int af)
1745 {
1746
1747 switch (af) {
1748 #ifdef INET
1749 case AF_INET:
1750 return wg->wg_so4;
1751 #endif
1752 #ifdef INET6
1753 case AF_INET6:
1754 return wg->wg_so6;
1755 #endif
1756 default:
1757 panic("wg: no such af: %d", af);
1758 }
1759 }
1760
1761 static struct socket *
1762 wg_get_so_by_peer(struct wg_peer *wgp, struct wg_sockaddr *wgsa)
1763 {
1764
1765 return wg_get_so_by_af(wgp->wgp_sc, wgsa_family(wgsa));
1766 }
1767
1768 static struct wg_sockaddr *
1769 wg_get_endpoint_sa(struct wg_peer *wgp, struct psref *psref)
1770 {
1771 struct wg_sockaddr *wgsa;
1772 int s;
1773
1774 s = pserialize_read_enter();
1775 wgsa = atomic_load_consume(&wgp->wgp_endpoint);
1776 psref_acquire(psref, &wgsa->wgsa_psref, wg_psref_class);
1777 pserialize_read_exit(s);
1778
1779 return wgsa;
1780 }
1781
1782 static void
1783 wg_put_sa(struct wg_peer *wgp, struct wg_sockaddr *wgsa, struct psref *psref)
1784 {
1785
1786 psref_release(psref, &wgsa->wgsa_psref, wg_psref_class);
1787 }
1788
1789 static int
1790 wg_send_so(struct wg_peer *wgp, struct mbuf *m)
1791 {
1792 int error;
1793 struct socket *so;
1794 struct psref psref;
1795 struct wg_sockaddr *wgsa;
1796
1797 wgsa = wg_get_endpoint_sa(wgp, &psref);
1798 so = wg_get_so_by_peer(wgp, wgsa);
1799 error = sosend(so, wgsatosa(wgsa), NULL, m, NULL, 0, curlwp);
1800 wg_put_sa(wgp, wgsa, &psref);
1801
1802 return error;
1803 }
1804
1805 static void
1806 wg_send_handshake_msg_init(struct wg_softc *wg, struct wg_peer *wgp)
1807 {
1808 int error;
1809 struct mbuf *m;
1810 struct wg_msg_init *wgmi;
1811 struct wg_session *wgs;
1812
1813 KASSERT(mutex_owned(wgp->wgp_lock));
1814
1815 wgs = wgp->wgp_session_unstable;
1816 /* XXX pull dispatch out into wg_task_send_init_message */
1817 switch (wgs->wgs_state) {
1818 case WGS_STATE_UNKNOWN: /* new session initiated by us */
1819 break;
1820 case WGS_STATE_INIT_ACTIVE: /* we're already initiating, stop */
1821 WG_TRACE("Session already initializing, skip starting new one");
1822 return;
1823 case WGS_STATE_INIT_PASSIVE: /* peer was trying -- XXX what now? */
1824 WG_TRACE("Session already initializing, waiting for peer");
1825 return;
1826 case WGS_STATE_ESTABLISHED: /* can't happen */
1827 panic("unstable session can't be established");
1828 case WGS_STATE_DESTROYING: /* rekey initiated by us too early */
1829 WG_TRACE("Session destroying");
1830 wg_put_session_index(wg, wgs);
1831 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1832 wgs->wgs_state);
1833 break;
1834 }
1835
1836 /*
1837 * Assign a fresh session index.
1838 */
1839 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1840 wgs->wgs_state);
1841 wg_get_session_index(wg, wgs);
1842
1843 /*
1844 * We have initiated a session. Transition to INIT_ACTIVE.
1845 * This doesn't publish it for use in the data rx path,
1846 * wg_handle_msg_data, or in the data tx path, wg_output -- we
1847 * have to wait for the peer to respond with their ephemeral
1848 * public key before we can derive a session key for tx/rx.
1849 * Hence only atomic_store_relaxed.
1850 */
1851 WG_DLOG("session[L=%"PRIx32" R=(unknown)] -> WGS_STATE_INIT_ACTIVE\n",
1852 wgs->wgs_local_index);
1853 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_INIT_ACTIVE);
1854
1855 m = m_gethdr(M_WAIT, MT_DATA);
1856 if (sizeof(*wgmi) > MHLEN) {
1857 m_clget(m, M_WAIT);
1858 CTASSERT(sizeof(*wgmi) <= MCLBYTES);
1859 }
1860 m->m_pkthdr.len = m->m_len = sizeof(*wgmi);
1861 wgmi = mtod(m, struct wg_msg_init *);
1862 wg_fill_msg_init(wg, wgp, wgs, wgmi);
1863
1864 error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
1865 if (error) {
1866 /*
1867 * Sending out an initiation packet failed; give up on
1868 * this session and toss packet waiting for it if any.
1869 *
1870 * XXX Why don't we just let the periodic handshake
1871 * retry logic work in this case?
1872 */
1873 WG_DLOG("send_hs_msg failed, error=%d\n", error);
1874 wg_put_session_index(wg, wgs);
1875 m = atomic_swap_ptr(&wgp->wgp_pending, NULL);
1876 m_freem(m);
1877 return;
1878 }
1879
1880 WG_TRACE("init msg sent");
1881 if (wgp->wgp_handshake_start_time == 0)
1882 wgp->wgp_handshake_start_time = time_uptime;
1883 callout_schedule(&wgp->wgp_handshake_timeout_timer,
1884 MIN(wg_rekey_timeout, (unsigned)(INT_MAX / hz)) * hz);
1885 }
1886
1887 static void
1888 wg_fill_msg_resp(struct wg_softc *wg, struct wg_peer *wgp,
1889 struct wg_session *wgs, struct wg_msg_resp *wgmr,
1890 const struct wg_msg_init *wgmi)
1891 {
1892 uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.3: Cr */
1893 uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.3: Hr */
1894 uint8_t cipher_key[WG_KDF_OUTPUT_LEN];
1895 uint8_t pubkey[WG_EPHEMERAL_KEY_LEN];
1896 uint8_t privkey[WG_EPHEMERAL_KEY_LEN];
1897
1898 KASSERT(mutex_owned(wgp->wgp_lock));
1899 KASSERT(wgs == wgp->wgp_session_unstable);
1900 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1901 wgs->wgs_state);
1902
1903 memcpy(hash, wgs->wgs_handshake_hash, sizeof(hash));
1904 memcpy(ckey, wgs->wgs_chaining_key, sizeof(ckey));
1905
1906 wgmr->wgmr_type = htole32(WG_MSG_TYPE_RESP);
1907 wgmr->wgmr_sender = wgs->wgs_local_index;
1908 wgmr->wgmr_receiver = wgmi->wgmi_sender;
1909
1910 /* [W] 5.4.3 Second Message: Responder to Initiator */
1911
1912 /* [N] 2.2: "e" */
1913 /* Er^priv, Er^pub := DH-GENERATE() */
1914 wg_algo_generate_keypair(pubkey, privkey);
1915 /* Cr := KDF1(Cr, Er^pub) */
1916 wg_algo_kdf(ckey, NULL, NULL, ckey, pubkey, sizeof(pubkey));
1917 /* msg.ephemeral := Er^pub */
1918 memcpy(wgmr->wgmr_ephemeral, pubkey, sizeof(wgmr->wgmr_ephemeral));
1919 /* Hr := HASH(Hr || msg.ephemeral) */
1920 wg_algo_hash(hash, pubkey, sizeof(pubkey));
1921
1922 WG_DUMP_HASH("ckey", ckey);
1923 WG_DUMP_HASH("hash", hash);
1924
1925 /* [N] 2.2: "ee" */
1926 /* Cr := KDF1(Cr, DH(Er^priv, Ei^pub)) */
1927 wg_algo_dh_kdf(ckey, NULL, privkey, wgs->wgs_ephemeral_key_peer);
1928
1929 /* [N] 2.2: "se" */
1930 /* Cr := KDF1(Cr, DH(Er^priv, Si^pub)) */
1931 wg_algo_dh_kdf(ckey, NULL, privkey, wgp->wgp_pubkey);
1932
1933 /* [N] 9.2: "psk" */
1934 {
1935 uint8_t kdfout[WG_KDF_OUTPUT_LEN];
1936 /* Cr, r, k := KDF3(Cr, Q) */
1937 wg_algo_kdf(ckey, kdfout, cipher_key, ckey, wgp->wgp_psk,
1938 sizeof(wgp->wgp_psk));
1939 /* Hr := HASH(Hr || r) */
1940 wg_algo_hash(hash, kdfout, sizeof(kdfout));
1941 }
1942
1943 /* msg.empty := AEAD(k, 0, e, Hr) */
1944 wg_algo_aead_enc(wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty),
1945 cipher_key, 0, NULL, 0, hash, sizeof(hash));
1946 /* Hr := HASH(Hr || msg.empty) */
1947 wg_algo_hash(hash, wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty));
1948
1949 WG_DUMP_HASH("wgmr_empty", wgmr->wgmr_empty);
1950
1951 /* [W] 5.4.4: Cookie MACs */
1952 /* msg.mac1 := MAC(HASH(LABEL-MAC1 || Sm'^pub), msg_a) */
1953 wg_algo_mac_mac1(wgmr->wgmr_mac1, sizeof(wgmi->wgmi_mac1),
1954 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey),
1955 (const uint8_t *)wgmr, offsetof(struct wg_msg_resp, wgmr_mac1));
1956 /* Need mac1 to decrypt a cookie from a cookie message */
1957 memcpy(wgp->wgp_last_sent_mac1, wgmr->wgmr_mac1,
1958 sizeof(wgp->wgp_last_sent_mac1));
1959 wgp->wgp_last_sent_mac1_valid = true;
1960
1961 if (wgp->wgp_latest_cookie_time == 0 ||
1962 (time_uptime - wgp->wgp_latest_cookie_time) >= WG_COOKIE_TIME)
1963 /* msg.mac2 := 0^16 */
1964 memset(wgmr->wgmr_mac2, 0, sizeof(wgmr->wgmr_mac2));
1965 else {
1966 /* msg.mac2 := MAC(Lm, msg_b) */
1967 wg_algo_mac(wgmr->wgmr_mac2, sizeof(wgmi->wgmi_mac2),
1968 wgp->wgp_latest_cookie, WG_COOKIE_LEN,
1969 (const uint8_t *)wgmr,
1970 offsetof(struct wg_msg_resp, wgmr_mac2),
1971 NULL, 0);
1972 }
1973
1974 memcpy(wgs->wgs_handshake_hash, hash, sizeof(hash));
1975 memcpy(wgs->wgs_chaining_key, ckey, sizeof(ckey));
1976 memcpy(wgs->wgs_ephemeral_key_pub, pubkey, sizeof(pubkey));
1977 memcpy(wgs->wgs_ephemeral_key_priv, privkey, sizeof(privkey));
1978 wgs->wgs_remote_index = wgmi->wgmi_sender;
1979 WG_DLOG("sender=%x\n", wgs->wgs_local_index);
1980 WG_DLOG("receiver=%x\n", wgs->wgs_remote_index);
1981 }
1982
1983 static void
1984 wg_swap_sessions(struct wg_peer *wgp)
1985 {
1986 struct wg_session *wgs, *wgs_prev;
1987
1988 KASSERT(mutex_owned(wgp->wgp_lock));
1989
1990 /*
1991 * Get the newly established session, to become the new
1992 * session. Caller must have transitioned from INIT_ACTIVE to
1993 * INIT_PASSIVE to ESTABLISHED already. This will become the
1994 * stable session.
1995 */
1996 wgs = wgp->wgp_session_unstable;
1997 KASSERTMSG(wgs->wgs_state == WGS_STATE_ESTABLISHED, "state=%d",
1998 wgs->wgs_state);
1999
2000 /*
2001 * Get the stable session, which is either the previously
2002 * established session in the ESTABLISHED state, or has not
2003 * been established at all and is UNKNOWN. This will become
2004 * the unstable session.
2005 */
2006 wgs_prev = wgp->wgp_session_stable;
2007 KASSERTMSG((wgs_prev->wgs_state == WGS_STATE_ESTABLISHED ||
2008 wgs_prev->wgs_state == WGS_STATE_UNKNOWN),
2009 "state=%d", wgs_prev->wgs_state);
2010
2011 /*
2012 * Publish the newly established session for the tx path to use
2013 * and make the other one the unstable session to handle
2014 * stragglers in the rx path and later be used for the next
2015 * session's handshake.
2016 *
2017 * If wgs_prev was previously ESTABLISHED, caller must
2018 * transition it to DESTROYING and then pass through
2019 * wg_put_session_index before recycling it.
2020 *
2021 * XXX Factor that logic out into this routine.
2022 */
2023 atomic_store_release(&wgp->wgp_session_stable, wgs);
2024 wgp->wgp_session_unstable = wgs_prev;
2025 }
2026
2027 static void __noinline
2028 wg_handle_msg_resp(struct wg_softc *wg, const struct wg_msg_resp *wgmr,
2029 const struct sockaddr *src)
2030 {
2031 uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.3: Cr */
2032 uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.3: Kr */
2033 uint8_t cipher_key[WG_KDF_OUTPUT_LEN];
2034 struct wg_peer *wgp;
2035 struct wg_session *wgs;
2036 struct psref psref;
2037 int error;
2038 uint8_t mac1[WG_MAC_LEN];
2039 struct wg_session *wgs_prev;
2040 struct mbuf *m;
2041
2042 wg_algo_mac_mac1(mac1, sizeof(mac1),
2043 wg->wg_pubkey, sizeof(wg->wg_pubkey),
2044 (const uint8_t *)wgmr, offsetof(struct wg_msg_resp, wgmr_mac1));
2045
2046 /*
2047 * [W] 5.3: Denial of Service Mitigation & Cookies
2048 * "the responder, ..., must always reject messages with an invalid
2049 * msg.mac1"
2050 */
2051 if (!consttime_memequal(mac1, wgmr->wgmr_mac1, sizeof(mac1))) {
2052 WG_DLOG("mac1 is invalid\n");
2053 return;
2054 }
2055
2056 WG_TRACE("resp msg received");
2057 wgs = wg_lookup_session_by_index(wg, wgmr->wgmr_receiver, &psref);
2058 if (wgs == NULL) {
2059 WG_TRACE("No session found");
2060 return;
2061 }
2062
2063 wgp = wgs->wgs_peer;
2064
2065 mutex_enter(wgp->wgp_lock);
2066
2067 /* If we weren't waiting for a handshake response, drop it. */
2068 if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE) {
2069 WG_TRACE("peer sent spurious handshake response, ignoring");
2070 goto out;
2071 }
2072
2073 if (__predict_false(wg_is_underload(wg, wgp, WG_MSG_TYPE_RESP))) {
2074 WG_TRACE("under load");
2075 /*
2076 * [W] 5.3: Denial of Service Mitigation & Cookies
2077 * "the responder, ..., and when under load may reject messages
2078 * with an invalid msg.mac2. If the responder receives a
2079 * message with a valid msg.mac1 yet with an invalid msg.mac2,
2080 * and is under load, it may respond with a cookie reply
2081 * message"
2082 */
2083 uint8_t zero[WG_MAC_LEN] = {0};
2084 if (consttime_memequal(wgmr->wgmr_mac2, zero, sizeof(zero))) {
2085 WG_TRACE("sending a cookie message: no cookie included");
2086 wg_send_cookie_msg(wg, wgp, wgmr->wgmr_sender,
2087 wgmr->wgmr_mac1, src);
2088 goto out;
2089 }
2090 if (!wgp->wgp_last_sent_cookie_valid) {
2091 WG_TRACE("sending a cookie message: no cookie sent ever");
2092 wg_send_cookie_msg(wg, wgp, wgmr->wgmr_sender,
2093 wgmr->wgmr_mac1, src);
2094 goto out;
2095 }
2096 uint8_t mac2[WG_MAC_LEN];
2097 wg_algo_mac(mac2, sizeof(mac2), wgp->wgp_last_sent_cookie,
2098 WG_COOKIE_LEN, (const uint8_t *)wgmr,
2099 offsetof(struct wg_msg_resp, wgmr_mac2), NULL, 0);
2100 if (!consttime_memequal(mac2, wgmr->wgmr_mac2, sizeof(mac2))) {
2101 WG_DLOG("mac2 is invalid\n");
2102 goto out;
2103 }
2104 WG_TRACE("under load, but continue to sending");
2105 }
2106
2107 memcpy(hash, wgs->wgs_handshake_hash, sizeof(hash));
2108 memcpy(ckey, wgs->wgs_chaining_key, sizeof(ckey));
2109
2110 /*
2111 * [W] 5.4.3 Second Message: Responder to Initiator
2112 * "When the initiator receives this message, it does the same
2113 * operations so that its final state variables are identical,
2114 * replacing the operands of the DH function to produce equivalent
2115 * values."
2116 * Note that the following comments of operations are just copies of
2117 * the initiator's ones.
2118 */
2119
2120 /* [N] 2.2: "e" */
2121 /* Cr := KDF1(Cr, Er^pub) */
2122 wg_algo_kdf(ckey, NULL, NULL, ckey, wgmr->wgmr_ephemeral,
2123 sizeof(wgmr->wgmr_ephemeral));
2124 /* Hr := HASH(Hr || msg.ephemeral) */
2125 wg_algo_hash(hash, wgmr->wgmr_ephemeral, sizeof(wgmr->wgmr_ephemeral));
2126
2127 WG_DUMP_HASH("ckey", ckey);
2128 WG_DUMP_HASH("hash", hash);
2129
2130 /* [N] 2.2: "ee" */
2131 /* Cr := KDF1(Cr, DH(Er^priv, Ei^pub)) */
2132 wg_algo_dh_kdf(ckey, NULL, wgs->wgs_ephemeral_key_priv,
2133 wgmr->wgmr_ephemeral);
2134
2135 /* [N] 2.2: "se" */
2136 /* Cr := KDF1(Cr, DH(Er^priv, Si^pub)) */
2137 wg_algo_dh_kdf(ckey, NULL, wg->wg_privkey, wgmr->wgmr_ephemeral);
2138
2139 /* [N] 9.2: "psk" */
2140 {
2141 uint8_t kdfout[WG_KDF_OUTPUT_LEN];
2142 /* Cr, r, k := KDF3(Cr, Q) */
2143 wg_algo_kdf(ckey, kdfout, cipher_key, ckey, wgp->wgp_psk,
2144 sizeof(wgp->wgp_psk));
2145 /* Hr := HASH(Hr || r) */
2146 wg_algo_hash(hash, kdfout, sizeof(kdfout));
2147 }
2148
2149 {
2150 uint8_t out[sizeof(wgmr->wgmr_empty)]; /* for safety */
2151 /* msg.empty := AEAD(k, 0, e, Hr) */
2152 error = wg_algo_aead_dec(out, 0, cipher_key, 0, wgmr->wgmr_empty,
2153 sizeof(wgmr->wgmr_empty), hash, sizeof(hash));
2154 WG_DUMP_HASH("wgmr_empty", wgmr->wgmr_empty);
2155 if (error != 0) {
2156 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2157 "%s: peer %s: wg_algo_aead_dec for empty message failed\n",
2158 if_name(&wg->wg_if), wgp->wgp_name);
2159 goto out;
2160 }
2161 /* Hr := HASH(Hr || msg.empty) */
2162 wg_algo_hash(hash, wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty));
2163 }
2164
2165 memcpy(wgs->wgs_handshake_hash, hash, sizeof(wgs->wgs_handshake_hash));
2166 memcpy(wgs->wgs_chaining_key, ckey, sizeof(wgs->wgs_chaining_key));
2167 wgs->wgs_remote_index = wgmr->wgmr_sender;
2168 WG_DLOG("receiver=%x\n", wgs->wgs_remote_index);
2169
2170 KASSERTMSG(wgs->wgs_state == WGS_STATE_INIT_ACTIVE, "state=%d",
2171 wgs->wgs_state);
2172 wgs->wgs_time_established = time_uptime32;
2173 wg_schedule_session_dtor_timer(wgp);
2174 wgs->wgs_time_last_data_sent = 0;
2175 wgs->wgs_is_initiator = true;
2176 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]:"
2177 " calculate keys as initiator\n",
2178 wgs->wgs_local_index, wgs->wgs_remote_index);
2179 wg_calculate_keys(wgs, true);
2180 wg_clear_states(wgs);
2181
2182 /*
2183 * Session is ready to receive data now that we have received
2184 * the responder's response.
2185 *
2186 * Transition from INIT_ACTIVE to ESTABLISHED to publish it to
2187 * the data rx path, wg_handle_msg_data.
2188 */
2189 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32" -> WGS_STATE_ESTABLISHED\n",
2190 wgs->wgs_local_index, wgs->wgs_remote_index);
2191 atomic_store_release(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
2192 WG_TRACE("WGS_STATE_ESTABLISHED");
2193
2194 callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
2195
2196 /*
2197 * Session is ready to send data now that we have received the
2198 * responder's response.
2199 *
2200 * Swap the sessions to publish the new one as the stable
2201 * session for the data tx path, wg_output.
2202 */
2203 wg_swap_sessions(wgp);
2204 KASSERT(wgs == wgp->wgp_session_stable);
2205 wgs_prev = wgp->wgp_session_unstable;
2206 getnanotime(&wgp->wgp_last_handshake_time);
2207 wgp->wgp_handshake_start_time = 0;
2208 wgp->wgp_last_sent_mac1_valid = false;
2209 wgp->wgp_last_sent_cookie_valid = false;
2210
2211 wg_update_endpoint_if_necessary(wgp, src);
2212
2213 /*
2214 * If we had a data packet queued up, send it; otherwise send a
2215 * keepalive message -- either way we have to send something
2216 * immediately or else the responder will never answer.
2217 */
2218 if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
2219 kpreempt_disable();
2220 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
2221 M_SETCTX(m, wgp);
2222 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
2223 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
2224 if_name(&wg->wg_if));
2225 m_freem(m);
2226 }
2227 kpreempt_enable();
2228 } else {
2229 wg_send_keepalive_msg(wgp, wgs);
2230 }
2231
2232 if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
2233 /*
2234 * Transition ESTABLISHED->DESTROYING. The session
2235 * will remain usable for the data rx path to process
2236 * packets still in flight to us, but we won't use it
2237 * for data tx.
2238 */
2239 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
2240 " -> WGS_STATE_DESTROYING\n",
2241 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
2242 atomic_store_relaxed(&wgs_prev->wgs_state,
2243 WGS_STATE_DESTROYING);
2244 } else {
2245 KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
2246 "state=%d", wgs_prev->wgs_state);
2247 }
2248
2249 out:
2250 mutex_exit(wgp->wgp_lock);
2251 wg_put_session(wgs, &psref);
2252 }
2253
2254 static void
2255 wg_send_handshake_msg_resp(struct wg_softc *wg, struct wg_peer *wgp,
2256 struct wg_session *wgs, const struct wg_msg_init *wgmi)
2257 {
2258 int error;
2259 struct mbuf *m;
2260 struct wg_msg_resp *wgmr;
2261
2262 KASSERT(mutex_owned(wgp->wgp_lock));
2263 KASSERT(wgs == wgp->wgp_session_unstable);
2264 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
2265 wgs->wgs_state);
2266
2267 m = m_gethdr(M_WAIT, MT_DATA);
2268 if (sizeof(*wgmr) > MHLEN) {
2269 m_clget(m, M_WAIT);
2270 CTASSERT(sizeof(*wgmr) <= MCLBYTES);
2271 }
2272 m->m_pkthdr.len = m->m_len = sizeof(*wgmr);
2273 wgmr = mtod(m, struct wg_msg_resp *);
2274 wg_fill_msg_resp(wg, wgp, wgs, wgmr, wgmi);
2275
2276 error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
2277 if (error) {
2278 WG_DLOG("send_hs_msg failed, error=%d\n", error);
2279 return;
2280 }
2281
2282 WG_TRACE("resp msg sent");
2283 }
2284
2285 static struct wg_peer *
2286 wg_lookup_peer_by_pubkey(struct wg_softc *wg,
2287 const uint8_t pubkey[static WG_STATIC_KEY_LEN], struct psref *psref)
2288 {
2289 struct wg_peer *wgp;
2290
2291 int s = pserialize_read_enter();
2292 wgp = thmap_get(wg->wg_peers_bypubkey, pubkey, WG_STATIC_KEY_LEN);
2293 if (wgp != NULL)
2294 wg_get_peer(wgp, psref);
2295 pserialize_read_exit(s);
2296
2297 return wgp;
2298 }
2299
2300 static void
2301 wg_fill_msg_cookie(struct wg_softc *wg, struct wg_peer *wgp,
2302 struct wg_msg_cookie *wgmc, const uint32_t sender,
2303 const uint8_t mac1[static WG_MAC_LEN], const struct sockaddr *src)
2304 {
2305 uint8_t cookie[WG_COOKIE_LEN];
2306 uint8_t key[WG_HASH_LEN];
2307 uint8_t addr[sizeof(struct in6_addr)];
2308 size_t addrlen;
2309 uint16_t uh_sport; /* be */
2310
2311 KASSERT(mutex_owned(wgp->wgp_lock));
2312
2313 wgmc->wgmc_type = htole32(WG_MSG_TYPE_COOKIE);
2314 wgmc->wgmc_receiver = sender;
2315 cprng_fast(wgmc->wgmc_salt, sizeof(wgmc->wgmc_salt));
2316
2317 /*
2318 * [W] 5.4.7: Under Load: Cookie Reply Message
2319 * "The secret variable, Rm, changes every two minutes to a
2320 * random value"
2321 */
2322 if ((time_uptime - wgp->wgp_last_cookiesecret_time) >
2323 WG_COOKIESECRET_TIME) {
2324 cprng_strong(kern_cprng, wgp->wgp_cookiesecret,
2325 sizeof(wgp->wgp_cookiesecret), 0);
2326 wgp->wgp_last_cookiesecret_time = time_uptime;
2327 }
2328
2329 switch (src->sa_family) {
2330 #ifdef INET
2331 case AF_INET: {
2332 const struct sockaddr_in *sin = satocsin(src);
2333 addrlen = sizeof(sin->sin_addr);
2334 memcpy(addr, &sin->sin_addr, addrlen);
2335 uh_sport = sin->sin_port;
2336 break;
2337 }
2338 #endif
2339 #ifdef INET6
2340 case AF_INET6: {
2341 const struct sockaddr_in6 *sin6 = satocsin6(src);
2342 addrlen = sizeof(sin6->sin6_addr);
2343 memcpy(addr, &sin6->sin6_addr, addrlen);
2344 uh_sport = sin6->sin6_port;
2345 break;
2346 }
2347 #endif
2348 default:
2349 panic("invalid af=%d", src->sa_family);
2350 }
2351
2352 wg_algo_mac(cookie, sizeof(cookie),
2353 wgp->wgp_cookiesecret, sizeof(wgp->wgp_cookiesecret),
2354 addr, addrlen, (const uint8_t *)&uh_sport, sizeof(uh_sport));
2355 wg_algo_mac_cookie(key, sizeof(key), wg->wg_pubkey,
2356 sizeof(wg->wg_pubkey));
2357 wg_algo_xaead_enc(wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie), key,
2358 cookie, sizeof(cookie), mac1, WG_MAC_LEN, wgmc->wgmc_salt);
2359
2360 /* Need to store to calculate mac2 */
2361 memcpy(wgp->wgp_last_sent_cookie, cookie, sizeof(cookie));
2362 wgp->wgp_last_sent_cookie_valid = true;
2363 }
2364
2365 static void
2366 wg_send_cookie_msg(struct wg_softc *wg, struct wg_peer *wgp,
2367 const uint32_t sender, const uint8_t mac1[static WG_MAC_LEN],
2368 const struct sockaddr *src)
2369 {
2370 int error;
2371 struct mbuf *m;
2372 struct wg_msg_cookie *wgmc;
2373
2374 KASSERT(mutex_owned(wgp->wgp_lock));
2375
2376 m = m_gethdr(M_WAIT, MT_DATA);
2377 if (sizeof(*wgmc) > MHLEN) {
2378 m_clget(m, M_WAIT);
2379 CTASSERT(sizeof(*wgmc) <= MCLBYTES);
2380 }
2381 m->m_pkthdr.len = m->m_len = sizeof(*wgmc);
2382 wgmc = mtod(m, struct wg_msg_cookie *);
2383 wg_fill_msg_cookie(wg, wgp, wgmc, sender, mac1, src);
2384
2385 error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
2386 if (error) {
2387 WG_DLOG("send_hs_msg failed, error=%d\n", error);
2388 return;
2389 }
2390
2391 WG_TRACE("cookie msg sent");
2392 }
2393
2394 static bool
2395 wg_is_underload(struct wg_softc *wg, struct wg_peer *wgp, int msgtype)
2396 {
2397 #ifdef WG_DEBUG_PARAMS
2398 if (wg_force_underload)
2399 return true;
2400 #endif
2401
2402 /*
2403 * XXX we don't have a means of a load estimation. The purpose of
2404 * the mechanism is a DoS mitigation, so we consider frequent handshake
2405 * messages as (a kind of) load; if a message of the same type comes
2406 * to a peer within 1 second, we consider we are under load.
2407 */
2408 time_t last = wgp->wgp_last_msg_received_time[msgtype];
2409 wgp->wgp_last_msg_received_time[msgtype] = time_uptime;
2410 return (time_uptime - last) == 0;
2411 }
2412
2413 static void
2414 wg_calculate_keys(struct wg_session *wgs, const bool initiator)
2415 {
2416
2417 KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
2418
2419 /*
2420 * [W] 5.4.5: Ti^send = Tr^recv, Ti^recv = Tr^send := KDF2(Ci = Cr, e)
2421 */
2422 if (initiator) {
2423 wg_algo_kdf(wgs->wgs_tkey_send, wgs->wgs_tkey_recv, NULL,
2424 wgs->wgs_chaining_key, NULL, 0);
2425 } else {
2426 wg_algo_kdf(wgs->wgs_tkey_recv, wgs->wgs_tkey_send, NULL,
2427 wgs->wgs_chaining_key, NULL, 0);
2428 }
2429 WG_DUMP_HASH("wgs_tkey_send", wgs->wgs_tkey_send);
2430 WG_DUMP_HASH("wgs_tkey_recv", wgs->wgs_tkey_recv);
2431 }
2432
2433 static uint64_t
2434 wg_session_get_send_counter(struct wg_session *wgs)
2435 {
2436 #ifdef __HAVE_ATOMIC64_LOADSTORE
2437 return atomic_load_relaxed(&wgs->wgs_send_counter);
2438 #else
2439 uint64_t send_counter;
2440
2441 mutex_enter(&wgs->wgs_send_counter_lock);
2442 send_counter = wgs->wgs_send_counter;
2443 mutex_exit(&wgs->wgs_send_counter_lock);
2444
2445 return send_counter;
2446 #endif
2447 }
2448
2449 static uint64_t
2450 wg_session_inc_send_counter(struct wg_session *wgs)
2451 {
2452 #ifdef __HAVE_ATOMIC64_LOADSTORE
2453 return atomic_inc_64_nv(&wgs->wgs_send_counter) - 1;
2454 #else
2455 uint64_t send_counter;
2456
2457 mutex_enter(&wgs->wgs_send_counter_lock);
2458 send_counter = wgs->wgs_send_counter++;
2459 mutex_exit(&wgs->wgs_send_counter_lock);
2460
2461 return send_counter;
2462 #endif
2463 }
2464
2465 static void
2466 wg_clear_states(struct wg_session *wgs)
2467 {
2468
2469 KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
2470
2471 wgs->wgs_send_counter = 0;
2472 sliwin_reset(&wgs->wgs_recvwin->window);
2473
2474 #define wgs_clear(v) explicit_memset(wgs->wgs_##v, 0, sizeof(wgs->wgs_##v))
2475 wgs_clear(handshake_hash);
2476 wgs_clear(chaining_key);
2477 wgs_clear(ephemeral_key_pub);
2478 wgs_clear(ephemeral_key_priv);
2479 wgs_clear(ephemeral_key_peer);
2480 #undef wgs_clear
2481 }
2482
2483 static struct wg_session *
2484 wg_lookup_session_by_index(struct wg_softc *wg, const uint32_t index,
2485 struct psref *psref)
2486 {
2487 struct wg_session *wgs;
2488
2489 int s = pserialize_read_enter();
2490 wgs = thmap_get(wg->wg_sessions_byindex, &index, sizeof index);
2491 if (wgs != NULL) {
2492 uint32_t oindex __diagused =
2493 atomic_load_relaxed(&wgs->wgs_local_index);
2494 KASSERTMSG(index == oindex,
2495 "index=%"PRIx32" wgs->wgs_local_index=%"PRIx32,
2496 index, oindex);
2497 psref_acquire(psref, &wgs->wgs_psref, wg_psref_class);
2498 }
2499 pserialize_read_exit(s);
2500
2501 return wgs;
2502 }
2503
2504 static void
2505 wg_send_keepalive_msg(struct wg_peer *wgp, struct wg_session *wgs)
2506 {
2507 struct mbuf *m;
2508
2509 /*
2510 * [W] 6.5 Passive Keepalive
2511 * "A keepalive message is simply a transport data message with
2512 * a zero-length encapsulated encrypted inner-packet."
2513 */
2514 WG_TRACE("");
2515 m = m_gethdr(M_WAIT, MT_DATA);
2516 wg_send_data_msg(wgp, wgs, m);
2517 }
2518
2519 static bool
2520 wg_need_to_send_init_message(struct wg_session *wgs)
2521 {
2522 /*
2523 * [W] 6.2 Transport Message Limits
2524 * "if a peer is the initiator of a current secure session,
2525 * WireGuard will send a handshake initiation message to begin
2526 * a new secure session ... if after receiving a transport data
2527 * message, the current secure session is (REJECT-AFTER-TIME
2528 * KEEPALIVE-TIMEOUT REKEY-TIMEOUT) seconds old and it has
2529 * not yet acted upon this event."
2530 */
2531 return wgs->wgs_is_initiator &&
2532 atomic_load_relaxed(&wgs->wgs_time_last_data_sent) == 0 &&
2533 ((time_uptime32 -
2534 atomic_load_relaxed(&wgs->wgs_time_established)) >=
2535 (wg_reject_after_time - wg_keepalive_timeout -
2536 wg_rekey_timeout));
2537 }
2538
2539 static void
2540 wg_schedule_peer_task(struct wg_peer *wgp, unsigned int task)
2541 {
2542
2543 mutex_enter(wgp->wgp_intr_lock);
2544 WG_DLOG("tasks=%d, task=%d\n", wgp->wgp_tasks, task);
2545 if (wgp->wgp_tasks == 0)
2546 /*
2547 * XXX If the current CPU is already loaded -- e.g., if
2548 * there's already a bunch of handshakes queued up --
2549 * consider tossing this over to another CPU to
2550 * distribute the load.
2551 */
2552 workqueue_enqueue(wg_wq, &wgp->wgp_work, NULL);
2553 wgp->wgp_tasks |= task;
2554 mutex_exit(wgp->wgp_intr_lock);
2555 }
2556
2557 static void
2558 wg_change_endpoint(struct wg_peer *wgp, const struct sockaddr *new)
2559 {
2560 struct wg_sockaddr *wgsa_prev;
2561
2562 WG_TRACE("Changing endpoint");
2563
2564 memcpy(wgp->wgp_endpoint0, new, new->sa_len);
2565 wgsa_prev = wgp->wgp_endpoint;
2566 atomic_store_release(&wgp->wgp_endpoint, wgp->wgp_endpoint0);
2567 wgp->wgp_endpoint0 = wgsa_prev;
2568 atomic_store_release(&wgp->wgp_endpoint_available, true);
2569
2570 wg_schedule_peer_task(wgp, WGP_TASK_ENDPOINT_CHANGED);
2571 }
2572
2573 static bool
2574 wg_validate_inner_packet(const char *packet, size_t decrypted_len, int *af)
2575 {
2576 uint16_t packet_len;
2577 const struct ip *ip;
2578
2579 if (__predict_false(decrypted_len < sizeof(*ip))) {
2580 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2581 sizeof(*ip));
2582 return false;
2583 }
2584
2585 ip = (const struct ip *)packet;
2586 if (ip->ip_v == 4)
2587 *af = AF_INET;
2588 else if (ip->ip_v == 6)
2589 *af = AF_INET6;
2590 else {
2591 WG_DLOG("ip_v=%d\n", ip->ip_v);
2592 return false;
2593 }
2594
2595 WG_DLOG("af=%d\n", *af);
2596
2597 switch (*af) {
2598 #ifdef INET
2599 case AF_INET:
2600 packet_len = ntohs(ip->ip_len);
2601 break;
2602 #endif
2603 #ifdef INET6
2604 case AF_INET6: {
2605 const struct ip6_hdr *ip6;
2606
2607 if (__predict_false(decrypted_len < sizeof(*ip6))) {
2608 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2609 sizeof(*ip6));
2610 return false;
2611 }
2612
2613 ip6 = (const struct ip6_hdr *)packet;
2614 packet_len = sizeof(*ip6) + ntohs(ip6->ip6_plen);
2615 break;
2616 }
2617 #endif
2618 default:
2619 return false;
2620 }
2621
2622 if (packet_len > decrypted_len) {
2623 WG_DLOG("packet_len %u > decrypted_len %zu\n", packet_len,
2624 decrypted_len);
2625 return false;
2626 }
2627
2628 return true;
2629 }
2630
2631 static bool
2632 wg_validate_route(struct wg_softc *wg, struct wg_peer *wgp_expected,
2633 int af, char *packet)
2634 {
2635 struct sockaddr_storage ss;
2636 struct sockaddr *sa;
2637 struct psref psref;
2638 struct wg_peer *wgp;
2639 bool ok;
2640
2641 /*
2642 * II CRYPTOKEY ROUTING
2643 * "it will only accept it if its source IP resolves in the
2644 * table to the public key used in the secure session for
2645 * decrypting it."
2646 */
2647
2648 switch (af) {
2649 #ifdef INET
2650 case AF_INET: {
2651 const struct ip *ip = (const struct ip *)packet;
2652 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
2653 sockaddr_in_init(sin, &ip->ip_src, 0);
2654 sa = sintosa(sin);
2655 break;
2656 }
2657 #endif
2658 #ifdef INET6
2659 case AF_INET6: {
2660 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)packet;
2661 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
2662 sockaddr_in6_init(sin6, &ip6->ip6_src, 0, 0, 0);
2663 sa = sin6tosa(sin6);
2664 break;
2665 }
2666 #endif
2667 default:
2668 __USE(ss);
2669 return false;
2670 }
2671
2672 wgp = wg_pick_peer_by_sa(wg, sa, &psref);
2673 ok = (wgp == wgp_expected);
2674 if (wgp != NULL)
2675 wg_put_peer(wgp, &psref);
2676
2677 return ok;
2678 }
2679
2680 static void
2681 wg_session_dtor_timer(void *arg)
2682 {
2683 struct wg_peer *wgp = arg;
2684
2685 WG_TRACE("enter");
2686
2687 wg_schedule_session_dtor_timer(wgp);
2688 wg_schedule_peer_task(wgp, WGP_TASK_DESTROY_PREV_SESSION);
2689 }
2690
2691 static void
2692 wg_schedule_session_dtor_timer(struct wg_peer *wgp)
2693 {
2694
2695 /*
2696 * If the periodic session destructor is already pending to
2697 * handle the previous session, that's fine -- leave it in
2698 * place; it will be scheduled again.
2699 */
2700 if (callout_pending(&wgp->wgp_session_dtor_timer)) {
2701 WG_DLOG("session dtor already pending\n");
2702 return;
2703 }
2704
2705 WG_DLOG("scheduling session dtor in %u secs\n", wg_reject_after_time);
2706 callout_schedule(&wgp->wgp_session_dtor_timer,
2707 wg_reject_after_time*hz);
2708 }
2709
2710 static bool
2711 sockaddr_port_match(const struct sockaddr *sa1, const struct sockaddr *sa2)
2712 {
2713 if (sa1->sa_family != sa2->sa_family)
2714 return false;
2715
2716 switch (sa1->sa_family) {
2717 #ifdef INET
2718 case AF_INET:
2719 return satocsin(sa1)->sin_port == satocsin(sa2)->sin_port;
2720 #endif
2721 #ifdef INET6
2722 case AF_INET6:
2723 return satocsin6(sa1)->sin6_port == satocsin6(sa2)->sin6_port;
2724 #endif
2725 default:
2726 return false;
2727 }
2728 }
2729
2730 static void
2731 wg_update_endpoint_if_necessary(struct wg_peer *wgp,
2732 const struct sockaddr *src)
2733 {
2734 struct wg_sockaddr *wgsa;
2735 struct psref psref;
2736
2737 wgsa = wg_get_endpoint_sa(wgp, &psref);
2738
2739 #ifdef WG_DEBUG_LOG
2740 char oldaddr[128], newaddr[128];
2741 sockaddr_format(wgsatosa(wgsa), oldaddr, sizeof(oldaddr));
2742 sockaddr_format(src, newaddr, sizeof(newaddr));
2743 WG_DLOG("old=%s, new=%s\n", oldaddr, newaddr);
2744 #endif
2745
2746 /*
2747 * III: "Since the packet has authenticated correctly, the source IP of
2748 * the outer UDP/IP packet is used to update the endpoint for peer..."
2749 */
2750 if (__predict_false(sockaddr_cmp(src, wgsatosa(wgsa)) != 0 ||
2751 !sockaddr_port_match(src, wgsatosa(wgsa)))) {
2752 /* XXX We can't change the endpoint twice in a short period */
2753 if (atomic_swap_uint(&wgp->wgp_endpoint_changing, 1) == 0) {
2754 wg_change_endpoint(wgp, src);
2755 }
2756 }
2757
2758 wg_put_sa(wgp, wgsa, &psref);
2759 }
2760
2761 static void __noinline
2762 wg_handle_msg_data(struct wg_softc *wg, struct mbuf *m,
2763 const struct sockaddr *src)
2764 {
2765 struct wg_msg_data *wgmd;
2766 char *encrypted_buf = NULL, *decrypted_buf;
2767 size_t encrypted_len, decrypted_len;
2768 struct wg_session *wgs;
2769 struct wg_peer *wgp;
2770 int state;
2771 uint32_t age;
2772 size_t mlen;
2773 struct psref psref;
2774 int error, af;
2775 bool success, free_encrypted_buf = false, ok;
2776 struct mbuf *n;
2777
2778 KASSERT(m->m_len >= sizeof(struct wg_msg_data));
2779 wgmd = mtod(m, struct wg_msg_data *);
2780
2781 KASSERT(wgmd->wgmd_type == htole32(WG_MSG_TYPE_DATA));
2782 WG_TRACE("data");
2783
2784 /* Find the putative session, or drop. */
2785 wgs = wg_lookup_session_by_index(wg, wgmd->wgmd_receiver, &psref);
2786 if (wgs == NULL) {
2787 WG_TRACE("No session found");
2788 m_freem(m);
2789 return;
2790 }
2791
2792 /*
2793 * We are only ready to handle data when in INIT_PASSIVE,
2794 * ESTABLISHED, or DESTROYING. All transitions out of that
2795 * state dissociate the session index and drain psrefs.
2796 *
2797 * atomic_load_acquire matches atomic_store_release in either
2798 * wg_handle_msg_init or wg_handle_msg_resp. (The transition
2799 * INIT_PASSIVE to ESTABLISHED in wg_task_establish_session
2800 * doesn't make a difference for this rx path.)
2801 */
2802 state = atomic_load_acquire(&wgs->wgs_state);
2803 switch (state) {
2804 case WGS_STATE_UNKNOWN:
2805 case WGS_STATE_INIT_ACTIVE:
2806 WG_TRACE("not yet ready for data");
2807 goto out;
2808 case WGS_STATE_INIT_PASSIVE:
2809 case WGS_STATE_ESTABLISHED:
2810 case WGS_STATE_DESTROYING:
2811 break;
2812 }
2813
2814 /*
2815 * Reject if the session is too old.
2816 */
2817 age = time_uptime32 - atomic_load_relaxed(&wgs->wgs_time_established);
2818 if (__predict_false(age >= wg_reject_after_time)) {
2819 WG_DLOG("session %"PRIx32" too old, %"PRIu32" sec\n",
2820 wgmd->wgmd_receiver, age);
2821 goto out;
2822 }
2823
2824 /*
2825 * Get the peer, for rate-limited logs (XXX MPSAFE, dtrace) and
2826 * to update the endpoint if authentication succeeds.
2827 */
2828 wgp = wgs->wgs_peer;
2829
2830 /*
2831 * Reject outrageously wrong sequence numbers before doing any
2832 * crypto work or taking any locks.
2833 */
2834 error = sliwin_check_fast(&wgs->wgs_recvwin->window,
2835 le64toh(wgmd->wgmd_counter));
2836 if (error) {
2837 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2838 "%s: peer %s: out-of-window packet: %"PRIu64"\n",
2839 if_name(&wg->wg_if), wgp->wgp_name,
2840 le64toh(wgmd->wgmd_counter));
2841 goto out;
2842 }
2843
2844 /* Ensure the payload and authenticator are contiguous. */
2845 mlen = m_length(m);
2846 encrypted_len = mlen - sizeof(*wgmd);
2847 if (encrypted_len < WG_AUTHTAG_LEN) {
2848 WG_DLOG("Short encrypted_len: %zu\n", encrypted_len);
2849 goto out;
2850 }
2851 success = m_ensure_contig(&m, sizeof(*wgmd) + encrypted_len);
2852 if (success) {
2853 encrypted_buf = mtod(m, char *) + sizeof(*wgmd);
2854 } else {
2855 encrypted_buf = kmem_intr_alloc(encrypted_len, KM_NOSLEEP);
2856 if (encrypted_buf == NULL) {
2857 WG_DLOG("failed to allocate encrypted_buf\n");
2858 goto out;
2859 }
2860 m_copydata(m, sizeof(*wgmd), encrypted_len, encrypted_buf);
2861 free_encrypted_buf = true;
2862 }
2863 /* m_ensure_contig may change m regardless of its result */
2864 KASSERT(m->m_len >= sizeof(*wgmd));
2865 wgmd = mtod(m, struct wg_msg_data *);
2866
2867 /*
2868 * Get a buffer for the plaintext. Add WG_AUTHTAG_LEN to avoid
2869 * a zero-length buffer (XXX). Drop if plaintext is longer
2870 * than MCLBYTES (XXX).
2871 */
2872 decrypted_len = encrypted_len - WG_AUTHTAG_LEN;
2873 if (decrypted_len > MCLBYTES) {
2874 /* FIXME handle larger data than MCLBYTES */
2875 WG_DLOG("couldn't handle larger data than MCLBYTES\n");
2876 goto out;
2877 }
2878 n = wg_get_mbuf(0, decrypted_len + WG_AUTHTAG_LEN);
2879 if (n == NULL) {
2880 WG_DLOG("wg_get_mbuf failed\n");
2881 goto out;
2882 }
2883 decrypted_buf = mtod(n, char *);
2884
2885 /* Decrypt and verify the packet. */
2886 WG_DLOG("mlen=%zu, encrypted_len=%zu\n", mlen, encrypted_len);
2887 error = wg_algo_aead_dec(decrypted_buf,
2888 encrypted_len - WG_AUTHTAG_LEN /* can be 0 */,
2889 wgs->wgs_tkey_recv, le64toh(wgmd->wgmd_counter), encrypted_buf,
2890 encrypted_len, NULL, 0);
2891 if (error != 0) {
2892 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2893 "%s: peer %s: failed to wg_algo_aead_dec\n",
2894 if_name(&wg->wg_if), wgp->wgp_name);
2895 m_freem(n);
2896 goto out;
2897 }
2898 WG_DLOG("outsize=%u\n", (u_int)decrypted_len);
2899
2900 /* Packet is genuine. Reject it if a replay or just too old. */
2901 mutex_enter(&wgs->wgs_recvwin->lock);
2902 error = sliwin_update(&wgs->wgs_recvwin->window,
2903 le64toh(wgmd->wgmd_counter));
2904 mutex_exit(&wgs->wgs_recvwin->lock);
2905 if (error) {
2906 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2907 "%s: peer %s: replay or out-of-window packet: %"PRIu64"\n",
2908 if_name(&wg->wg_if), wgp->wgp_name,
2909 le64toh(wgmd->wgmd_counter));
2910 m_freem(n);
2911 goto out;
2912 }
2913
2914 /* We're done with m now; free it and chuck the pointers. */
2915 m_freem(m);
2916 m = NULL;
2917 wgmd = NULL;
2918
2919 /*
2920 * The packet is genuine. Update the peer's endpoint if the
2921 * source address changed.
2922 *
2923 * XXX How to prevent DoS by replaying genuine packets from the
2924 * wrong source address?
2925 */
2926 wg_update_endpoint_if_necessary(wgp, src);
2927
2928 /*
2929 * Validate the encapsulated packet header and get the address
2930 * family, or drop.
2931 */
2932 ok = wg_validate_inner_packet(decrypted_buf, decrypted_len, &af);
2933 if (!ok) {
2934 m_freem(n);
2935 goto update_state;
2936 }
2937
2938 /* Submit it into our network stack if routable. */
2939 ok = wg_validate_route(wg, wgp, af, decrypted_buf);
2940 if (ok) {
2941 wg->wg_ops->input(&wg->wg_if, n, af);
2942 } else {
2943 char addrstr[INET6_ADDRSTRLEN];
2944 memset(addrstr, 0, sizeof(addrstr));
2945 switch (af) {
2946 #ifdef INET
2947 case AF_INET: {
2948 const struct ip *ip = (const struct ip *)decrypted_buf;
2949 IN_PRINT(addrstr, &ip->ip_src);
2950 break;
2951 }
2952 #endif
2953 #ifdef INET6
2954 case AF_INET6: {
2955 const struct ip6_hdr *ip6 =
2956 (const struct ip6_hdr *)decrypted_buf;
2957 IN6_PRINT(addrstr, &ip6->ip6_src);
2958 break;
2959 }
2960 #endif
2961 default:
2962 panic("invalid af=%d", af);
2963 }
2964 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2965 "%s: peer %s: invalid source address (%s)\n",
2966 if_name(&wg->wg_if), wgp->wgp_name, addrstr);
2967 m_freem(n);
2968 /*
2969 * The inner address is invalid however the session is valid
2970 * so continue the session processing below.
2971 */
2972 }
2973 n = NULL;
2974
2975 update_state:
2976 /* Update the state machine if necessary. */
2977 if (__predict_false(state == WGS_STATE_INIT_PASSIVE)) {
2978 /*
2979 * We were waiting for the initiator to send their
2980 * first data transport message, and that has happened.
2981 * Schedule a task to establish this session.
2982 */
2983 wg_schedule_peer_task(wgp, WGP_TASK_ESTABLISH_SESSION);
2984 } else {
2985 if (__predict_false(wg_need_to_send_init_message(wgs))) {
2986 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
2987 }
2988 /*
2989 * [W] 6.5 Passive Keepalive
2990 * "If a peer has received a validly-authenticated transport
2991 * data message (section 5.4.6), but does not have any packets
2992 * itself to send back for KEEPALIVE-TIMEOUT seconds, it sends
2993 * a keepalive message."
2994 */
2995 const uint32_t now = time_uptime32;
2996 const uint32_t time_last_data_sent =
2997 atomic_load_relaxed(&wgs->wgs_time_last_data_sent);
2998 WG_DLOG("time_uptime32=%"PRIu32
2999 " wgs_time_last_data_sent=%"PRIu32"\n",
3000 now, time_last_data_sent);
3001 if ((now - time_last_data_sent) >= wg_keepalive_timeout) {
3002 WG_TRACE("Schedule sending keepalive message");
3003 /*
3004 * We can't send a keepalive message here to avoid
3005 * a deadlock; we already hold the solock of a socket
3006 * that is used to send the message.
3007 */
3008 wg_schedule_peer_task(wgp,
3009 WGP_TASK_SEND_KEEPALIVE_MESSAGE);
3010 }
3011 }
3012 out:
3013 wg_put_session(wgs, &psref);
3014 m_freem(m);
3015 if (free_encrypted_buf)
3016 kmem_intr_free(encrypted_buf, encrypted_len);
3017 }
3018
3019 static void __noinline
3020 wg_handle_msg_cookie(struct wg_softc *wg, const struct wg_msg_cookie *wgmc)
3021 {
3022 struct wg_session *wgs;
3023 struct wg_peer *wgp;
3024 struct psref psref;
3025 int error;
3026 uint8_t key[WG_HASH_LEN];
3027 uint8_t cookie[WG_COOKIE_LEN];
3028
3029 WG_TRACE("cookie msg received");
3030
3031 /* Find the putative session. */
3032 wgs = wg_lookup_session_by_index(wg, wgmc->wgmc_receiver, &psref);
3033 if (wgs == NULL) {
3034 WG_TRACE("No session found");
3035 return;
3036 }
3037
3038 /* Lock the peer so we can update the cookie state. */
3039 wgp = wgs->wgs_peer;
3040 mutex_enter(wgp->wgp_lock);
3041
3042 if (!wgp->wgp_last_sent_mac1_valid) {
3043 WG_TRACE("No valid mac1 sent (or expired)");
3044 goto out;
3045 }
3046
3047 /*
3048 * wgp_last_sent_mac1_valid is only set to true when we are
3049 * transitioning to INIT_ACTIVE or INIT_PASSIVE, and always
3050 * cleared on transition out of them.
3051 */
3052 KASSERTMSG((wgs->wgs_state == WGS_STATE_INIT_ACTIVE ||
3053 wgs->wgs_state == WGS_STATE_INIT_PASSIVE),
3054 "state=%d", wgs->wgs_state);
3055
3056 /* Decrypt the cookie and store it for later handshake retry. */
3057 wg_algo_mac_cookie(key, sizeof(key), wgp->wgp_pubkey,
3058 sizeof(wgp->wgp_pubkey));
3059 error = wg_algo_xaead_dec(cookie, sizeof(cookie), key,
3060 wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie),
3061 wgp->wgp_last_sent_mac1, sizeof(wgp->wgp_last_sent_mac1),
3062 wgmc->wgmc_salt);
3063 if (error != 0) {
3064 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3065 "%s: peer %s: wg_algo_aead_dec for cookie failed: "
3066 "error=%d\n", if_name(&wg->wg_if), wgp->wgp_name, error);
3067 goto out;
3068 }
3069 /*
3070 * [W] 6.6: Interaction with Cookie Reply System
3071 * "it should simply store the decrypted cookie value from the cookie
3072 * reply message, and wait for the expiration of the REKEY-TIMEOUT
3073 * timer for retrying a handshake initiation message."
3074 */
3075 wgp->wgp_latest_cookie_time = time_uptime;
3076 memcpy(wgp->wgp_latest_cookie, cookie, sizeof(wgp->wgp_latest_cookie));
3077 out:
3078 mutex_exit(wgp->wgp_lock);
3079 wg_put_session(wgs, &psref);
3080 }
3081
3082 static struct mbuf *
3083 wg_validate_msg_header(struct wg_softc *wg, struct mbuf *m)
3084 {
3085 struct wg_msg wgm;
3086 size_t mbuflen;
3087 size_t msglen;
3088
3089 /*
3090 * Get the mbuf chain length. It is already guaranteed, by
3091 * wg_overudp_cb, to be large enough for a struct wg_msg.
3092 */
3093 mbuflen = m_length(m);
3094 KASSERT(mbuflen >= sizeof(struct wg_msg));
3095
3096 /*
3097 * Copy the message header (32-bit message type) out -- we'll
3098 * worry about contiguity and alignment later.
3099 */
3100 m_copydata(m, 0, sizeof(wgm), &wgm);
3101 switch (le32toh(wgm.wgm_type)) {
3102 case WG_MSG_TYPE_INIT:
3103 msglen = sizeof(struct wg_msg_init);
3104 break;
3105 case WG_MSG_TYPE_RESP:
3106 msglen = sizeof(struct wg_msg_resp);
3107 break;
3108 case WG_MSG_TYPE_COOKIE:
3109 msglen = sizeof(struct wg_msg_cookie);
3110 break;
3111 case WG_MSG_TYPE_DATA:
3112 msglen = sizeof(struct wg_msg_data);
3113 break;
3114 default:
3115 WG_LOG_RATECHECK(&wg->wg_ppsratecheck, LOG_DEBUG,
3116 "%s: Unexpected msg type: %u\n", if_name(&wg->wg_if),
3117 le32toh(wgm.wgm_type));
3118 goto error;
3119 }
3120
3121 /* Verify the mbuf chain is long enough for this type of message. */
3122 if (__predict_false(mbuflen < msglen)) {
3123 WG_DLOG("Invalid msg size: mbuflen=%zu type=%u\n", mbuflen,
3124 le32toh(wgm.wgm_type));
3125 goto error;
3126 }
3127
3128 /* Make the message header contiguous if necessary. */
3129 if (__predict_false(m->m_len < msglen)) {
3130 m = m_pullup(m, msglen);
3131 if (m == NULL)
3132 return NULL;
3133 }
3134
3135 return m;
3136
3137 error:
3138 m_freem(m);
3139 return NULL;
3140 }
3141
3142 static void
3143 wg_handle_packet(struct wg_softc *wg, struct mbuf *m,
3144 const struct sockaddr *src)
3145 {
3146 struct wg_msg *wgm;
3147
3148 KASSERT(curlwp->l_pflag & LP_BOUND);
3149
3150 m = wg_validate_msg_header(wg, m);
3151 if (__predict_false(m == NULL))
3152 return;
3153
3154 KASSERT(m->m_len >= sizeof(struct wg_msg));
3155 wgm = mtod(m, struct wg_msg *);
3156 switch (le32toh(wgm->wgm_type)) {
3157 case WG_MSG_TYPE_INIT:
3158 wg_handle_msg_init(wg, (struct wg_msg_init *)wgm, src);
3159 break;
3160 case WG_MSG_TYPE_RESP:
3161 wg_handle_msg_resp(wg, (struct wg_msg_resp *)wgm, src);
3162 break;
3163 case WG_MSG_TYPE_COOKIE:
3164 wg_handle_msg_cookie(wg, (struct wg_msg_cookie *)wgm);
3165 break;
3166 case WG_MSG_TYPE_DATA:
3167 wg_handle_msg_data(wg, m, src);
3168 /* wg_handle_msg_data frees m for us */
3169 return;
3170 default:
3171 panic("invalid message type: %d", le32toh(wgm->wgm_type));
3172 }
3173
3174 m_freem(m);
3175 }
3176
3177 static void
3178 wg_receive_packets(struct wg_softc *wg, const int af)
3179 {
3180
3181 for (;;) {
3182 int error, flags;
3183 struct socket *so;
3184 struct mbuf *m = NULL;
3185 struct uio dummy_uio;
3186 struct mbuf *paddr = NULL;
3187 struct sockaddr *src;
3188
3189 so = wg_get_so_by_af(wg, af);
3190 flags = MSG_DONTWAIT;
3191 dummy_uio.uio_resid = 1000000000;
3192
3193 error = so->so_receive(so, &paddr, &dummy_uio, &m, NULL,
3194 &flags);
3195 if (error || m == NULL) {
3196 //if (error == EWOULDBLOCK)
3197 return;
3198 }
3199
3200 KASSERT(paddr != NULL);
3201 KASSERT(paddr->m_len >= sizeof(struct sockaddr));
3202 src = mtod(paddr, struct sockaddr *);
3203
3204 wg_handle_packet(wg, m, src);
3205 }
3206 }
3207
3208 static void
3209 wg_get_peer(struct wg_peer *wgp, struct psref *psref)
3210 {
3211
3212 psref_acquire(psref, &wgp->wgp_psref, wg_psref_class);
3213 }
3214
3215 static void
3216 wg_put_peer(struct wg_peer *wgp, struct psref *psref)
3217 {
3218
3219 psref_release(psref, &wgp->wgp_psref, wg_psref_class);
3220 }
3221
3222 static void
3223 wg_task_send_init_message(struct wg_softc *wg, struct wg_peer *wgp)
3224 {
3225 struct wg_session *wgs;
3226
3227 WG_TRACE("WGP_TASK_SEND_INIT_MESSAGE");
3228
3229 KASSERT(mutex_owned(wgp->wgp_lock));
3230
3231 if (!atomic_load_acquire(&wgp->wgp_endpoint_available)) {
3232 WGLOG(LOG_DEBUG, "%s: No endpoint available\n",
3233 if_name(&wg->wg_if));
3234 /* XXX should do something? */
3235 return;
3236 }
3237
3238 /*
3239 * If we already have an established session, there's no need
3240 * to initiate a new one -- unless the rekey-after-time or
3241 * rekey-after-messages limits have passed.
3242 */
3243 wgs = wgp->wgp_session_stable;
3244 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3245 !atomic_load_relaxed(&wgs->wgs_force_rekey))
3246 return;
3247
3248 /*
3249 * Ensure we're initiating a new session. If the unstable
3250 * session is already INIT_ACTIVE or INIT_PASSIVE, this does
3251 * nothing.
3252 */
3253 wg_send_handshake_msg_init(wg, wgp);
3254 }
3255
3256 static void
3257 wg_task_retry_handshake(struct wg_softc *wg, struct wg_peer *wgp)
3258 {
3259 struct wg_session *wgs;
3260
3261 WG_TRACE("WGP_TASK_RETRY_HANDSHAKE");
3262
3263 KASSERT(mutex_owned(wgp->wgp_lock));
3264 KASSERT(wgp->wgp_handshake_start_time != 0);
3265
3266 wgs = wgp->wgp_session_unstable;
3267 if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE)
3268 return;
3269
3270 /*
3271 * XXX no real need to assign a new index here, but we do need
3272 * to transition to UNKNOWN temporarily
3273 */
3274 wg_put_session_index(wg, wgs);
3275
3276 /* [W] 6.4 Handshake Initiation Retransmission */
3277 if ((time_uptime - wgp->wgp_handshake_start_time) >
3278 wg_rekey_attempt_time) {
3279 /* Give up handshaking */
3280 wgp->wgp_handshake_start_time = 0;
3281 WG_TRACE("give up");
3282
3283 /*
3284 * If a new data packet comes, handshaking will be retried
3285 * and a new session would be established at that time,
3286 * however we don't want to send pending packets then.
3287 */
3288 wg_purge_pending_packets(wgp);
3289 return;
3290 }
3291
3292 wg_task_send_init_message(wg, wgp);
3293 }
3294
3295 static void
3296 wg_task_establish_session(struct wg_softc *wg, struct wg_peer *wgp)
3297 {
3298 struct wg_session *wgs, *wgs_prev;
3299 struct mbuf *m;
3300
3301 KASSERT(mutex_owned(wgp->wgp_lock));
3302
3303 wgs = wgp->wgp_session_unstable;
3304 if (wgs->wgs_state != WGS_STATE_INIT_PASSIVE)
3305 /* XXX Can this happen? */
3306 return;
3307
3308 wgs->wgs_time_last_data_sent = 0;
3309 wgs->wgs_is_initiator = false;
3310
3311 /*
3312 * Session was already ready to receive data. Transition from
3313 * INIT_PASSIVE to ESTABLISHED just so we can swap the
3314 * sessions.
3315 *
3316 * atomic_store_relaxed because this doesn't affect the data rx
3317 * path, wg_handle_msg_data -- changing from INIT_PASSIVE to
3318 * ESTABLISHED makes no difference to the data rx path, and the
3319 * transition to INIT_PASSIVE with store-release already
3320 * published the state needed by the data rx path.
3321 */
3322 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_ESTABLISHED\n",
3323 wgs->wgs_local_index, wgs->wgs_remote_index);
3324 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
3325 WG_TRACE("WGS_STATE_ESTABLISHED");
3326
3327 /*
3328 * Session is ready to send data too now that we have received
3329 * the peer initiator's first data packet.
3330 *
3331 * Swap the sessions to publish the new one as the stable
3332 * session for the data tx path, wg_output.
3333 */
3334 wg_swap_sessions(wgp);
3335 KASSERT(wgs == wgp->wgp_session_stable);
3336 wgs_prev = wgp->wgp_session_unstable;
3337 getnanotime(&wgp->wgp_last_handshake_time);
3338 wgp->wgp_handshake_start_time = 0;
3339 wgp->wgp_last_sent_mac1_valid = false;
3340 wgp->wgp_last_sent_cookie_valid = false;
3341
3342 /* If we had a data packet queued up, send it. */
3343 if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
3344 kpreempt_disable();
3345 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
3346 M_SETCTX(m, wgp);
3347 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
3348 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
3349 if_name(&wg->wg_if));
3350 m_freem(m);
3351 }
3352 kpreempt_enable();
3353 }
3354
3355 if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
3356 /*
3357 * Transition ESTABLISHED->DESTROYING. The session
3358 * will remain usable for the data rx path to process
3359 * packets still in flight to us, but we won't use it
3360 * for data tx.
3361 */
3362 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
3363 " -> WGS_STATE_DESTROYING\n",
3364 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
3365 atomic_store_relaxed(&wgs_prev->wgs_state,
3366 WGS_STATE_DESTROYING);
3367 } else {
3368 KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
3369 "state=%d", wgs_prev->wgs_state);
3370 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
3371 " -> WGS_STATE_UNKNOWN\n",
3372 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
3373 wgs_prev->wgs_local_index = 0; /* paranoia */
3374 wgs_prev->wgs_remote_index = 0; /* paranoia */
3375 wg_clear_states(wgs_prev); /* paranoia */
3376 wgs_prev->wgs_state = WGS_STATE_UNKNOWN;
3377 }
3378 }
3379
3380 static void
3381 wg_task_endpoint_changed(struct wg_softc *wg, struct wg_peer *wgp)
3382 {
3383
3384 WG_TRACE("WGP_TASK_ENDPOINT_CHANGED");
3385
3386 KASSERT(mutex_owned(wgp->wgp_lock));
3387
3388 if (atomic_load_relaxed(&wgp->wgp_endpoint_changing)) {
3389 pserialize_perform(wgp->wgp_psz);
3390 mutex_exit(wgp->wgp_lock);
3391 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref,
3392 wg_psref_class);
3393 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref,
3394 wg_psref_class);
3395 mutex_enter(wgp->wgp_lock);
3396 atomic_store_release(&wgp->wgp_endpoint_changing, 0);
3397 }
3398 }
3399
3400 static void
3401 wg_task_send_keepalive_message(struct wg_softc *wg, struct wg_peer *wgp)
3402 {
3403 struct wg_session *wgs;
3404
3405 WG_TRACE("WGP_TASK_SEND_KEEPALIVE_MESSAGE");
3406
3407 KASSERT(mutex_owned(wgp->wgp_lock));
3408
3409 wgs = wgp->wgp_session_stable;
3410 if (wgs->wgs_state != WGS_STATE_ESTABLISHED)
3411 return;
3412
3413 wg_send_keepalive_msg(wgp, wgs);
3414 }
3415
3416 static void
3417 wg_task_destroy_prev_session(struct wg_softc *wg, struct wg_peer *wgp)
3418 {
3419 struct wg_session *wgs;
3420 uint32_t age;
3421
3422 WG_TRACE("WGP_TASK_DESTROY_PREV_SESSION");
3423
3424 KASSERT(mutex_owned(wgp->wgp_lock));
3425
3426 /*
3427 * If theres's any previous unstable session, i.e., one that
3428 * was ESTABLISHED and is now DESTROYING, older than
3429 * reject-after-time, destroy it. Upcoming sessions are still
3430 * in INIT_ACTIVE or INIT_PASSIVE -- we don't touch those here.
3431 *
3432 * No atomic for access to wgs_time_established because it is
3433 * only updated under wgp_lock.
3434 */
3435 wgs = wgp->wgp_session_unstable;
3436 KASSERT(wgs->wgs_state != WGS_STATE_ESTABLISHED);
3437 if (wgs->wgs_state == WGS_STATE_DESTROYING &&
3438 ((age = (time_uptime32 - wgs->wgs_time_established)) >=
3439 wg_reject_after_time)) {
3440 WG_DLOG("destroying past session %"PRIu32" sec old\n", age);
3441 wg_put_session_index(wg, wgs);
3442 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
3443 wgs->wgs_state);
3444 }
3445
3446 /*
3447 * If theres's any ESTABLISHED stable session older than
3448 * reject-after-time, destroy it. (The stable session can also
3449 * be in UNKNOWN state -- nothing to do in that case)
3450 */
3451 wgs = wgp->wgp_session_stable;
3452 KASSERT(wgs->wgs_state != WGS_STATE_INIT_ACTIVE);
3453 KASSERT(wgs->wgs_state != WGS_STATE_INIT_PASSIVE);
3454 KASSERT(wgs->wgs_state != WGS_STATE_DESTROYING);
3455 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3456 ((age = (time_uptime32 - wgs->wgs_time_established)) >=
3457 wg_reject_after_time)) {
3458 WG_DLOG("destroying current session %"PRIu32" sec old\n", age);
3459 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_DESTROYING);
3460 wg_put_session_index(wg, wgs);
3461 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
3462 wgs->wgs_state);
3463 }
3464
3465 /*
3466 * If there's no sessions left, no need to have the timer run
3467 * until the next time around -- halt it.
3468 *
3469 * It is only ever scheduled with wgp_lock held or in the
3470 * callout itself, and callout_halt prevents rescheudling
3471 * itself, so this never races with rescheduling.
3472 */
3473 if (wgp->wgp_session_unstable->wgs_state == WGS_STATE_UNKNOWN &&
3474 wgp->wgp_session_stable->wgs_state == WGS_STATE_UNKNOWN)
3475 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
3476 }
3477
3478 static void
3479 wg_peer_work(struct work *wk, void *cookie)
3480 {
3481 struct wg_peer *wgp = container_of(wk, struct wg_peer, wgp_work);
3482 struct wg_softc *wg = wgp->wgp_sc;
3483 unsigned int tasks;
3484
3485 mutex_enter(wgp->wgp_intr_lock);
3486 while ((tasks = wgp->wgp_tasks) != 0) {
3487 wgp->wgp_tasks = 0;
3488 mutex_exit(wgp->wgp_intr_lock);
3489
3490 mutex_enter(wgp->wgp_lock);
3491 if (ISSET(tasks, WGP_TASK_SEND_INIT_MESSAGE))
3492 wg_task_send_init_message(wg, wgp);
3493 if (ISSET(tasks, WGP_TASK_RETRY_HANDSHAKE))
3494 wg_task_retry_handshake(wg, wgp);
3495 if (ISSET(tasks, WGP_TASK_ESTABLISH_SESSION))
3496 wg_task_establish_session(wg, wgp);
3497 if (ISSET(tasks, WGP_TASK_ENDPOINT_CHANGED))
3498 wg_task_endpoint_changed(wg, wgp);
3499 if (ISSET(tasks, WGP_TASK_SEND_KEEPALIVE_MESSAGE))
3500 wg_task_send_keepalive_message(wg, wgp);
3501 if (ISSET(tasks, WGP_TASK_DESTROY_PREV_SESSION))
3502 wg_task_destroy_prev_session(wg, wgp);
3503 mutex_exit(wgp->wgp_lock);
3504
3505 mutex_enter(wgp->wgp_intr_lock);
3506 }
3507 mutex_exit(wgp->wgp_intr_lock);
3508 }
3509
3510 static void
3511 wg_job(struct threadpool_job *job)
3512 {
3513 struct wg_softc *wg = container_of(job, struct wg_softc, wg_job);
3514 int bound, upcalls;
3515
3516 mutex_enter(wg->wg_intr_lock);
3517 while ((upcalls = wg->wg_upcalls) != 0) {
3518 wg->wg_upcalls = 0;
3519 mutex_exit(wg->wg_intr_lock);
3520 bound = curlwp_bind();
3521 if (ISSET(upcalls, WG_UPCALL_INET))
3522 wg_receive_packets(wg, AF_INET);
3523 if (ISSET(upcalls, WG_UPCALL_INET6))
3524 wg_receive_packets(wg, AF_INET6);
3525 curlwp_bindx(bound);
3526 mutex_enter(wg->wg_intr_lock);
3527 }
3528 threadpool_job_done(job);
3529 mutex_exit(wg->wg_intr_lock);
3530 }
3531
3532 static int
3533 wg_bind_port(struct wg_softc *wg, const uint16_t port)
3534 {
3535 int error = 0;
3536 uint16_t old_port = wg->wg_listen_port;
3537
3538 if (port != 0 && old_port == port)
3539 return 0;
3540
3541 #ifdef INET
3542 struct sockaddr_in _sin, *sin = &_sin;
3543 sin->sin_len = sizeof(*sin);
3544 sin->sin_family = AF_INET;
3545 sin->sin_addr.s_addr = INADDR_ANY;
3546 sin->sin_port = htons(port);
3547
3548 error = sobind(wg->wg_so4, sintosa(sin), curlwp);
3549 if (error)
3550 return error;
3551 #endif
3552
3553 #ifdef INET6
3554 struct sockaddr_in6 _sin6, *sin6 = &_sin6;
3555 sin6->sin6_len = sizeof(*sin6);
3556 sin6->sin6_family = AF_INET6;
3557 sin6->sin6_addr = in6addr_any;
3558 sin6->sin6_port = htons(port);
3559
3560 error = sobind(wg->wg_so6, sin6tosa(sin6), curlwp);
3561 if (error)
3562 return error;
3563 #endif
3564
3565 wg->wg_listen_port = port;
3566
3567 return error;
3568 }
3569
3570 static void
3571 wg_so_upcall(struct socket *so, void *cookie, int events, int waitflag)
3572 {
3573 struct wg_softc *wg = cookie;
3574 int reason;
3575
3576 reason = (so->so_proto->pr_domain->dom_family == AF_INET) ?
3577 WG_UPCALL_INET :
3578 WG_UPCALL_INET6;
3579
3580 mutex_enter(wg->wg_intr_lock);
3581 wg->wg_upcalls |= reason;
3582 threadpool_schedule_job(wg->wg_threadpool, &wg->wg_job);
3583 mutex_exit(wg->wg_intr_lock);
3584 }
3585
3586 static int
3587 wg_overudp_cb(struct mbuf **mp, int offset, struct socket *so,
3588 struct sockaddr *src, void *arg)
3589 {
3590 struct wg_softc *wg = arg;
3591 struct wg_msg wgm;
3592 struct mbuf *m = *mp;
3593
3594 WG_TRACE("enter");
3595
3596 /* Verify the mbuf chain is long enough to have a wg msg header. */
3597 KASSERT(offset <= m_length(m));
3598 if (__predict_false(m_length(m) - offset < sizeof(struct wg_msg))) {
3599 /* drop on the floor */
3600 m_freem(m);
3601 return -1;
3602 }
3603
3604 /*
3605 * Copy the message header (32-bit message type) out -- we'll
3606 * worry about contiguity and alignment later.
3607 */
3608 m_copydata(m, offset, sizeof(struct wg_msg), &wgm);
3609 WG_DLOG("type=%d\n", le32toh(wgm.wgm_type));
3610
3611 /*
3612 * Handle DATA packets promptly as they arrive, if they are in
3613 * an active session. Other packets may require expensive
3614 * public-key crypto and are not as sensitive to latency, so
3615 * defer them to the worker thread.
3616 */
3617 switch (le32toh(wgm.wgm_type)) {
3618 case WG_MSG_TYPE_DATA:
3619 /* handle immediately */
3620 m_adj(m, offset);
3621 if (__predict_false(m->m_len < sizeof(struct wg_msg_data))) {
3622 m = m_pullup(m, sizeof(struct wg_msg_data));
3623 if (m == NULL)
3624 return -1;
3625 }
3626 wg_handle_msg_data(wg, m, src);
3627 *mp = NULL;
3628 return 1;
3629 case WG_MSG_TYPE_INIT:
3630 case WG_MSG_TYPE_RESP:
3631 case WG_MSG_TYPE_COOKIE:
3632 /* pass through to so_receive in wg_receive_packets */
3633 return 0;
3634 default:
3635 /* drop on the floor */
3636 m_freem(m);
3637 return -1;
3638 }
3639 }
3640
3641 static int
3642 wg_socreate(struct wg_softc *wg, int af, struct socket **sop)
3643 {
3644 int error;
3645 struct socket *so;
3646
3647 error = socreate(af, &so, SOCK_DGRAM, 0, curlwp, NULL);
3648 if (error != 0)
3649 return error;
3650
3651 solock(so);
3652 so->so_upcallarg = wg;
3653 so->so_upcall = wg_so_upcall;
3654 so->so_rcv.sb_flags |= SB_UPCALL;
3655 inpcb_register_overudp_cb(sotoinpcb(so), wg_overudp_cb, wg);
3656 sounlock(so);
3657
3658 *sop = so;
3659
3660 return 0;
3661 }
3662
3663 static bool
3664 wg_session_hit_limits(struct wg_session *wgs)
3665 {
3666 uint32_t time_established =
3667 atomic_load_relaxed(&wgs->wgs_time_established);
3668
3669 /*
3670 * [W] 6.2: Transport Message Limits
3671 * "After REJECT-AFTER-MESSAGES transport data messages or after the
3672 * current secure session is REJECT-AFTER-TIME seconds old, whichever
3673 * comes first, WireGuard will refuse to send or receive any more
3674 * transport data messages using the current secure session, ..."
3675 */
3676 KASSERT(time_established != 0 || time_uptime > UINT32_MAX);
3677 if ((time_uptime32 - time_established) > wg_reject_after_time) {
3678 WG_DLOG("The session hits REJECT_AFTER_TIME\n");
3679 return true;
3680 } else if (wg_session_get_send_counter(wgs) >
3681 wg_reject_after_messages) {
3682 WG_DLOG("The session hits REJECT_AFTER_MESSAGES\n");
3683 return true;
3684 }
3685
3686 return false;
3687 }
3688
3689 static void
3690 wgintr(void *cookie)
3691 {
3692 struct wg_peer *wgp;
3693 struct wg_session *wgs;
3694 struct mbuf *m;
3695 struct psref psref;
3696
3697 while ((m = pktq_dequeue(wg_pktq)) != NULL) {
3698 wgp = M_GETCTX(m, struct wg_peer *);
3699 if ((wgs = wg_get_stable_session(wgp, &psref)) == NULL) {
3700 WG_TRACE("no stable session");
3701 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3702 goto next0;
3703 }
3704 if (__predict_false(wg_session_hit_limits(wgs))) {
3705 WG_TRACE("stable session hit limits");
3706 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3707 goto next1;
3708 }
3709 wg_send_data_msg(wgp, wgs, m);
3710 m = NULL; /* consumed */
3711 next1: wg_put_session(wgs, &psref);
3712 next0: m_freem(m);
3713 /* XXX Yield to avoid userland starvation? */
3714 }
3715 }
3716
3717 static void
3718 wg_purge_pending_packets(struct wg_peer *wgp)
3719 {
3720 struct mbuf *m;
3721
3722 m = atomic_swap_ptr(&wgp->wgp_pending, NULL);
3723 m_freem(m);
3724 #ifdef ALTQ
3725 wg_start(&wgp->wgp_sc->wg_if);
3726 #endif
3727 pktq_barrier(wg_pktq);
3728 }
3729
3730 static void
3731 wg_handshake_timeout_timer(void *arg)
3732 {
3733 struct wg_peer *wgp = arg;
3734
3735 WG_TRACE("enter");
3736
3737 wg_schedule_peer_task(wgp, WGP_TASK_RETRY_HANDSHAKE);
3738 }
3739
3740 static struct wg_peer *
3741 wg_alloc_peer(struct wg_softc *wg)
3742 {
3743 struct wg_peer *wgp;
3744
3745 wgp = kmem_zalloc(sizeof(*wgp), KM_SLEEP);
3746
3747 wgp->wgp_sc = wg;
3748 callout_init(&wgp->wgp_handshake_timeout_timer, CALLOUT_MPSAFE);
3749 callout_setfunc(&wgp->wgp_handshake_timeout_timer,
3750 wg_handshake_timeout_timer, wgp);
3751 callout_init(&wgp->wgp_session_dtor_timer, CALLOUT_MPSAFE);
3752 callout_setfunc(&wgp->wgp_session_dtor_timer,
3753 wg_session_dtor_timer, wgp);
3754 PSLIST_ENTRY_INIT(wgp, wgp_peerlist_entry);
3755 wgp->wgp_endpoint_changing = false;
3756 wgp->wgp_endpoint_available = false;
3757 wgp->wgp_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
3758 wgp->wgp_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
3759 wgp->wgp_psz = pserialize_create();
3760 psref_target_init(&wgp->wgp_psref, wg_psref_class);
3761
3762 wgp->wgp_endpoint = kmem_zalloc(sizeof(*wgp->wgp_endpoint), KM_SLEEP);
3763 wgp->wgp_endpoint0 = kmem_zalloc(sizeof(*wgp->wgp_endpoint0), KM_SLEEP);
3764 psref_target_init(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
3765 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
3766
3767 struct wg_session *wgs;
3768 wgp->wgp_session_stable =
3769 kmem_zalloc(sizeof(*wgp->wgp_session_stable), KM_SLEEP);
3770 wgp->wgp_session_unstable =
3771 kmem_zalloc(sizeof(*wgp->wgp_session_unstable), KM_SLEEP);
3772 wgs = wgp->wgp_session_stable;
3773 wgs->wgs_peer = wgp;
3774 wgs->wgs_state = WGS_STATE_UNKNOWN;
3775 psref_target_init(&wgs->wgs_psref, wg_psref_class);
3776 #ifndef __HAVE_ATOMIC64_LOADSTORE
3777 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
3778 #endif
3779 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
3780 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
3781
3782 wgs = wgp->wgp_session_unstable;
3783 wgs->wgs_peer = wgp;
3784 wgs->wgs_state = WGS_STATE_UNKNOWN;
3785 psref_target_init(&wgs->wgs_psref, wg_psref_class);
3786 #ifndef __HAVE_ATOMIC64_LOADSTORE
3787 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
3788 #endif
3789 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
3790 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
3791
3792 return wgp;
3793 }
3794
3795 static void
3796 wg_destroy_peer(struct wg_peer *wgp)
3797 {
3798 struct wg_session *wgs;
3799 struct wg_softc *wg = wgp->wgp_sc;
3800
3801 /* Prevent new packets from this peer on any source address. */
3802 rw_enter(wg->wg_rwlock, RW_WRITER);
3803 for (int i = 0; i < wgp->wgp_n_allowedips; i++) {
3804 struct wg_allowedip *wga = &wgp->wgp_allowedips[i];
3805 struct radix_node_head *rnh = wg_rnh(wg, wga->wga_family);
3806 struct radix_node *rn;
3807
3808 KASSERT(rnh != NULL);
3809 rn = rnh->rnh_deladdr(&wga->wga_sa_addr,
3810 &wga->wga_sa_mask, rnh);
3811 if (rn == NULL) {
3812 char addrstr[128];
3813 sockaddr_format(&wga->wga_sa_addr, addrstr,
3814 sizeof(addrstr));
3815 WGLOG(LOG_WARNING, "%s: Couldn't delete %s",
3816 if_name(&wg->wg_if), addrstr);
3817 }
3818 }
3819 rw_exit(wg->wg_rwlock);
3820
3821 /* Purge pending packets. */
3822 wg_purge_pending_packets(wgp);
3823
3824 /* Halt all packet processing and timeouts. */
3825 callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
3826 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
3827
3828 /* Wait for any queued work to complete. */
3829 workqueue_wait(wg_wq, &wgp->wgp_work);
3830
3831 wgs = wgp->wgp_session_unstable;
3832 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
3833 mutex_enter(wgp->wgp_lock);
3834 wg_destroy_session(wg, wgs);
3835 mutex_exit(wgp->wgp_lock);
3836 }
3837 mutex_destroy(&wgs->wgs_recvwin->lock);
3838 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
3839 #ifndef __HAVE_ATOMIC64_LOADSTORE
3840 mutex_destroy(&wgs->wgs_send_counter_lock);
3841 #endif
3842 kmem_free(wgs, sizeof(*wgs));
3843
3844 wgs = wgp->wgp_session_stable;
3845 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
3846 mutex_enter(wgp->wgp_lock);
3847 wg_destroy_session(wg, wgs);
3848 mutex_exit(wgp->wgp_lock);
3849 }
3850 mutex_destroy(&wgs->wgs_recvwin->lock);
3851 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
3852 #ifndef __HAVE_ATOMIC64_LOADSTORE
3853 mutex_destroy(&wgs->wgs_send_counter_lock);
3854 #endif
3855 kmem_free(wgs, sizeof(*wgs));
3856
3857 psref_target_destroy(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
3858 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
3859 kmem_free(wgp->wgp_endpoint, sizeof(*wgp->wgp_endpoint));
3860 kmem_free(wgp->wgp_endpoint0, sizeof(*wgp->wgp_endpoint0));
3861
3862 pserialize_destroy(wgp->wgp_psz);
3863 mutex_obj_free(wgp->wgp_intr_lock);
3864 mutex_obj_free(wgp->wgp_lock);
3865
3866 kmem_free(wgp, sizeof(*wgp));
3867 }
3868
3869 static void
3870 wg_destroy_all_peers(struct wg_softc *wg)
3871 {
3872 struct wg_peer *wgp, *wgp0 __diagused;
3873 void *garbage_byname, *garbage_bypubkey;
3874
3875 restart:
3876 garbage_byname = garbage_bypubkey = NULL;
3877 mutex_enter(wg->wg_lock);
3878 WG_PEER_WRITER_FOREACH(wgp, wg) {
3879 if (wgp->wgp_name[0]) {
3880 wgp0 = thmap_del(wg->wg_peers_byname, wgp->wgp_name,
3881 strlen(wgp->wgp_name));
3882 KASSERT(wgp0 == wgp);
3883 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
3884 }
3885 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
3886 sizeof(wgp->wgp_pubkey));
3887 KASSERT(wgp0 == wgp);
3888 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
3889 WG_PEER_WRITER_REMOVE(wgp);
3890 wg->wg_npeers--;
3891 mutex_enter(wgp->wgp_lock);
3892 pserialize_perform(wgp->wgp_psz);
3893 mutex_exit(wgp->wgp_lock);
3894 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
3895 break;
3896 }
3897 mutex_exit(wg->wg_lock);
3898
3899 if (wgp == NULL)
3900 return;
3901
3902 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
3903
3904 wg_destroy_peer(wgp);
3905 thmap_gc(wg->wg_peers_byname, garbage_byname);
3906 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
3907
3908 goto restart;
3909 }
3910
3911 static int
3912 wg_destroy_peer_name(struct wg_softc *wg, const char *name)
3913 {
3914 struct wg_peer *wgp, *wgp0 __diagused;
3915 void *garbage_byname, *garbage_bypubkey;
3916
3917 mutex_enter(wg->wg_lock);
3918 wgp = thmap_del(wg->wg_peers_byname, name, strlen(name));
3919 if (wgp != NULL) {
3920 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
3921 sizeof(wgp->wgp_pubkey));
3922 KASSERT(wgp0 == wgp);
3923 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
3924 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
3925 WG_PEER_WRITER_REMOVE(wgp);
3926 wg->wg_npeers--;
3927 if (wg->wg_npeers == 0)
3928 if_link_state_change(&wg->wg_if, LINK_STATE_DOWN);
3929 mutex_enter(wgp->wgp_lock);
3930 pserialize_perform(wgp->wgp_psz);
3931 mutex_exit(wgp->wgp_lock);
3932 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
3933 }
3934 mutex_exit(wg->wg_lock);
3935
3936 if (wgp == NULL)
3937 return ENOENT;
3938
3939 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
3940
3941 wg_destroy_peer(wgp);
3942 thmap_gc(wg->wg_peers_byname, garbage_byname);
3943 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
3944
3945 return 0;
3946 }
3947
3948 static int
3949 wg_if_attach(struct wg_softc *wg)
3950 {
3951
3952 wg->wg_if.if_addrlen = 0;
3953 wg->wg_if.if_mtu = WG_MTU;
3954 wg->wg_if.if_flags = IFF_MULTICAST;
3955 wg->wg_if.if_extflags = IFEF_MPSAFE;
3956 wg->wg_if.if_ioctl = wg_ioctl;
3957 wg->wg_if.if_output = wg_output;
3958 wg->wg_if.if_init = wg_init;
3959 #ifdef ALTQ
3960 wg->wg_if.if_start = wg_start;
3961 #endif
3962 wg->wg_if.if_stop = wg_stop;
3963 wg->wg_if.if_type = IFT_OTHER;
3964 wg->wg_if.if_dlt = DLT_NULL;
3965 wg->wg_if.if_softc = wg;
3966 #ifdef ALTQ
3967 IFQ_SET_READY(&wg->wg_if.if_snd);
3968 #endif
3969 if_initialize(&wg->wg_if);
3970
3971 wg->wg_if.if_link_state = LINK_STATE_DOWN;
3972 if_alloc_sadl(&wg->wg_if);
3973 if_register(&wg->wg_if);
3974
3975 bpf_attach(&wg->wg_if, DLT_NULL, sizeof(uint32_t));
3976
3977 return 0;
3978 }
3979
3980 static void
3981 wg_if_detach(struct wg_softc *wg)
3982 {
3983 struct ifnet *ifp = &wg->wg_if;
3984
3985 bpf_detach(ifp);
3986 if_detach(ifp);
3987 }
3988
3989 static int
3990 wg_clone_create(struct if_clone *ifc, int unit)
3991 {
3992 struct wg_softc *wg;
3993 int error;
3994
3995 wg_guarantee_initialized();
3996
3997 error = wg_count_inc();
3998 if (error)
3999 return error;
4000
4001 wg = kmem_zalloc(sizeof(*wg), KM_SLEEP);
4002
4003 if_initname(&wg->wg_if, ifc->ifc_name, unit);
4004
4005 PSLIST_INIT(&wg->wg_peers);
4006 wg->wg_peers_bypubkey = thmap_create(0, NULL, THMAP_NOCOPY);
4007 wg->wg_peers_byname = thmap_create(0, NULL, THMAP_NOCOPY);
4008 wg->wg_sessions_byindex = thmap_create(0, NULL, THMAP_NOCOPY);
4009 wg->wg_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
4010 wg->wg_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
4011 wg->wg_rwlock = rw_obj_alloc();
4012 threadpool_job_init(&wg->wg_job, wg_job, wg->wg_intr_lock,
4013 "%s", if_name(&wg->wg_if));
4014 wg->wg_ops = &wg_ops_rumpkernel;
4015
4016 error = threadpool_get(&wg->wg_threadpool, PRI_NONE);
4017 if (error)
4018 goto fail0;
4019
4020 #ifdef INET
4021 error = wg_socreate(wg, AF_INET, &wg->wg_so4);
4022 if (error)
4023 goto fail1;
4024 rn_inithead((void **)&wg->wg_rtable_ipv4,
4025 offsetof(struct sockaddr_in, sin_addr) * NBBY);
4026 #endif
4027 #ifdef INET6
4028 error = wg_socreate(wg, AF_INET6, &wg->wg_so6);
4029 if (error)
4030 goto fail2;
4031 rn_inithead((void **)&wg->wg_rtable_ipv6,
4032 offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
4033 #endif
4034
4035 error = wg_if_attach(wg);
4036 if (error)
4037 goto fail3;
4038
4039 return 0;
4040
4041 fail4: __unused
4042 wg_destroy_all_peers(wg);
4043 wg_if_detach(wg);
4044 fail3:
4045 #ifdef INET6
4046 solock(wg->wg_so6);
4047 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
4048 sounlock(wg->wg_so6);
4049 #endif
4050 #ifdef INET
4051 solock(wg->wg_so4);
4052 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
4053 sounlock(wg->wg_so4);
4054 #endif
4055 mutex_enter(wg->wg_intr_lock);
4056 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
4057 mutex_exit(wg->wg_intr_lock);
4058 #ifdef INET6
4059 if (wg->wg_rtable_ipv6 != NULL)
4060 free(wg->wg_rtable_ipv6, M_RTABLE);
4061 soclose(wg->wg_so6);
4062 fail2:
4063 #endif
4064 #ifdef INET
4065 if (wg->wg_rtable_ipv4 != NULL)
4066 free(wg->wg_rtable_ipv4, M_RTABLE);
4067 soclose(wg->wg_so4);
4068 fail1:
4069 #endif
4070 threadpool_put(wg->wg_threadpool, PRI_NONE);
4071 fail0: threadpool_job_destroy(&wg->wg_job);
4072 rw_obj_free(wg->wg_rwlock);
4073 mutex_obj_free(wg->wg_intr_lock);
4074 mutex_obj_free(wg->wg_lock);
4075 thmap_destroy(wg->wg_sessions_byindex);
4076 thmap_destroy(wg->wg_peers_byname);
4077 thmap_destroy(wg->wg_peers_bypubkey);
4078 PSLIST_DESTROY(&wg->wg_peers);
4079 kmem_free(wg, sizeof(*wg));
4080 wg_count_dec();
4081 return error;
4082 }
4083
4084 static int
4085 wg_clone_destroy(struct ifnet *ifp)
4086 {
4087 struct wg_softc *wg = container_of(ifp, struct wg_softc, wg_if);
4088
4089 #ifdef WG_RUMPKERNEL
4090 if (wg_user_mode(wg)) {
4091 rumpuser_wg_destroy(wg->wg_user);
4092 wg->wg_user = NULL;
4093 }
4094 #endif
4095
4096 wg_destroy_all_peers(wg);
4097 wg_if_detach(wg);
4098 #ifdef INET6
4099 solock(wg->wg_so6);
4100 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
4101 sounlock(wg->wg_so6);
4102 #endif
4103 #ifdef INET
4104 solock(wg->wg_so4);
4105 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
4106 sounlock(wg->wg_so4);
4107 #endif
4108 mutex_enter(wg->wg_intr_lock);
4109 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
4110 mutex_exit(wg->wg_intr_lock);
4111 #ifdef INET6
4112 if (wg->wg_rtable_ipv6 != NULL)
4113 free(wg->wg_rtable_ipv6, M_RTABLE);
4114 soclose(wg->wg_so6);
4115 #endif
4116 #ifdef INET
4117 if (wg->wg_rtable_ipv4 != NULL)
4118 free(wg->wg_rtable_ipv4, M_RTABLE);
4119 soclose(wg->wg_so4);
4120 #endif
4121 threadpool_put(wg->wg_threadpool, PRI_NONE);
4122 threadpool_job_destroy(&wg->wg_job);
4123 rw_obj_free(wg->wg_rwlock);
4124 mutex_obj_free(wg->wg_intr_lock);
4125 mutex_obj_free(wg->wg_lock);
4126 thmap_destroy(wg->wg_sessions_byindex);
4127 thmap_destroy(wg->wg_peers_byname);
4128 thmap_destroy(wg->wg_peers_bypubkey);
4129 PSLIST_DESTROY(&wg->wg_peers);
4130 kmem_free(wg, sizeof(*wg));
4131 wg_count_dec();
4132
4133 return 0;
4134 }
4135
4136 static struct wg_peer *
4137 wg_pick_peer_by_sa(struct wg_softc *wg, const struct sockaddr *sa,
4138 struct psref *psref)
4139 {
4140 struct radix_node_head *rnh;
4141 struct radix_node *rn;
4142 struct wg_peer *wgp = NULL;
4143 struct wg_allowedip *wga;
4144
4145 #ifdef WG_DEBUG_LOG
4146 char addrstr[128];
4147 sockaddr_format(sa, addrstr, sizeof(addrstr));
4148 WG_DLOG("sa=%s\n", addrstr);
4149 #endif
4150
4151 rw_enter(wg->wg_rwlock, RW_READER);
4152
4153 rnh = wg_rnh(wg, sa->sa_family);
4154 if (rnh == NULL)
4155 goto out;
4156
4157 rn = rnh->rnh_matchaddr(sa, rnh);
4158 if (rn == NULL || (rn->rn_flags & RNF_ROOT) != 0)
4159 goto out;
4160
4161 WG_TRACE("success");
4162
4163 wga = container_of(rn, struct wg_allowedip, wga_nodes[0]);
4164 wgp = wga->wga_peer;
4165 wg_get_peer(wgp, psref);
4166
4167 out:
4168 rw_exit(wg->wg_rwlock);
4169 return wgp;
4170 }
4171
4172 static void
4173 wg_fill_msg_data(struct wg_softc *wg, struct wg_peer *wgp,
4174 struct wg_session *wgs, struct wg_msg_data *wgmd)
4175 {
4176
4177 memset(wgmd, 0, sizeof(*wgmd));
4178 wgmd->wgmd_type = htole32(WG_MSG_TYPE_DATA);
4179 wgmd->wgmd_receiver = wgs->wgs_remote_index;
4180 /* [W] 5.4.6: msg.counter := Nm^send */
4181 /* [W] 5.4.6: Nm^send := Nm^send + 1 */
4182 wgmd->wgmd_counter = htole64(wg_session_inc_send_counter(wgs));
4183 WG_DLOG("counter=%"PRIu64"\n", le64toh(wgmd->wgmd_counter));
4184 }
4185
4186 static int
4187 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
4188 const struct rtentry *rt)
4189 {
4190 struct wg_softc *wg = ifp->if_softc;
4191 struct wg_peer *wgp = NULL;
4192 struct wg_session *wgs = NULL;
4193 struct psref wgp_psref, wgs_psref;
4194 int bound;
4195 int error;
4196
4197 bound = curlwp_bind();
4198
4199 /* TODO make the nest limit configurable via sysctl */
4200 error = if_tunnel_check_nesting(ifp, m, 1);
4201 if (error) {
4202 WGLOG(LOG_ERR,
4203 "%s: tunneling loop detected and packet dropped\n",
4204 if_name(&wg->wg_if));
4205 goto out0;
4206 }
4207
4208 #ifdef ALTQ
4209 bool altq = atomic_load_relaxed(&ifp->if_snd.altq_flags)
4210 & ALTQF_ENABLED;
4211 if (altq)
4212 IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
4213 #endif
4214
4215 bpf_mtap_af(ifp, dst->sa_family, m, BPF_D_OUT);
4216
4217 m->m_flags &= ~(M_BCAST|M_MCAST);
4218
4219 wgp = wg_pick_peer_by_sa(wg, dst, &wgp_psref);
4220 if (wgp == NULL) {
4221 WG_TRACE("peer not found");
4222 error = EHOSTUNREACH;
4223 goto out0;
4224 }
4225
4226 /* Clear checksum-offload flags. */
4227 m->m_pkthdr.csum_flags = 0;
4228 m->m_pkthdr.csum_data = 0;
4229
4230 /* Check whether there's an established session. */
4231 wgs = wg_get_stable_session(wgp, &wgs_psref);
4232 if (wgs == NULL) {
4233 /*
4234 * No established session. If we're the first to try
4235 * sending data, schedule a handshake and queue the
4236 * packet for when the handshake is done; otherwise
4237 * just drop the packet and let the ongoing handshake
4238 * attempt continue. We could queue more data packets
4239 * but it's not clear that's worthwhile.
4240 */
4241 if ((m = atomic_swap_ptr(&wgp->wgp_pending, m)) == NULL) {
4242 WG_TRACE("queued first packet; init handshake");
4243 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4244 } else {
4245 WG_TRACE("first packet already queued, dropping");
4246 }
4247 goto out1;
4248 }
4249
4250 /* There's an established session. Toss it in the queue. */
4251 #ifdef ALTQ
4252 if (altq) {
4253 mutex_enter(ifp->if_snd.ifq_lock);
4254 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
4255 M_SETCTX(m, wgp);
4256 ALTQ_ENQUEUE(&ifp->if_snd, m, error);
4257 m = NULL; /* consume */
4258 }
4259 mutex_exit(ifp->if_snd.ifq_lock);
4260 if (m == NULL) {
4261 wg_start(ifp);
4262 goto out2;
4263 }
4264 }
4265 #endif
4266 kpreempt_disable();
4267 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
4268 M_SETCTX(m, wgp);
4269 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
4270 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
4271 if_name(&wg->wg_if));
4272 error = ENOBUFS;
4273 goto out3;
4274 }
4275 m = NULL; /* consumed */
4276 error = 0;
4277 out3: kpreempt_enable();
4278
4279 #ifdef ALTQ
4280 out2:
4281 #endif
4282 wg_put_session(wgs, &wgs_psref);
4283 out1: wg_put_peer(wgp, &wgp_psref);
4284 out0: m_freem(m);
4285 curlwp_bindx(bound);
4286 return error;
4287 }
4288
4289 static int
4290 wg_send_udp(struct wg_peer *wgp, struct mbuf *m)
4291 {
4292 struct psref psref;
4293 struct wg_sockaddr *wgsa;
4294 int error;
4295 struct socket *so;
4296
4297 wgsa = wg_get_endpoint_sa(wgp, &psref);
4298 so = wg_get_so_by_peer(wgp, wgsa);
4299 solock(so);
4300 switch (wgsatosa(wgsa)->sa_family) {
4301 #ifdef INET
4302 case AF_INET:
4303 error = udp_send(so, m, wgsatosa(wgsa), NULL, curlwp);
4304 break;
4305 #endif
4306 #ifdef INET6
4307 case AF_INET6:
4308 error = udp6_output(sotoinpcb(so), m, wgsatosin6(wgsa),
4309 NULL, curlwp);
4310 break;
4311 #endif
4312 default:
4313 m_freem(m);
4314 error = EPFNOSUPPORT;
4315 }
4316 sounlock(so);
4317 wg_put_sa(wgp, wgsa, &psref);
4318
4319 return error;
4320 }
4321
4322 /* Inspired by pppoe_get_mbuf */
4323 static struct mbuf *
4324 wg_get_mbuf(size_t leading_len, size_t len)
4325 {
4326 struct mbuf *m;
4327
4328 KASSERT(leading_len <= MCLBYTES);
4329 KASSERT(len <= MCLBYTES - leading_len);
4330
4331 m = m_gethdr(M_DONTWAIT, MT_DATA);
4332 if (m == NULL)
4333 return NULL;
4334 if (len + leading_len > MHLEN) {
4335 m_clget(m, M_DONTWAIT);
4336 if ((m->m_flags & M_EXT) == 0) {
4337 m_free(m);
4338 return NULL;
4339 }
4340 }
4341 m->m_data += leading_len;
4342 m->m_pkthdr.len = m->m_len = len;
4343
4344 return m;
4345 }
4346
4347 static void
4348 wg_send_data_msg(struct wg_peer *wgp, struct wg_session *wgs, struct mbuf *m)
4349 {
4350 struct wg_softc *wg = wgp->wgp_sc;
4351 int error;
4352 size_t inner_len, padded_len, encrypted_len;
4353 char *padded_buf = NULL;
4354 size_t mlen;
4355 struct wg_msg_data *wgmd;
4356 bool free_padded_buf = false;
4357 struct mbuf *n;
4358 size_t leading_len = max_hdr + sizeof(struct udphdr);
4359
4360 mlen = m_length(m);
4361 inner_len = mlen;
4362 padded_len = roundup(mlen, 16);
4363 encrypted_len = padded_len + WG_AUTHTAG_LEN;
4364 WG_DLOG("inner=%zu, padded=%zu, encrypted_len=%zu\n",
4365 inner_len, padded_len, encrypted_len);
4366 if (mlen != 0) {
4367 bool success;
4368 success = m_ensure_contig(&m, padded_len);
4369 if (success) {
4370 padded_buf = mtod(m, char *);
4371 } else {
4372 padded_buf = kmem_intr_alloc(padded_len, KM_NOSLEEP);
4373 if (padded_buf == NULL) {
4374 error = ENOBUFS;
4375 goto out;
4376 }
4377 free_padded_buf = true;
4378 m_copydata(m, 0, mlen, padded_buf);
4379 }
4380 memset(padded_buf + mlen, 0, padded_len - inner_len);
4381 }
4382
4383 n = wg_get_mbuf(leading_len, sizeof(*wgmd) + encrypted_len);
4384 if (n == NULL) {
4385 error = ENOBUFS;
4386 goto out;
4387 }
4388 KASSERT(n->m_len >= sizeof(*wgmd));
4389 wgmd = mtod(n, struct wg_msg_data *);
4390 wg_fill_msg_data(wg, wgp, wgs, wgmd);
4391
4392 /* [W] 5.4.6: AEAD(Tm^send, Nm^send, P, e) */
4393 wg_algo_aead_enc((char *)wgmd + sizeof(*wgmd), encrypted_len,
4394 wgs->wgs_tkey_send, le64toh(wgmd->wgmd_counter),
4395 padded_buf, padded_len,
4396 NULL, 0);
4397
4398 error = wg->wg_ops->send_data_msg(wgp, n); /* consumes n */
4399 if (error) {
4400 WG_DLOG("send_data_msg failed, error=%d\n", error);
4401 goto out;
4402 }
4403
4404 /*
4405 * Packet was sent out -- count it in the interface statistics.
4406 */
4407 if_statadd(&wg->wg_if, if_obytes, mlen);
4408 if_statinc(&wg->wg_if, if_opackets);
4409
4410 /*
4411 * Record when we last sent data, for determining when we need
4412 * to send a passive keepalive.
4413 *
4414 * Other logic assumes that wgs_time_last_data_sent is zero iff
4415 * we have never sent data on this session. Early at boot, if
4416 * wg(4) starts operating within <1sec, or after 136 years of
4417 * uptime, we may observe time_uptime32 = 0. In that case,
4418 * pretend we observed 1 instead. That way, we correctly
4419 * indicate we have sent data on this session; the only logic
4420 * this might adversely affect is the keepalive timeout
4421 * detection, which might spuriously send a keepalive during
4422 * one second every 136 years. All of this is very silly, of
4423 * course, but the cost to guaranteeing wgs_time_last_data_sent
4424 * is nonzero is negligible here.
4425 */
4426 const uint32_t now = time_uptime32;
4427 atomic_store_relaxed(&wgs->wgs_time_last_data_sent, MAX(now, 1));
4428
4429 /*
4430 * Check rekey-after-time.
4431 */
4432 if (wgs->wgs_is_initiator &&
4433 ((time_uptime32 -
4434 atomic_load_relaxed(&wgs->wgs_time_established)) >=
4435 wg_rekey_after_time)) {
4436 /*
4437 * [W] 6.2 Transport Message Limits
4438 * "if a peer is the initiator of a current secure
4439 * session, WireGuard will send a handshake initiation
4440 * message to begin a new secure session if, after
4441 * transmitting a transport data message, the current
4442 * secure session is REKEY-AFTER-TIME seconds old,"
4443 */
4444 WG_TRACE("rekey after time");
4445 atomic_store_relaxed(&wgs->wgs_force_rekey, true);
4446 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4447 }
4448
4449 /*
4450 * Check rekey-after-messages.
4451 */
4452 if (wg_session_get_send_counter(wgs) >= wg_rekey_after_messages) {
4453 /*
4454 * [W] 6.2 Transport Message Limits
4455 * "WireGuard will try to create a new session, by
4456 * sending a handshake initiation message (section
4457 * 5.4.2), after it has sent REKEY-AFTER-MESSAGES
4458 * transport data messages..."
4459 */
4460 WG_TRACE("rekey after messages");
4461 atomic_store_relaxed(&wgs->wgs_force_rekey, true);
4462 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4463 }
4464
4465 out: m_freem(m);
4466 if (free_padded_buf)
4467 kmem_intr_free(padded_buf, padded_len);
4468 }
4469
4470 static void
4471 wg_input(struct ifnet *ifp, struct mbuf *m, const int af)
4472 {
4473 pktqueue_t *pktq;
4474 size_t pktlen;
4475
4476 KASSERT(af == AF_INET || af == AF_INET6);
4477
4478 WG_TRACE("");
4479
4480 m_set_rcvif(m, ifp);
4481 pktlen = m->m_pkthdr.len;
4482
4483 bpf_mtap_af(ifp, af, m, BPF_D_IN);
4484
4485 switch (af) {
4486 #ifdef INET
4487 case AF_INET:
4488 pktq = ip_pktq;
4489 break;
4490 #endif
4491 #ifdef INET6
4492 case AF_INET6:
4493 pktq = ip6_pktq;
4494 break;
4495 #endif
4496 default:
4497 panic("invalid af=%d", af);
4498 }
4499
4500 kpreempt_disable();
4501 const u_int h = curcpu()->ci_index;
4502 if (__predict_true(pktq_enqueue(pktq, m, h))) {
4503 if_statadd(ifp, if_ibytes, pktlen);
4504 if_statinc(ifp, if_ipackets);
4505 } else {
4506 m_freem(m);
4507 }
4508 kpreempt_enable();
4509 }
4510
4511 static void
4512 wg_calc_pubkey(uint8_t pubkey[static WG_STATIC_KEY_LEN],
4513 const uint8_t privkey[static WG_STATIC_KEY_LEN])
4514 {
4515
4516 crypto_scalarmult_base(pubkey, privkey);
4517 }
4518
4519 static int
4520 wg_rtable_add_route(struct wg_softc *wg, struct wg_allowedip *wga)
4521 {
4522 struct radix_node_head *rnh;
4523 struct radix_node *rn;
4524 int error = 0;
4525
4526 rw_enter(wg->wg_rwlock, RW_WRITER);
4527 rnh = wg_rnh(wg, wga->wga_family);
4528 KASSERT(rnh != NULL);
4529 rn = rnh->rnh_addaddr(&wga->wga_sa_addr, &wga->wga_sa_mask, rnh,
4530 wga->wga_nodes);
4531 rw_exit(wg->wg_rwlock);
4532
4533 if (rn == NULL)
4534 error = EEXIST;
4535
4536 return error;
4537 }
4538
4539 static int
4540 wg_handle_prop_peer(struct wg_softc *wg, prop_dictionary_t peer,
4541 struct wg_peer **wgpp)
4542 {
4543 int error = 0;
4544 const void *pubkey;
4545 size_t pubkey_len;
4546 const void *psk;
4547 size_t psk_len;
4548 const char *name = NULL;
4549
4550 if (prop_dictionary_get_string(peer, "name", &name)) {
4551 if (strlen(name) > WG_PEER_NAME_MAXLEN) {
4552 error = EINVAL;
4553 goto out;
4554 }
4555 }
4556
4557 if (!prop_dictionary_get_data(peer, "public_key",
4558 &pubkey, &pubkey_len)) {
4559 error = EINVAL;
4560 goto out;
4561 }
4562 #ifdef WG_DEBUG_DUMP
4563 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4564 char *hex = gethexdump(pubkey, pubkey_len);
4565 log(LOG_DEBUG, "pubkey=%p, pubkey_len=%zu\n%s\n",
4566 pubkey, pubkey_len, hex);
4567 puthexdump(hex, pubkey, pubkey_len);
4568 }
4569 #endif
4570
4571 struct wg_peer *wgp = wg_alloc_peer(wg);
4572 memcpy(wgp->wgp_pubkey, pubkey, sizeof(wgp->wgp_pubkey));
4573 if (name != NULL)
4574 strncpy(wgp->wgp_name, name, sizeof(wgp->wgp_name));
4575
4576 if (prop_dictionary_get_data(peer, "preshared_key", &psk, &psk_len)) {
4577 if (psk_len != sizeof(wgp->wgp_psk)) {
4578 error = EINVAL;
4579 goto out;
4580 }
4581 memcpy(wgp->wgp_psk, psk, sizeof(wgp->wgp_psk));
4582 }
4583
4584 const void *addr;
4585 size_t addr_len;
4586 struct wg_sockaddr *wgsa = wgp->wgp_endpoint;
4587
4588 if (!prop_dictionary_get_data(peer, "endpoint", &addr, &addr_len))
4589 goto skip_endpoint;
4590 if (addr_len < sizeof(*wgsatosa(wgsa)) ||
4591 addr_len > sizeof(*wgsatoss(wgsa))) {
4592 error = EINVAL;
4593 goto out;
4594 }
4595 memcpy(wgsatoss(wgsa), addr, addr_len);
4596 switch (wgsa_family(wgsa)) {
4597 #ifdef INET
4598 case AF_INET:
4599 break;
4600 #endif
4601 #ifdef INET6
4602 case AF_INET6:
4603 break;
4604 #endif
4605 default:
4606 error = EPFNOSUPPORT;
4607 goto out;
4608 }
4609 if (addr_len != sockaddr_getsize_by_family(wgsa_family(wgsa))) {
4610 error = EINVAL;
4611 goto out;
4612 }
4613 {
4614 char addrstr[128];
4615 sockaddr_format(wgsatosa(wgsa), addrstr, sizeof(addrstr));
4616 WG_DLOG("addr=%s\n", addrstr);
4617 }
4618 wgp->wgp_endpoint_available = true;
4619
4620 prop_array_t allowedips;
4621 skip_endpoint:
4622 allowedips = prop_dictionary_get(peer, "allowedips");
4623 if (allowedips == NULL)
4624 goto skip;
4625
4626 prop_object_iterator_t _it = prop_array_iterator(allowedips);
4627 prop_dictionary_t prop_allowedip;
4628 int j = 0;
4629 while ((prop_allowedip = prop_object_iterator_next(_it)) != NULL) {
4630 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
4631
4632 if (!prop_dictionary_get_int(prop_allowedip, "family",
4633 &wga->wga_family))
4634 continue;
4635 if (!prop_dictionary_get_data(prop_allowedip, "ip",
4636 &addr, &addr_len))
4637 continue;
4638 if (!prop_dictionary_get_uint8(prop_allowedip, "cidr",
4639 &wga->wga_cidr))
4640 continue;
4641
4642 switch (wga->wga_family) {
4643 #ifdef INET
4644 case AF_INET: {
4645 struct sockaddr_in sin;
4646 char addrstr[128];
4647 struct in_addr mask;
4648 struct sockaddr_in sin_mask;
4649
4650 if (addr_len != sizeof(struct in_addr))
4651 return EINVAL;
4652 memcpy(&wga->wga_addr4, addr, addr_len);
4653
4654 sockaddr_in_init(&sin, (const struct in_addr *)addr,
4655 0);
4656 sockaddr_copy(&wga->wga_sa_addr,
4657 sizeof(sin), sintosa(&sin));
4658
4659 sockaddr_format(sintosa(&sin),
4660 addrstr, sizeof(addrstr));
4661 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4662
4663 in_len2mask(&mask, wga->wga_cidr);
4664 sockaddr_in_init(&sin_mask, &mask, 0);
4665 sockaddr_copy(&wga->wga_sa_mask,
4666 sizeof(sin_mask), sintosa(&sin_mask));
4667
4668 break;
4669 }
4670 #endif
4671 #ifdef INET6
4672 case AF_INET6: {
4673 struct sockaddr_in6 sin6;
4674 char addrstr[128];
4675 struct in6_addr mask;
4676 struct sockaddr_in6 sin6_mask;
4677
4678 if (addr_len != sizeof(struct in6_addr))
4679 return EINVAL;
4680 memcpy(&wga->wga_addr6, addr, addr_len);
4681
4682 sockaddr_in6_init(&sin6, (const struct in6_addr *)addr,
4683 0, 0, 0);
4684 sockaddr_copy(&wga->wga_sa_addr,
4685 sizeof(sin6), sin6tosa(&sin6));
4686
4687 sockaddr_format(sin6tosa(&sin6),
4688 addrstr, sizeof(addrstr));
4689 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4690
4691 in6_prefixlen2mask(&mask, wga->wga_cidr);
4692 sockaddr_in6_init(&sin6_mask, &mask, 0, 0, 0);
4693 sockaddr_copy(&wga->wga_sa_mask,
4694 sizeof(sin6_mask), sin6tosa(&sin6_mask));
4695
4696 break;
4697 }
4698 #endif
4699 default:
4700 error = EINVAL;
4701 goto out;
4702 }
4703 wga->wga_peer = wgp;
4704
4705 error = wg_rtable_add_route(wg, wga);
4706 if (error != 0)
4707 goto out;
4708
4709 j++;
4710 }
4711 wgp->wgp_n_allowedips = j;
4712 skip:
4713 *wgpp = wgp;
4714 out:
4715 return error;
4716 }
4717
4718 static int
4719 wg_alloc_prop_buf(char **_buf, struct ifdrv *ifd)
4720 {
4721 int error;
4722 char *buf;
4723
4724 WG_DLOG("buf=%p, len=%zu\n", ifd->ifd_data, ifd->ifd_len);
4725 if (ifd->ifd_len >= WG_MAX_PROPLEN)
4726 return E2BIG;
4727 buf = kmem_alloc(ifd->ifd_len + 1, KM_SLEEP);
4728 error = copyin(ifd->ifd_data, buf, ifd->ifd_len);
4729 if (error != 0)
4730 return error;
4731 buf[ifd->ifd_len] = '\0';
4732 #ifdef WG_DEBUG_DUMP
4733 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4734 log(LOG_DEBUG, "%.*s\n", (int)MIN(INT_MAX, ifd->ifd_len),
4735 (const char *)buf);
4736 }
4737 #endif
4738 *_buf = buf;
4739 return 0;
4740 }
4741
4742 static int
4743 wg_ioctl_set_private_key(struct wg_softc *wg, struct ifdrv *ifd)
4744 {
4745 int error;
4746 prop_dictionary_t prop_dict;
4747 char *buf = NULL;
4748 const void *privkey;
4749 size_t privkey_len;
4750
4751 error = wg_alloc_prop_buf(&buf, ifd);
4752 if (error != 0)
4753 return error;
4754 error = EINVAL;
4755 prop_dict = prop_dictionary_internalize(buf);
4756 if (prop_dict == NULL)
4757 goto out;
4758 if (!prop_dictionary_get_data(prop_dict, "private_key",
4759 &privkey, &privkey_len))
4760 goto out;
4761 #ifdef WG_DEBUG_DUMP
4762 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4763 char *hex = gethexdump(privkey, privkey_len);
4764 log(LOG_DEBUG, "privkey=%p, privkey_len=%zu\n%s\n",
4765 privkey, privkey_len, hex);
4766 puthexdump(hex, privkey, privkey_len);
4767 }
4768 #endif
4769 if (privkey_len != WG_STATIC_KEY_LEN)
4770 goto out;
4771 memcpy(wg->wg_privkey, privkey, WG_STATIC_KEY_LEN);
4772 wg_calc_pubkey(wg->wg_pubkey, wg->wg_privkey);
4773 error = 0;
4774
4775 out:
4776 kmem_free(buf, ifd->ifd_len + 1);
4777 return error;
4778 }
4779
4780 static int
4781 wg_ioctl_set_listen_port(struct wg_softc *wg, struct ifdrv *ifd)
4782 {
4783 int error;
4784 prop_dictionary_t prop_dict;
4785 char *buf = NULL;
4786 uint16_t port;
4787
4788 error = wg_alloc_prop_buf(&buf, ifd);
4789 if (error != 0)
4790 return error;
4791 error = EINVAL;
4792 prop_dict = prop_dictionary_internalize(buf);
4793 if (prop_dict == NULL)
4794 goto out;
4795 if (!prop_dictionary_get_uint16(prop_dict, "listen_port", &port))
4796 goto out;
4797
4798 error = wg->wg_ops->bind_port(wg, (uint16_t)port);
4799
4800 out:
4801 kmem_free(buf, ifd->ifd_len + 1);
4802 return error;
4803 }
4804
4805 static int
4806 wg_ioctl_add_peer(struct wg_softc *wg, struct ifdrv *ifd)
4807 {
4808 int error;
4809 prop_dictionary_t prop_dict;
4810 char *buf = NULL;
4811 struct wg_peer *wgp = NULL, *wgp0 __diagused;
4812
4813 error = wg_alloc_prop_buf(&buf, ifd);
4814 if (error != 0)
4815 return error;
4816 error = EINVAL;
4817 prop_dict = prop_dictionary_internalize(buf);
4818 if (prop_dict == NULL)
4819 goto out;
4820
4821 error = wg_handle_prop_peer(wg, prop_dict, &wgp);
4822 if (error != 0)
4823 goto out;
4824
4825 mutex_enter(wg->wg_lock);
4826 if (thmap_get(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4827 sizeof(wgp->wgp_pubkey)) != NULL ||
4828 (wgp->wgp_name[0] &&
4829 thmap_get(wg->wg_peers_byname, wgp->wgp_name,
4830 strlen(wgp->wgp_name)) != NULL)) {
4831 mutex_exit(wg->wg_lock);
4832 wg_destroy_peer(wgp);
4833 error = EEXIST;
4834 goto out;
4835 }
4836 wgp0 = thmap_put(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4837 sizeof(wgp->wgp_pubkey), wgp);
4838 KASSERT(wgp0 == wgp);
4839 if (wgp->wgp_name[0]) {
4840 wgp0 = thmap_put(wg->wg_peers_byname, wgp->wgp_name,
4841 strlen(wgp->wgp_name), wgp);
4842 KASSERT(wgp0 == wgp);
4843 }
4844 WG_PEER_WRITER_INSERT_HEAD(wgp, wg);
4845 wg->wg_npeers++;
4846 mutex_exit(wg->wg_lock);
4847
4848 if_link_state_change(&wg->wg_if, LINK_STATE_UP);
4849
4850 out:
4851 kmem_free(buf, ifd->ifd_len + 1);
4852 return error;
4853 }
4854
4855 static int
4856 wg_ioctl_delete_peer(struct wg_softc *wg, struct ifdrv *ifd)
4857 {
4858 int error;
4859 prop_dictionary_t prop_dict;
4860 char *buf = NULL;
4861 const char *name;
4862
4863 error = wg_alloc_prop_buf(&buf, ifd);
4864 if (error != 0)
4865 return error;
4866 error = EINVAL;
4867 prop_dict = prop_dictionary_internalize(buf);
4868 if (prop_dict == NULL)
4869 goto out;
4870
4871 if (!prop_dictionary_get_string(prop_dict, "name", &name))
4872 goto out;
4873 if (strlen(name) > WG_PEER_NAME_MAXLEN)
4874 goto out;
4875
4876 error = wg_destroy_peer_name(wg, name);
4877 out:
4878 kmem_free(buf, ifd->ifd_len + 1);
4879 return error;
4880 }
4881
4882 static bool
4883 wg_is_authorized(struct wg_softc *wg, u_long cmd)
4884 {
4885 int au = cmd == SIOCGDRVSPEC ?
4886 KAUTH_REQ_NETWORK_INTERFACE_WG_GETPRIV :
4887 KAUTH_REQ_NETWORK_INTERFACE_WG_SETPRIV;
4888 return kauth_authorize_network(kauth_cred_get(),
4889 KAUTH_NETWORK_INTERFACE_WG, au, &wg->wg_if,
4890 (void *)cmd, NULL) == 0;
4891 }
4892
4893 static int
4894 wg_ioctl_get(struct wg_softc *wg, struct ifdrv *ifd)
4895 {
4896 int error = ENOMEM;
4897 prop_dictionary_t prop_dict;
4898 prop_array_t peers = NULL;
4899 char *buf;
4900 struct wg_peer *wgp;
4901 int s, i;
4902
4903 prop_dict = prop_dictionary_create();
4904 if (prop_dict == NULL)
4905 goto error;
4906
4907 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
4908 if (!prop_dictionary_set_data(prop_dict, "private_key",
4909 wg->wg_privkey, WG_STATIC_KEY_LEN))
4910 goto error;
4911 }
4912
4913 if (wg->wg_listen_port != 0) {
4914 if (!prop_dictionary_set_uint16(prop_dict, "listen_port",
4915 wg->wg_listen_port))
4916 goto error;
4917 }
4918
4919 if (wg->wg_npeers == 0)
4920 goto skip_peers;
4921
4922 peers = prop_array_create();
4923 if (peers == NULL)
4924 goto error;
4925
4926 s = pserialize_read_enter();
4927 i = 0;
4928 WG_PEER_READER_FOREACH(wgp, wg) {
4929 struct wg_sockaddr *wgsa;
4930 struct psref wgp_psref, wgsa_psref;
4931 prop_dictionary_t prop_peer;
4932
4933 wg_get_peer(wgp, &wgp_psref);
4934 pserialize_read_exit(s);
4935
4936 prop_peer = prop_dictionary_create();
4937 if (prop_peer == NULL)
4938 goto next;
4939
4940 if (strlen(wgp->wgp_name) > 0) {
4941 if (!prop_dictionary_set_string(prop_peer, "name",
4942 wgp->wgp_name))
4943 goto next;
4944 }
4945
4946 if (!prop_dictionary_set_data(prop_peer, "public_key",
4947 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey)))
4948 goto next;
4949
4950 uint8_t psk_zero[WG_PRESHARED_KEY_LEN] = {0};
4951 if (!consttime_memequal(wgp->wgp_psk, psk_zero,
4952 sizeof(wgp->wgp_psk))) {
4953 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
4954 if (!prop_dictionary_set_data(prop_peer,
4955 "preshared_key",
4956 wgp->wgp_psk, sizeof(wgp->wgp_psk)))
4957 goto next;
4958 }
4959 }
4960
4961 wgsa = wg_get_endpoint_sa(wgp, &wgsa_psref);
4962 CTASSERT(AF_UNSPEC == 0);
4963 if (wgsa_family(wgsa) != 0 /*AF_UNSPEC*/ &&
4964 !prop_dictionary_set_data(prop_peer, "endpoint",
4965 wgsatoss(wgsa),
4966 sockaddr_getsize_by_family(wgsa_family(wgsa)))) {
4967 wg_put_sa(wgp, wgsa, &wgsa_psref);
4968 goto next;
4969 }
4970 wg_put_sa(wgp, wgsa, &wgsa_psref);
4971
4972 const struct timespec *t = &wgp->wgp_last_handshake_time;
4973
4974 if (!prop_dictionary_set_uint64(prop_peer,
4975 "last_handshake_time_sec", (uint64_t)t->tv_sec))
4976 goto next;
4977 if (!prop_dictionary_set_uint32(prop_peer,
4978 "last_handshake_time_nsec", (uint32_t)t->tv_nsec))
4979 goto next;
4980
4981 if (wgp->wgp_n_allowedips == 0)
4982 goto skip_allowedips;
4983
4984 prop_array_t allowedips = prop_array_create();
4985 if (allowedips == NULL)
4986 goto next;
4987 for (int j = 0; j < wgp->wgp_n_allowedips; j++) {
4988 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
4989 prop_dictionary_t prop_allowedip;
4990
4991 prop_allowedip = prop_dictionary_create();
4992 if (prop_allowedip == NULL)
4993 break;
4994
4995 if (!prop_dictionary_set_int(prop_allowedip, "family",
4996 wga->wga_family))
4997 goto _next;
4998 if (!prop_dictionary_set_uint8(prop_allowedip, "cidr",
4999 wga->wga_cidr))
5000 goto _next;
5001
5002 switch (wga->wga_family) {
5003 #ifdef INET
5004 case AF_INET:
5005 if (!prop_dictionary_set_data(prop_allowedip,
5006 "ip", &wga->wga_addr4,
5007 sizeof(wga->wga_addr4)))
5008 goto _next;
5009 break;
5010 #endif
5011 #ifdef INET6
5012 case AF_INET6:
5013 if (!prop_dictionary_set_data(prop_allowedip,
5014 "ip", &wga->wga_addr6,
5015 sizeof(wga->wga_addr6)))
5016 goto _next;
5017 break;
5018 #endif
5019 default:
5020 panic("invalid af=%d", wga->wga_family);
5021 }
5022 prop_array_set(allowedips, j, prop_allowedip);
5023 _next:
5024 prop_object_release(prop_allowedip);
5025 }
5026 prop_dictionary_set(prop_peer, "allowedips", allowedips);
5027 prop_object_release(allowedips);
5028
5029 skip_allowedips:
5030
5031 prop_array_set(peers, i, prop_peer);
5032 next:
5033 if (prop_peer)
5034 prop_object_release(prop_peer);
5035 i++;
5036
5037 s = pserialize_read_enter();
5038 wg_put_peer(wgp, &wgp_psref);
5039 }
5040 pserialize_read_exit(s);
5041
5042 prop_dictionary_set(prop_dict, "peers", peers);
5043 prop_object_release(peers);
5044 peers = NULL;
5045
5046 skip_peers:
5047 buf = prop_dictionary_externalize(prop_dict);
5048 if (buf == NULL)
5049 goto error;
5050 if (ifd->ifd_len < (strlen(buf) + 1)) {
5051 error = EINVAL;
5052 goto error;
5053 }
5054 error = copyout(buf, ifd->ifd_data, strlen(buf) + 1);
5055
5056 free(buf, 0);
5057 error:
5058 if (peers != NULL)
5059 prop_object_release(peers);
5060 if (prop_dict != NULL)
5061 prop_object_release(prop_dict);
5062
5063 return error;
5064 }
5065
5066 static int
5067 wg_ioctl(struct ifnet *ifp, u_long cmd, void *data)
5068 {
5069 struct wg_softc *wg = ifp->if_softc;
5070 struct ifreq *ifr = data;
5071 struct ifaddr *ifa = data;
5072 struct ifdrv *ifd = data;
5073 int error = 0;
5074
5075 switch (cmd) {
5076 case SIOCINITIFADDR:
5077 if (ifa->ifa_addr->sa_family != AF_LINK &&
5078 (ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
5079 (IFF_UP | IFF_RUNNING)) {
5080 ifp->if_flags |= IFF_UP;
5081 error = if_init(ifp);
5082 }
5083 return error;
5084 case SIOCADDMULTI:
5085 case SIOCDELMULTI:
5086 switch (ifr->ifr_addr.sa_family) {
5087 #ifdef INET
5088 case AF_INET: /* IP supports Multicast */
5089 break;
5090 #endif
5091 #ifdef INET6
5092 case AF_INET6: /* IP6 supports Multicast */
5093 break;
5094 #endif
5095 default: /* Other protocols doesn't support Multicast */
5096 error = EAFNOSUPPORT;
5097 break;
5098 }
5099 return error;
5100 case SIOCSDRVSPEC:
5101 if (!wg_is_authorized(wg, cmd)) {
5102 return EPERM;
5103 }
5104 switch (ifd->ifd_cmd) {
5105 case WG_IOCTL_SET_PRIVATE_KEY:
5106 error = wg_ioctl_set_private_key(wg, ifd);
5107 break;
5108 case WG_IOCTL_SET_LISTEN_PORT:
5109 error = wg_ioctl_set_listen_port(wg, ifd);
5110 break;
5111 case WG_IOCTL_ADD_PEER:
5112 error = wg_ioctl_add_peer(wg, ifd);
5113 break;
5114 case WG_IOCTL_DELETE_PEER:
5115 error = wg_ioctl_delete_peer(wg, ifd);
5116 break;
5117 default:
5118 error = EINVAL;
5119 break;
5120 }
5121 return error;
5122 case SIOCGDRVSPEC:
5123 return wg_ioctl_get(wg, ifd);
5124 case SIOCSIFFLAGS:
5125 if ((error = ifioctl_common(ifp, cmd, data)) != 0)
5126 break;
5127 switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
5128 case IFF_RUNNING:
5129 /*
5130 * If interface is marked down and it is running,
5131 * then stop and disable it.
5132 */
5133 if_stop(ifp, 1);
5134 break;
5135 case IFF_UP:
5136 /*
5137 * If interface is marked up and it is stopped, then
5138 * start it.
5139 */
5140 error = if_init(ifp);
5141 break;
5142 default:
5143 break;
5144 }
5145 return error;
5146 #ifdef WG_RUMPKERNEL
5147 case SIOCSLINKSTR:
5148 error = wg_ioctl_linkstr(wg, ifd);
5149 if (error)
5150 return error;
5151 wg->wg_ops = &wg_ops_rumpuser;
5152 return 0;
5153 #endif
5154 default:
5155 break;
5156 }
5157
5158 error = ifioctl_common(ifp, cmd, data);
5159
5160 #ifdef WG_RUMPKERNEL
5161 if (!wg_user_mode(wg))
5162 return error;
5163
5164 /* Do the same to the corresponding tun device on the host */
5165 /*
5166 * XXX Actually the command has not been handled yet. It
5167 * will be handled via pr_ioctl form doifioctl later.
5168 */
5169 switch (cmd) {
5170 #ifdef INET
5171 case SIOCAIFADDR:
5172 case SIOCDIFADDR: {
5173 struct in_aliasreq _ifra = *(const struct in_aliasreq *)data;
5174 struct in_aliasreq *ifra = &_ifra;
5175 KASSERT(error == ENOTTY);
5176 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5177 IFNAMSIZ);
5178 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET);
5179 if (error == 0)
5180 error = ENOTTY;
5181 break;
5182 }
5183 #endif
5184 #ifdef INET6
5185 case SIOCAIFADDR_IN6:
5186 case SIOCDIFADDR_IN6: {
5187 struct in6_aliasreq _ifra = *(const struct in6_aliasreq *)data;
5188 struct in6_aliasreq *ifra = &_ifra;
5189 KASSERT(error == ENOTTY);
5190 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5191 IFNAMSIZ);
5192 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET6);
5193 if (error == 0)
5194 error = ENOTTY;
5195 break;
5196 }
5197 #endif
5198 default:
5199 break;
5200 }
5201 #endif /* WG_RUMPKERNEL */
5202
5203 return error;
5204 }
5205
5206 static int
5207 wg_init(struct ifnet *ifp)
5208 {
5209
5210 ifp->if_flags |= IFF_RUNNING;
5211
5212 /* TODO flush pending packets. */
5213 return 0;
5214 }
5215
5216 #ifdef ALTQ
5217 static void
5218 wg_start(struct ifnet *ifp)
5219 {
5220 struct mbuf *m;
5221
5222 for (;;) {
5223 IFQ_DEQUEUE(&ifp->if_snd, m);
5224 if (m == NULL)
5225 break;
5226
5227 kpreempt_disable();
5228 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
5229 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
5230 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
5231 if_name(ifp));
5232 m_freem(m);
5233 }
5234 kpreempt_enable();
5235 }
5236 }
5237 #endif
5238
5239 static void
5240 wg_stop(struct ifnet *ifp, int disable)
5241 {
5242
5243 KASSERT((ifp->if_flags & IFF_RUNNING) != 0);
5244 ifp->if_flags &= ~IFF_RUNNING;
5245
5246 /* Need to do something? */
5247 }
5248
5249 #ifdef WG_DEBUG_PARAMS
5250 SYSCTL_SETUP(sysctl_net_wg_setup, "sysctl net.wg setup")
5251 {
5252 const struct sysctlnode *node = NULL;
5253
5254 sysctl_createv(clog, 0, NULL, &node,
5255 CTLFLAG_PERMANENT,
5256 CTLTYPE_NODE, "wg",
5257 SYSCTL_DESCR("wg(4)"),
5258 NULL, 0, NULL, 0,
5259 CTL_NET, CTL_CREATE, CTL_EOL);
5260 sysctl_createv(clog, 0, &node, NULL,
5261 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5262 CTLTYPE_QUAD, "rekey_after_messages",
5263 SYSCTL_DESCR("session liftime by messages"),
5264 NULL, 0, &wg_rekey_after_messages, 0, CTL_CREATE, CTL_EOL);
5265 sysctl_createv(clog, 0, &node, NULL,
5266 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5267 CTLTYPE_INT, "rekey_after_time",
5268 SYSCTL_DESCR("session liftime"),
5269 NULL, 0, &wg_rekey_after_time, 0, CTL_CREATE, CTL_EOL);
5270 sysctl_createv(clog, 0, &node, NULL,
5271 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5272 CTLTYPE_INT, "rekey_timeout",
5273 SYSCTL_DESCR("session handshake retry time"),
5274 NULL, 0, &wg_rekey_timeout, 0, CTL_CREATE, CTL_EOL);
5275 sysctl_createv(clog, 0, &node, NULL,
5276 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5277 CTLTYPE_INT, "rekey_attempt_time",
5278 SYSCTL_DESCR("session handshake timeout"),
5279 NULL, 0, &wg_rekey_attempt_time, 0, CTL_CREATE, CTL_EOL);
5280 sysctl_createv(clog, 0, &node, NULL,
5281 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5282 CTLTYPE_INT, "keepalive_timeout",
5283 SYSCTL_DESCR("keepalive timeout"),
5284 NULL, 0, &wg_keepalive_timeout, 0, CTL_CREATE, CTL_EOL);
5285 sysctl_createv(clog, 0, &node, NULL,
5286 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5287 CTLTYPE_BOOL, "force_underload",
5288 SYSCTL_DESCR("force to detemine under load"),
5289 NULL, 0, &wg_force_underload, 0, CTL_CREATE, CTL_EOL);
5290 sysctl_createv(clog, 0, &node, NULL,
5291 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5292 CTLTYPE_INT, "debug",
5293 SYSCTL_DESCR("set debug flags 1=log 2=trace 4=dump 8=packet"),
5294 NULL, 0, &wg_debug, 0, CTL_CREATE, CTL_EOL);
5295 }
5296 #endif
5297
5298 #ifdef WG_RUMPKERNEL
5299 static bool
5300 wg_user_mode(struct wg_softc *wg)
5301 {
5302
5303 return wg->wg_user != NULL;
5304 }
5305
5306 static int
5307 wg_ioctl_linkstr(struct wg_softc *wg, struct ifdrv *ifd)
5308 {
5309 struct ifnet *ifp = &wg->wg_if;
5310 int error;
5311
5312 if (ifp->if_flags & IFF_UP)
5313 return EBUSY;
5314
5315 if (ifd->ifd_cmd == IFLINKSTR_UNSET) {
5316 /* XXX do nothing */
5317 return 0;
5318 } else if (ifd->ifd_cmd != 0) {
5319 return EINVAL;
5320 } else if (wg->wg_user != NULL) {
5321 return EBUSY;
5322 }
5323
5324 /* Assume \0 included */
5325 if (ifd->ifd_len > IFNAMSIZ) {
5326 return E2BIG;
5327 } else if (ifd->ifd_len < 1) {
5328 return EINVAL;
5329 }
5330
5331 char tun_name[IFNAMSIZ];
5332 error = copyinstr(ifd->ifd_data, tun_name, ifd->ifd_len, NULL);
5333 if (error != 0)
5334 return error;
5335
5336 if (strncmp(tun_name, "tun", 3) != 0)
5337 return EINVAL;
5338
5339 error = rumpuser_wg_create(tun_name, wg, &wg->wg_user);
5340
5341 return error;
5342 }
5343
5344 static int
5345 wg_send_user(struct wg_peer *wgp, struct mbuf *m)
5346 {
5347 int error;
5348 struct psref psref;
5349 struct wg_sockaddr *wgsa;
5350 struct wg_softc *wg = wgp->wgp_sc;
5351 struct iovec iov[1];
5352
5353 wgsa = wg_get_endpoint_sa(wgp, &psref);
5354
5355 iov[0].iov_base = mtod(m, void *);
5356 iov[0].iov_len = m->m_len;
5357
5358 /* Send messages to a peer via an ordinary socket. */
5359 error = rumpuser_wg_send_peer(wg->wg_user, wgsatosa(wgsa), iov, 1);
5360
5361 wg_put_sa(wgp, wgsa, &psref);
5362
5363 m_freem(m);
5364
5365 return error;
5366 }
5367
5368 static void
5369 wg_input_user(struct ifnet *ifp, struct mbuf *m, const int af)
5370 {
5371 struct wg_softc *wg = ifp->if_softc;
5372 struct iovec iov[2];
5373 struct sockaddr_storage ss;
5374
5375 KASSERT(af == AF_INET || af == AF_INET6);
5376
5377 WG_TRACE("");
5378
5379 switch (af) {
5380 #ifdef INET
5381 case AF_INET: {
5382 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
5383 struct ip *ip;
5384
5385 KASSERT(m->m_len >= sizeof(struct ip));
5386 ip = mtod(m, struct ip *);
5387 sockaddr_in_init(sin, &ip->ip_dst, 0);
5388 break;
5389 }
5390 #endif
5391 #ifdef INET6
5392 case AF_INET6: {
5393 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
5394 struct ip6_hdr *ip6;
5395
5396 KASSERT(m->m_len >= sizeof(struct ip6_hdr));
5397 ip6 = mtod(m, struct ip6_hdr *);
5398 sockaddr_in6_init(sin6, &ip6->ip6_dst, 0, 0, 0);
5399 break;
5400 }
5401 #endif
5402 default:
5403 goto out;
5404 }
5405
5406 iov[0].iov_base = &ss;
5407 iov[0].iov_len = ss.ss_len;
5408 iov[1].iov_base = mtod(m, void *);
5409 iov[1].iov_len = m->m_len;
5410
5411 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5412
5413 /* Send decrypted packets to users via a tun. */
5414 rumpuser_wg_send_user(wg->wg_user, iov, 2);
5415
5416 out: m_freem(m);
5417 }
5418
5419 static int
5420 wg_bind_port_user(struct wg_softc *wg, const uint16_t port)
5421 {
5422 int error;
5423 uint16_t old_port = wg->wg_listen_port;
5424
5425 if (port != 0 && old_port == port)
5426 return 0;
5427
5428 error = rumpuser_wg_sock_bind(wg->wg_user, port);
5429 if (error)
5430 return error;
5431
5432 wg->wg_listen_port = port;
5433 return 0;
5434 }
5435
5436 /*
5437 * Receive user packets.
5438 */
5439 void
5440 rumpkern_wg_recv_user(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
5441 {
5442 struct ifnet *ifp = &wg->wg_if;
5443 struct mbuf *m;
5444 const struct sockaddr *dst;
5445 int error;
5446
5447 WG_TRACE("");
5448
5449 dst = iov[0].iov_base;
5450
5451 m = m_gethdr(M_DONTWAIT, MT_DATA);
5452 if (m == NULL)
5453 return;
5454 m->m_len = m->m_pkthdr.len = 0;
5455 m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
5456
5457 WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
5458 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5459
5460 error = wg_output(ifp, m, dst, NULL); /* consumes m */
5461 if (error)
5462 WG_DLOG("wg_output failed, error=%d\n", error);
5463 }
5464
5465 /*
5466 * Receive packets from a peer.
5467 */
5468 void
5469 rumpkern_wg_recv_peer(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
5470 {
5471 struct mbuf *m;
5472 const struct sockaddr *src;
5473 int bound;
5474
5475 WG_TRACE("");
5476
5477 src = iov[0].iov_base;
5478
5479 m = m_gethdr(M_DONTWAIT, MT_DATA);
5480 if (m == NULL)
5481 return;
5482 m->m_len = m->m_pkthdr.len = 0;
5483 m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
5484
5485 WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
5486 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5487
5488 bound = curlwp_bind();
5489 wg_handle_packet(wg, m, src);
5490 curlwp_bindx(bound);
5491 }
5492 #endif /* WG_RUMPKERNEL */
5493
5494 /*
5495 * Module infrastructure
5496 */
5497 #include "if_module.h"
5498
5499 IF_MODULE(MODULE_CLASS_DRIVER, wg, "sodium,blake2s")
5500