Home | History | Annotate | Line # | Download | only in net
if_wg.c revision 1.114
      1 /*	$NetBSD: if_wg.c,v 1.114 2024/07/29 02:29:11 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.114 2024/07/29 02:29:11 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 	wgs = wgp->wgp_session_unstable;
   1991 	KASSERTMSG(wgs->wgs_state == WGS_STATE_ESTABLISHED, "state=%d",
   1992 	    wgs->wgs_state);
   1993 
   1994 	wgs_prev = wgp->wgp_session_stable;
   1995 	KASSERTMSG((wgs_prev->wgs_state == WGS_STATE_ESTABLISHED ||
   1996 		wgs_prev->wgs_state == WGS_STATE_UNKNOWN),
   1997 	    "state=%d", wgs_prev->wgs_state);
   1998 	atomic_store_release(&wgp->wgp_session_stable, wgs);
   1999 	wgp->wgp_session_unstable = wgs_prev;
   2000 }
   2001 
   2002 static void __noinline
   2003 wg_handle_msg_resp(struct wg_softc *wg, const struct wg_msg_resp *wgmr,
   2004     const struct sockaddr *src)
   2005 {
   2006 	uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.3: Cr */
   2007 	uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.3: Kr */
   2008 	uint8_t cipher_key[WG_KDF_OUTPUT_LEN];
   2009 	struct wg_peer *wgp;
   2010 	struct wg_session *wgs;
   2011 	struct psref psref;
   2012 	int error;
   2013 	uint8_t mac1[WG_MAC_LEN];
   2014 	struct wg_session *wgs_prev;
   2015 	struct mbuf *m;
   2016 
   2017 	wg_algo_mac_mac1(mac1, sizeof(mac1),
   2018 	    wg->wg_pubkey, sizeof(wg->wg_pubkey),
   2019 	    (const uint8_t *)wgmr, offsetof(struct wg_msg_resp, wgmr_mac1));
   2020 
   2021 	/*
   2022 	 * [W] 5.3: Denial of Service Mitigation & Cookies
   2023 	 * "the responder, ..., must always reject messages with an invalid
   2024 	 *  msg.mac1"
   2025 	 */
   2026 	if (!consttime_memequal(mac1, wgmr->wgmr_mac1, sizeof(mac1))) {
   2027 		WG_DLOG("mac1 is invalid\n");
   2028 		return;
   2029 	}
   2030 
   2031 	WG_TRACE("resp msg received");
   2032 	wgs = wg_lookup_session_by_index(wg, wgmr->wgmr_receiver, &psref);
   2033 	if (wgs == NULL) {
   2034 		WG_TRACE("No session found");
   2035 		return;
   2036 	}
   2037 
   2038 	wgp = wgs->wgs_peer;
   2039 
   2040 	mutex_enter(wgp->wgp_lock);
   2041 
   2042 	/* If we weren't waiting for a handshake response, drop it.  */
   2043 	if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE) {
   2044 		WG_TRACE("peer sent spurious handshake response, ignoring");
   2045 		goto out;
   2046 	}
   2047 
   2048 	if (__predict_false(wg_is_underload(wg, wgp, WG_MSG_TYPE_RESP))) {
   2049 		WG_TRACE("under load");
   2050 		/*
   2051 		 * [W] 5.3: Denial of Service Mitigation & Cookies
   2052 		 * "the responder, ..., and when under load may reject messages
   2053 		 *  with an invalid msg.mac2.  If the responder receives a
   2054 		 *  message with a valid msg.mac1 yet with an invalid msg.mac2,
   2055 		 *  and is under load, it may respond with a cookie reply
   2056 		 *  message"
   2057 		 */
   2058 		uint8_t zero[WG_MAC_LEN] = {0};
   2059 		if (consttime_memequal(wgmr->wgmr_mac2, zero, sizeof(zero))) {
   2060 			WG_TRACE("sending a cookie message: no cookie included");
   2061 			wg_send_cookie_msg(wg, wgp, wgmr->wgmr_sender,
   2062 			    wgmr->wgmr_mac1, src);
   2063 			goto out;
   2064 		}
   2065 		if (!wgp->wgp_last_sent_cookie_valid) {
   2066 			WG_TRACE("sending a cookie message: no cookie sent ever");
   2067 			wg_send_cookie_msg(wg, wgp, wgmr->wgmr_sender,
   2068 			    wgmr->wgmr_mac1, src);
   2069 			goto out;
   2070 		}
   2071 		uint8_t mac2[WG_MAC_LEN];
   2072 		wg_algo_mac(mac2, sizeof(mac2), wgp->wgp_last_sent_cookie,
   2073 		    WG_COOKIE_LEN, (const uint8_t *)wgmr,
   2074 		    offsetof(struct wg_msg_resp, wgmr_mac2), NULL, 0);
   2075 		if (!consttime_memequal(mac2, wgmr->wgmr_mac2, sizeof(mac2))) {
   2076 			WG_DLOG("mac2 is invalid\n");
   2077 			goto out;
   2078 		}
   2079 		WG_TRACE("under load, but continue to sending");
   2080 	}
   2081 
   2082 	memcpy(hash, wgs->wgs_handshake_hash, sizeof(hash));
   2083 	memcpy(ckey, wgs->wgs_chaining_key, sizeof(ckey));
   2084 
   2085 	/*
   2086 	 * [W] 5.4.3 Second Message: Responder to Initiator
   2087 	 * "When the initiator receives this message, it does the same
   2088 	 *  operations so that its final state variables are identical,
   2089 	 *  replacing the operands of the DH function to produce equivalent
   2090 	 *  values."
   2091 	 *  Note that the following comments of operations are just copies of
   2092 	 *  the initiator's ones.
   2093 	 */
   2094 
   2095 	/* [N] 2.2: "e" */
   2096 	/* Cr := KDF1(Cr, Er^pub) */
   2097 	wg_algo_kdf(ckey, NULL, NULL, ckey, wgmr->wgmr_ephemeral,
   2098 	    sizeof(wgmr->wgmr_ephemeral));
   2099 	/* Hr := HASH(Hr || msg.ephemeral) */
   2100 	wg_algo_hash(hash, wgmr->wgmr_ephemeral, sizeof(wgmr->wgmr_ephemeral));
   2101 
   2102 	WG_DUMP_HASH("ckey", ckey);
   2103 	WG_DUMP_HASH("hash", hash);
   2104 
   2105 	/* [N] 2.2: "ee" */
   2106 	/* Cr := KDF1(Cr, DH(Er^priv, Ei^pub)) */
   2107 	wg_algo_dh_kdf(ckey, NULL, wgs->wgs_ephemeral_key_priv,
   2108 	    wgmr->wgmr_ephemeral);
   2109 
   2110 	/* [N] 2.2: "se" */
   2111 	/* Cr := KDF1(Cr, DH(Er^priv, Si^pub)) */
   2112 	wg_algo_dh_kdf(ckey, NULL, wg->wg_privkey, wgmr->wgmr_ephemeral);
   2113 
   2114 	/* [N] 9.2: "psk" */
   2115     {
   2116 	uint8_t kdfout[WG_KDF_OUTPUT_LEN];
   2117 	/* Cr, r, k := KDF3(Cr, Q) */
   2118 	wg_algo_kdf(ckey, kdfout, cipher_key, ckey, wgp->wgp_psk,
   2119 	    sizeof(wgp->wgp_psk));
   2120 	/* Hr := HASH(Hr || r) */
   2121 	wg_algo_hash(hash, kdfout, sizeof(kdfout));
   2122     }
   2123 
   2124     {
   2125 	uint8_t out[sizeof(wgmr->wgmr_empty)]; /* for safety */
   2126 	/* msg.empty := AEAD(k, 0, e, Hr) */
   2127 	error = wg_algo_aead_dec(out, 0, cipher_key, 0, wgmr->wgmr_empty,
   2128 	    sizeof(wgmr->wgmr_empty), hash, sizeof(hash));
   2129 	WG_DUMP_HASH("wgmr_empty", wgmr->wgmr_empty);
   2130 	if (error != 0) {
   2131 		WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
   2132 		    "%s: peer %s: wg_algo_aead_dec for empty message failed\n",
   2133 		    if_name(&wg->wg_if), wgp->wgp_name);
   2134 		goto out;
   2135 	}
   2136 	/* Hr := HASH(Hr || msg.empty) */
   2137 	wg_algo_hash(hash, wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty));
   2138     }
   2139 
   2140 	memcpy(wgs->wgs_handshake_hash, hash, sizeof(wgs->wgs_handshake_hash));
   2141 	memcpy(wgs->wgs_chaining_key, ckey, sizeof(wgs->wgs_chaining_key));
   2142 	wgs->wgs_remote_index = wgmr->wgmr_sender;
   2143 	WG_DLOG("receiver=%x\n", wgs->wgs_remote_index);
   2144 
   2145 	KASSERTMSG(wgs->wgs_state == WGS_STATE_INIT_ACTIVE, "state=%d",
   2146 	    wgs->wgs_state);
   2147 	wgs->wgs_time_established = time_uptime32;
   2148 	wg_schedule_session_dtor_timer(wgp);
   2149 	wgs->wgs_time_last_data_sent = 0;
   2150 	wgs->wgs_is_initiator = true;
   2151 	WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]:"
   2152 	    " calculate keys as initiator\n",
   2153 	    wgs->wgs_local_index, wgs->wgs_remote_index);
   2154 	wg_calculate_keys(wgs, true);
   2155 	wg_clear_states(wgs);
   2156 
   2157 	/*
   2158 	 * Session is ready to receive data now that we have received
   2159 	 * the responder's response.
   2160 	 *
   2161 	 * Transition from INIT_ACTIVE to ESTABLISHED to publish it to
   2162 	 * the data rx path, wg_handle_msg_data.
   2163 	 */
   2164 	WG_DLOG("session[L=%"PRIx32" R=%"PRIx32" -> WGS_STATE_ESTABLISHED\n",
   2165 	    wgs->wgs_local_index, wgs->wgs_remote_index);
   2166 	atomic_store_release(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
   2167 	WG_TRACE("WGS_STATE_ESTABLISHED");
   2168 
   2169 	callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
   2170 
   2171 	/*
   2172 	 * Session is ready to send data now that we have received the
   2173 	 * responder's response.
   2174 	 *
   2175 	 * Swap the sessions to publish the new one as the stable
   2176 	 * session for the data tx path, wg_output.
   2177 	 */
   2178 	wg_swap_sessions(wgp);
   2179 	KASSERT(wgs == wgp->wgp_session_stable);
   2180 	wgs_prev = wgp->wgp_session_unstable;
   2181 	getnanotime(&wgp->wgp_last_handshake_time);
   2182 	wgp->wgp_handshake_start_time = 0;
   2183 	wgp->wgp_last_sent_mac1_valid = false;
   2184 	wgp->wgp_last_sent_cookie_valid = false;
   2185 
   2186 	wg_update_endpoint_if_necessary(wgp, src);
   2187 
   2188 	/*
   2189 	 * If we had a data packet queued up, send it; otherwise send a
   2190 	 * keepalive message -- either way we have to send something
   2191 	 * immediately or else the responder will never answer.
   2192 	 */
   2193 	if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
   2194 		kpreempt_disable();
   2195 		const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
   2196 		M_SETCTX(m, wgp);
   2197 		if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
   2198 			WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
   2199 			    if_name(&wg->wg_if));
   2200 			m_freem(m);
   2201 		}
   2202 		kpreempt_enable();
   2203 	} else {
   2204 		wg_send_keepalive_msg(wgp, wgs);
   2205 	}
   2206 
   2207 	if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
   2208 		/*
   2209 		 * Transition ESTABLISHED->DESTROYING.  The session
   2210 		 * will remain usable for the data rx path to process
   2211 		 * packets still in flight to us, but we won't use it
   2212 		 * for data tx.
   2213 		 */
   2214 		WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
   2215 		    " -> WGS_STATE_DESTROYING\n",
   2216 		    wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
   2217 		atomic_store_relaxed(&wgs_prev->wgs_state,
   2218 		    WGS_STATE_DESTROYING);
   2219 	} else {
   2220 		KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
   2221 		    "state=%d", wgs_prev->wgs_state);
   2222 	}
   2223 
   2224 out:
   2225 	mutex_exit(wgp->wgp_lock);
   2226 	wg_put_session(wgs, &psref);
   2227 }
   2228 
   2229 static void
   2230 wg_send_handshake_msg_resp(struct wg_softc *wg, struct wg_peer *wgp,
   2231     struct wg_session *wgs, const struct wg_msg_init *wgmi)
   2232 {
   2233 	int error;
   2234 	struct mbuf *m;
   2235 	struct wg_msg_resp *wgmr;
   2236 
   2237 	KASSERT(mutex_owned(wgp->wgp_lock));
   2238 	KASSERT(wgs == wgp->wgp_session_unstable);
   2239 	KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
   2240 	    wgs->wgs_state);
   2241 
   2242 	m = m_gethdr(M_WAIT, MT_DATA);
   2243 	if (sizeof(*wgmr) > MHLEN) {
   2244 		m_clget(m, M_WAIT);
   2245 		CTASSERT(sizeof(*wgmr) <= MCLBYTES);
   2246 	}
   2247 	m->m_pkthdr.len = m->m_len = sizeof(*wgmr);
   2248 	wgmr = mtod(m, struct wg_msg_resp *);
   2249 	wg_fill_msg_resp(wg, wgp, wgs, wgmr, wgmi);
   2250 
   2251 	error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
   2252 	if (error) {
   2253 		WG_DLOG("send_hs_msg failed, error=%d\n", error);
   2254 		return;
   2255 	}
   2256 
   2257 	WG_TRACE("resp msg sent");
   2258 }
   2259 
   2260 static struct wg_peer *
   2261 wg_lookup_peer_by_pubkey(struct wg_softc *wg,
   2262     const uint8_t pubkey[static WG_STATIC_KEY_LEN], struct psref *psref)
   2263 {
   2264 	struct wg_peer *wgp;
   2265 
   2266 	int s = pserialize_read_enter();
   2267 	wgp = thmap_get(wg->wg_peers_bypubkey, pubkey, WG_STATIC_KEY_LEN);
   2268 	if (wgp != NULL)
   2269 		wg_get_peer(wgp, psref);
   2270 	pserialize_read_exit(s);
   2271 
   2272 	return wgp;
   2273 }
   2274 
   2275 static void
   2276 wg_fill_msg_cookie(struct wg_softc *wg, struct wg_peer *wgp,
   2277     struct wg_msg_cookie *wgmc, const uint32_t sender,
   2278     const uint8_t mac1[static WG_MAC_LEN], const struct sockaddr *src)
   2279 {
   2280 	uint8_t cookie[WG_COOKIE_LEN];
   2281 	uint8_t key[WG_HASH_LEN];
   2282 	uint8_t addr[sizeof(struct in6_addr)];
   2283 	size_t addrlen;
   2284 	uint16_t uh_sport; /* be */
   2285 
   2286 	KASSERT(mutex_owned(wgp->wgp_lock));
   2287 
   2288 	wgmc->wgmc_type = htole32(WG_MSG_TYPE_COOKIE);
   2289 	wgmc->wgmc_receiver = sender;
   2290 	cprng_fast(wgmc->wgmc_salt, sizeof(wgmc->wgmc_salt));
   2291 
   2292 	/*
   2293 	 * [W] 5.4.7: Under Load: Cookie Reply Message
   2294 	 * "The secret variable, Rm, changes every two minutes to a
   2295 	 * random value"
   2296 	 */
   2297 	if ((time_uptime - wgp->wgp_last_cookiesecret_time) >
   2298 	    WG_COOKIESECRET_TIME) {
   2299 		cprng_strong(kern_cprng, wgp->wgp_cookiesecret,
   2300 		    sizeof(wgp->wgp_cookiesecret), 0);
   2301 		wgp->wgp_last_cookiesecret_time = time_uptime;
   2302 	}
   2303 
   2304 	switch (src->sa_family) {
   2305 #ifdef INET
   2306 	case AF_INET: {
   2307 		const struct sockaddr_in *sin = satocsin(src);
   2308 		addrlen = sizeof(sin->sin_addr);
   2309 		memcpy(addr, &sin->sin_addr, addrlen);
   2310 		uh_sport = sin->sin_port;
   2311 		break;
   2312 	    }
   2313 #endif
   2314 #ifdef INET6
   2315 	case AF_INET6: {
   2316 		const struct sockaddr_in6 *sin6 = satocsin6(src);
   2317 		addrlen = sizeof(sin6->sin6_addr);
   2318 		memcpy(addr, &sin6->sin6_addr, addrlen);
   2319 		uh_sport = sin6->sin6_port;
   2320 		break;
   2321 	    }
   2322 #endif
   2323 	default:
   2324 		panic("invalid af=%d", src->sa_family);
   2325 	}
   2326 
   2327 	wg_algo_mac(cookie, sizeof(cookie),
   2328 	    wgp->wgp_cookiesecret, sizeof(wgp->wgp_cookiesecret),
   2329 	    addr, addrlen, (const uint8_t *)&uh_sport, sizeof(uh_sport));
   2330 	wg_algo_mac_cookie(key, sizeof(key), wg->wg_pubkey,
   2331 	    sizeof(wg->wg_pubkey));
   2332 	wg_algo_xaead_enc(wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie), key,
   2333 	    cookie, sizeof(cookie), mac1, WG_MAC_LEN, wgmc->wgmc_salt);
   2334 
   2335 	/* Need to store to calculate mac2 */
   2336 	memcpy(wgp->wgp_last_sent_cookie, cookie, sizeof(cookie));
   2337 	wgp->wgp_last_sent_cookie_valid = true;
   2338 }
   2339 
   2340 static void
   2341 wg_send_cookie_msg(struct wg_softc *wg, struct wg_peer *wgp,
   2342     const uint32_t sender, const uint8_t mac1[static WG_MAC_LEN],
   2343     const struct sockaddr *src)
   2344 {
   2345 	int error;
   2346 	struct mbuf *m;
   2347 	struct wg_msg_cookie *wgmc;
   2348 
   2349 	KASSERT(mutex_owned(wgp->wgp_lock));
   2350 
   2351 	m = m_gethdr(M_WAIT, MT_DATA);
   2352 	if (sizeof(*wgmc) > MHLEN) {
   2353 		m_clget(m, M_WAIT);
   2354 		CTASSERT(sizeof(*wgmc) <= MCLBYTES);
   2355 	}
   2356 	m->m_pkthdr.len = m->m_len = sizeof(*wgmc);
   2357 	wgmc = mtod(m, struct wg_msg_cookie *);
   2358 	wg_fill_msg_cookie(wg, wgp, wgmc, sender, mac1, src);
   2359 
   2360 	error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
   2361 	if (error) {
   2362 		WG_DLOG("send_hs_msg failed, error=%d\n", error);
   2363 		return;
   2364 	}
   2365 
   2366 	WG_TRACE("cookie msg sent");
   2367 }
   2368 
   2369 static bool
   2370 wg_is_underload(struct wg_softc *wg, struct wg_peer *wgp, int msgtype)
   2371 {
   2372 #ifdef WG_DEBUG_PARAMS
   2373 	if (wg_force_underload)
   2374 		return true;
   2375 #endif
   2376 
   2377 	/*
   2378 	 * XXX we don't have a means of a load estimation.  The purpose of
   2379 	 * the mechanism is a DoS mitigation, so we consider frequent handshake
   2380 	 * messages as (a kind of) load; if a message of the same type comes
   2381 	 * to a peer within 1 second, we consider we are under load.
   2382 	 */
   2383 	time_t last = wgp->wgp_last_msg_received_time[msgtype];
   2384 	wgp->wgp_last_msg_received_time[msgtype] = time_uptime;
   2385 	return (time_uptime - last) == 0;
   2386 }
   2387 
   2388 static void
   2389 wg_calculate_keys(struct wg_session *wgs, const bool initiator)
   2390 {
   2391 
   2392 	KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
   2393 
   2394 	/*
   2395 	 * [W] 5.4.5: Ti^send = Tr^recv, Ti^recv = Tr^send := KDF2(Ci = Cr, e)
   2396 	 */
   2397 	if (initiator) {
   2398 		wg_algo_kdf(wgs->wgs_tkey_send, wgs->wgs_tkey_recv, NULL,
   2399 		    wgs->wgs_chaining_key, NULL, 0);
   2400 	} else {
   2401 		wg_algo_kdf(wgs->wgs_tkey_recv, wgs->wgs_tkey_send, NULL,
   2402 		    wgs->wgs_chaining_key, NULL, 0);
   2403 	}
   2404 	WG_DUMP_HASH("wgs_tkey_send", wgs->wgs_tkey_send);
   2405 	WG_DUMP_HASH("wgs_tkey_recv", wgs->wgs_tkey_recv);
   2406 }
   2407 
   2408 static uint64_t
   2409 wg_session_get_send_counter(struct wg_session *wgs)
   2410 {
   2411 #ifdef __HAVE_ATOMIC64_LOADSTORE
   2412 	return atomic_load_relaxed(&wgs->wgs_send_counter);
   2413 #else
   2414 	uint64_t send_counter;
   2415 
   2416 	mutex_enter(&wgs->wgs_send_counter_lock);
   2417 	send_counter = wgs->wgs_send_counter;
   2418 	mutex_exit(&wgs->wgs_send_counter_lock);
   2419 
   2420 	return send_counter;
   2421 #endif
   2422 }
   2423 
   2424 static uint64_t
   2425 wg_session_inc_send_counter(struct wg_session *wgs)
   2426 {
   2427 #ifdef __HAVE_ATOMIC64_LOADSTORE
   2428 	return atomic_inc_64_nv(&wgs->wgs_send_counter) - 1;
   2429 #else
   2430 	uint64_t send_counter;
   2431 
   2432 	mutex_enter(&wgs->wgs_send_counter_lock);
   2433 	send_counter = wgs->wgs_send_counter++;
   2434 	mutex_exit(&wgs->wgs_send_counter_lock);
   2435 
   2436 	return send_counter;
   2437 #endif
   2438 }
   2439 
   2440 static void
   2441 wg_clear_states(struct wg_session *wgs)
   2442 {
   2443 
   2444 	KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
   2445 
   2446 	wgs->wgs_send_counter = 0;
   2447 	sliwin_reset(&wgs->wgs_recvwin->window);
   2448 
   2449 #define wgs_clear(v)	explicit_memset(wgs->wgs_##v, 0, sizeof(wgs->wgs_##v))
   2450 	wgs_clear(handshake_hash);
   2451 	wgs_clear(chaining_key);
   2452 	wgs_clear(ephemeral_key_pub);
   2453 	wgs_clear(ephemeral_key_priv);
   2454 	wgs_clear(ephemeral_key_peer);
   2455 #undef wgs_clear
   2456 }
   2457 
   2458 static struct wg_session *
   2459 wg_lookup_session_by_index(struct wg_softc *wg, const uint32_t index,
   2460     struct psref *psref)
   2461 {
   2462 	struct wg_session *wgs;
   2463 
   2464 	int s = pserialize_read_enter();
   2465 	wgs = thmap_get(wg->wg_sessions_byindex, &index, sizeof index);
   2466 	if (wgs != NULL) {
   2467 		uint32_t oindex __diagused =
   2468 		    atomic_load_relaxed(&wgs->wgs_local_index);
   2469 		KASSERTMSG(index == oindex,
   2470 		    "index=%"PRIx32" wgs->wgs_local_index=%"PRIx32,
   2471 		    index, oindex);
   2472 		psref_acquire(psref, &wgs->wgs_psref, wg_psref_class);
   2473 	}
   2474 	pserialize_read_exit(s);
   2475 
   2476 	return wgs;
   2477 }
   2478 
   2479 static void
   2480 wg_send_keepalive_msg(struct wg_peer *wgp, struct wg_session *wgs)
   2481 {
   2482 	struct mbuf *m;
   2483 
   2484 	/*
   2485 	 * [W] 6.5 Passive Keepalive
   2486 	 * "A keepalive message is simply a transport data message with
   2487 	 *  a zero-length encapsulated encrypted inner-packet."
   2488 	 */
   2489 	WG_TRACE("");
   2490 	m = m_gethdr(M_WAIT, MT_DATA);
   2491 	wg_send_data_msg(wgp, wgs, m);
   2492 }
   2493 
   2494 static bool
   2495 wg_need_to_send_init_message(struct wg_session *wgs)
   2496 {
   2497 	/*
   2498 	 * [W] 6.2 Transport Message Limits
   2499 	 * "if a peer is the initiator of a current secure session,
   2500 	 *  WireGuard will send a handshake initiation message to begin
   2501 	 *  a new secure session ... if after receiving a transport data
   2502 	 *  message, the current secure session is (REJECT-AFTER-TIME 
   2503 	 *  KEEPALIVE-TIMEOUT  REKEY-TIMEOUT) seconds old and it has
   2504 	 *  not yet acted upon this event."
   2505 	 */
   2506 	return wgs->wgs_is_initiator &&
   2507 	    atomic_load_relaxed(&wgs->wgs_time_last_data_sent) == 0 &&
   2508 	    ((time_uptime32 -
   2509 		atomic_load_relaxed(&wgs->wgs_time_established)) >=
   2510 		(wg_reject_after_time - wg_keepalive_timeout -
   2511 		    wg_rekey_timeout));
   2512 }
   2513 
   2514 static void
   2515 wg_schedule_peer_task(struct wg_peer *wgp, unsigned int task)
   2516 {
   2517 
   2518 	mutex_enter(wgp->wgp_intr_lock);
   2519 	WG_DLOG("tasks=%d, task=%d\n", wgp->wgp_tasks, task);
   2520 	if (wgp->wgp_tasks == 0)
   2521 		/*
   2522 		 * XXX If the current CPU is already loaded -- e.g., if
   2523 		 * there's already a bunch of handshakes queued up --
   2524 		 * consider tossing this over to another CPU to
   2525 		 * distribute the load.
   2526 		 */
   2527 		workqueue_enqueue(wg_wq, &wgp->wgp_work, NULL);
   2528 	wgp->wgp_tasks |= task;
   2529 	mutex_exit(wgp->wgp_intr_lock);
   2530 }
   2531 
   2532 static void
   2533 wg_change_endpoint(struct wg_peer *wgp, const struct sockaddr *new)
   2534 {
   2535 	struct wg_sockaddr *wgsa_prev;
   2536 
   2537 	WG_TRACE("Changing endpoint");
   2538 
   2539 	memcpy(wgp->wgp_endpoint0, new, new->sa_len);
   2540 	wgsa_prev = wgp->wgp_endpoint;
   2541 	atomic_store_release(&wgp->wgp_endpoint, wgp->wgp_endpoint0);
   2542 	wgp->wgp_endpoint0 = wgsa_prev;
   2543 	atomic_store_release(&wgp->wgp_endpoint_available, true);
   2544 
   2545 	wg_schedule_peer_task(wgp, WGP_TASK_ENDPOINT_CHANGED);
   2546 }
   2547 
   2548 static bool
   2549 wg_validate_inner_packet(const char *packet, size_t decrypted_len, int *af)
   2550 {
   2551 	uint16_t packet_len;
   2552 	const struct ip *ip;
   2553 
   2554 	if (__predict_false(decrypted_len < sizeof(*ip))) {
   2555 		WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
   2556 		    sizeof(*ip));
   2557 		return false;
   2558 	}
   2559 
   2560 	ip = (const struct ip *)packet;
   2561 	if (ip->ip_v == 4)
   2562 		*af = AF_INET;
   2563 	else if (ip->ip_v == 6)
   2564 		*af = AF_INET6;
   2565 	else {
   2566 		WG_DLOG("ip_v=%d\n", ip->ip_v);
   2567 		return false;
   2568 	}
   2569 
   2570 	WG_DLOG("af=%d\n", *af);
   2571 
   2572 	switch (*af) {
   2573 #ifdef INET
   2574 	case AF_INET:
   2575 		packet_len = ntohs(ip->ip_len);
   2576 		break;
   2577 #endif
   2578 #ifdef INET6
   2579 	case AF_INET6: {
   2580 		const struct ip6_hdr *ip6;
   2581 
   2582 		if (__predict_false(decrypted_len < sizeof(*ip6))) {
   2583 			WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
   2584 			    sizeof(*ip6));
   2585 			return false;
   2586 		}
   2587 
   2588 		ip6 = (const struct ip6_hdr *)packet;
   2589 		packet_len = sizeof(*ip6) + ntohs(ip6->ip6_plen);
   2590 		break;
   2591 	}
   2592 #endif
   2593 	default:
   2594 		return false;
   2595 	}
   2596 
   2597 	if (packet_len > decrypted_len) {
   2598 		WG_DLOG("packet_len %u > decrypted_len %zu\n", packet_len,
   2599 		    decrypted_len);
   2600 		return false;
   2601 	}
   2602 
   2603 	return true;
   2604 }
   2605 
   2606 static bool
   2607 wg_validate_route(struct wg_softc *wg, struct wg_peer *wgp_expected,
   2608     int af, char *packet)
   2609 {
   2610 	struct sockaddr_storage ss;
   2611 	struct sockaddr *sa;
   2612 	struct psref psref;
   2613 	struct wg_peer *wgp;
   2614 	bool ok;
   2615 
   2616 	/*
   2617 	 * II CRYPTOKEY ROUTING
   2618 	 * "it will only accept it if its source IP resolves in the
   2619 	 *  table to the public key used in the secure session for
   2620 	 *  decrypting it."
   2621 	 */
   2622 
   2623 	switch (af) {
   2624 #ifdef INET
   2625 	case AF_INET: {
   2626 		const struct ip *ip = (const struct ip *)packet;
   2627 		struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
   2628 		sockaddr_in_init(sin, &ip->ip_src, 0);
   2629 		sa = sintosa(sin);
   2630 		break;
   2631 	}
   2632 #endif
   2633 #ifdef INET6
   2634 	case AF_INET6: {
   2635 		const struct ip6_hdr *ip6 = (const struct ip6_hdr *)packet;
   2636 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
   2637 		sockaddr_in6_init(sin6, &ip6->ip6_src, 0, 0, 0);
   2638 		sa = sin6tosa(sin6);
   2639 		break;
   2640 	}
   2641 #endif
   2642 	default:
   2643 		__USE(ss);
   2644 		return false;
   2645 	}
   2646 
   2647 	wgp = wg_pick_peer_by_sa(wg, sa, &psref);
   2648 	ok = (wgp == wgp_expected);
   2649 	if (wgp != NULL)
   2650 		wg_put_peer(wgp, &psref);
   2651 
   2652 	return ok;
   2653 }
   2654 
   2655 static void
   2656 wg_session_dtor_timer(void *arg)
   2657 {
   2658 	struct wg_peer *wgp = arg;
   2659 
   2660 	WG_TRACE("enter");
   2661 
   2662 	wg_schedule_session_dtor_timer(wgp);
   2663 	wg_schedule_peer_task(wgp, WGP_TASK_DESTROY_PREV_SESSION);
   2664 }
   2665 
   2666 static void
   2667 wg_schedule_session_dtor_timer(struct wg_peer *wgp)
   2668 {
   2669 
   2670 	/*
   2671 	 * If the periodic session destructor is already pending to
   2672 	 * handle the previous session, that's fine -- leave it in
   2673 	 * place; it will be scheduled again.
   2674 	 */
   2675 	if (callout_pending(&wgp->wgp_session_dtor_timer)) {
   2676 		WG_DLOG("session dtor already pending\n");
   2677 		return;
   2678 	}
   2679 
   2680 	WG_DLOG("scheduling session dtor in %u secs\n", wg_reject_after_time);
   2681 	callout_schedule(&wgp->wgp_session_dtor_timer,
   2682 	    wg_reject_after_time*hz);
   2683 }
   2684 
   2685 static bool
   2686 sockaddr_port_match(const struct sockaddr *sa1, const struct sockaddr *sa2)
   2687 {
   2688 	if (sa1->sa_family != sa2->sa_family)
   2689 		return false;
   2690 
   2691 	switch (sa1->sa_family) {
   2692 #ifdef INET
   2693 	case AF_INET:
   2694 		return satocsin(sa1)->sin_port == satocsin(sa2)->sin_port;
   2695 #endif
   2696 #ifdef INET6
   2697 	case AF_INET6:
   2698 		return satocsin6(sa1)->sin6_port == satocsin6(sa2)->sin6_port;
   2699 #endif
   2700 	default:
   2701 		return false;
   2702 	}
   2703 }
   2704 
   2705 static void
   2706 wg_update_endpoint_if_necessary(struct wg_peer *wgp,
   2707     const struct sockaddr *src)
   2708 {
   2709 	struct wg_sockaddr *wgsa;
   2710 	struct psref psref;
   2711 
   2712 	wgsa = wg_get_endpoint_sa(wgp, &psref);
   2713 
   2714 #ifdef WG_DEBUG_LOG
   2715 	char oldaddr[128], newaddr[128];
   2716 	sockaddr_format(wgsatosa(wgsa), oldaddr, sizeof(oldaddr));
   2717 	sockaddr_format(src, newaddr, sizeof(newaddr));
   2718 	WG_DLOG("old=%s, new=%s\n", oldaddr, newaddr);
   2719 #endif
   2720 
   2721 	/*
   2722 	 * III: "Since the packet has authenticated correctly, the source IP of
   2723 	 * the outer UDP/IP packet is used to update the endpoint for peer..."
   2724 	 */
   2725 	if (__predict_false(sockaddr_cmp(src, wgsatosa(wgsa)) != 0 ||
   2726 		!sockaddr_port_match(src, wgsatosa(wgsa)))) {
   2727 		/* XXX We can't change the endpoint twice in a short period */
   2728 		if (atomic_swap_uint(&wgp->wgp_endpoint_changing, 1) == 0) {
   2729 			wg_change_endpoint(wgp, src);
   2730 		}
   2731 	}
   2732 
   2733 	wg_put_sa(wgp, wgsa, &psref);
   2734 }
   2735 
   2736 static void __noinline
   2737 wg_handle_msg_data(struct wg_softc *wg, struct mbuf *m,
   2738     const struct sockaddr *src)
   2739 {
   2740 	struct wg_msg_data *wgmd;
   2741 	char *encrypted_buf = NULL, *decrypted_buf;
   2742 	size_t encrypted_len, decrypted_len;
   2743 	struct wg_session *wgs;
   2744 	struct wg_peer *wgp;
   2745 	int state;
   2746 	uint32_t age;
   2747 	size_t mlen;
   2748 	struct psref psref;
   2749 	int error, af;
   2750 	bool success, free_encrypted_buf = false, ok;
   2751 	struct mbuf *n;
   2752 
   2753 	KASSERT(m->m_len >= sizeof(struct wg_msg_data));
   2754 	wgmd = mtod(m, struct wg_msg_data *);
   2755 
   2756 	KASSERT(wgmd->wgmd_type == htole32(WG_MSG_TYPE_DATA));
   2757 	WG_TRACE("data");
   2758 
   2759 	/* Find the putative session, or drop.  */
   2760 	wgs = wg_lookup_session_by_index(wg, wgmd->wgmd_receiver, &psref);
   2761 	if (wgs == NULL) {
   2762 		WG_TRACE("No session found");
   2763 		m_freem(m);
   2764 		return;
   2765 	}
   2766 
   2767 	/*
   2768 	 * We are only ready to handle data when in INIT_PASSIVE,
   2769 	 * ESTABLISHED, or DESTROYING.  All transitions out of that
   2770 	 * state dissociate the session index and drain psrefs.
   2771 	 *
   2772 	 * atomic_load_acquire matches atomic_store_release in either
   2773 	 * wg_handle_msg_init or wg_handle_msg_resp.  (The transition
   2774 	 * INIT_PASSIVE to ESTABLISHED in wg_task_establish_session
   2775 	 * doesn't make a difference for this rx path.)
   2776 	 */
   2777 	state = atomic_load_acquire(&wgs->wgs_state);
   2778 	switch (state) {
   2779 	case WGS_STATE_UNKNOWN:
   2780 	case WGS_STATE_INIT_ACTIVE:
   2781 		WG_TRACE("not yet ready for data");
   2782 		goto out;
   2783 	case WGS_STATE_INIT_PASSIVE:
   2784 	case WGS_STATE_ESTABLISHED:
   2785 	case WGS_STATE_DESTROYING:
   2786 		break;
   2787 	}
   2788 
   2789 	/*
   2790 	 * Reject if the session is too old.
   2791 	 */
   2792 	age = time_uptime32 - atomic_load_relaxed(&wgs->wgs_time_established);
   2793 	if (__predict_false(age >= wg_reject_after_time)) {
   2794 		WG_DLOG("session %"PRIx32" too old, %"PRIu32" sec\n",
   2795 		    wgmd->wgmd_receiver, age);
   2796 	       goto out;
   2797 	}
   2798 
   2799 	/*
   2800 	 * Get the peer, for rate-limited logs (XXX MPSAFE, dtrace) and
   2801 	 * to update the endpoint if authentication succeeds.
   2802 	 */
   2803 	wgp = wgs->wgs_peer;
   2804 
   2805 	/*
   2806 	 * Reject outrageously wrong sequence numbers before doing any
   2807 	 * crypto work or taking any locks.
   2808 	 */
   2809 	error = sliwin_check_fast(&wgs->wgs_recvwin->window,
   2810 	    le64toh(wgmd->wgmd_counter));
   2811 	if (error) {
   2812 		WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
   2813 		    "%s: peer %s: out-of-window packet: %"PRIu64"\n",
   2814 		    if_name(&wg->wg_if), wgp->wgp_name,
   2815 		    le64toh(wgmd->wgmd_counter));
   2816 		goto out;
   2817 	}
   2818 
   2819 	/* Ensure the payload and authenticator are contiguous.  */
   2820 	mlen = m_length(m);
   2821 	encrypted_len = mlen - sizeof(*wgmd);
   2822 	if (encrypted_len < WG_AUTHTAG_LEN) {
   2823 		WG_DLOG("Short encrypted_len: %zu\n", encrypted_len);
   2824 		goto out;
   2825 	}
   2826 	success = m_ensure_contig(&m, sizeof(*wgmd) + encrypted_len);
   2827 	if (success) {
   2828 		encrypted_buf = mtod(m, char *) + sizeof(*wgmd);
   2829 	} else {
   2830 		encrypted_buf = kmem_intr_alloc(encrypted_len, KM_NOSLEEP);
   2831 		if (encrypted_buf == NULL) {
   2832 			WG_DLOG("failed to allocate encrypted_buf\n");
   2833 			goto out;
   2834 		}
   2835 		m_copydata(m, sizeof(*wgmd), encrypted_len, encrypted_buf);
   2836 		free_encrypted_buf = true;
   2837 	}
   2838 	/* m_ensure_contig may change m regardless of its result */
   2839 	KASSERT(m->m_len >= sizeof(*wgmd));
   2840 	wgmd = mtod(m, struct wg_msg_data *);
   2841 
   2842 	/*
   2843 	 * Get a buffer for the plaintext.  Add WG_AUTHTAG_LEN to avoid
   2844 	 * a zero-length buffer (XXX).  Drop if plaintext is longer
   2845 	 * than MCLBYTES (XXX).
   2846 	 */
   2847 	decrypted_len = encrypted_len - WG_AUTHTAG_LEN;
   2848 	if (decrypted_len > MCLBYTES) {
   2849 		/* FIXME handle larger data than MCLBYTES */
   2850 		WG_DLOG("couldn't handle larger data than MCLBYTES\n");
   2851 		goto out;
   2852 	}
   2853 	n = wg_get_mbuf(0, decrypted_len + WG_AUTHTAG_LEN);
   2854 	if (n == NULL) {
   2855 		WG_DLOG("wg_get_mbuf failed\n");
   2856 		goto out;
   2857 	}
   2858 	decrypted_buf = mtod(n, char *);
   2859 
   2860 	/* Decrypt and verify the packet.  */
   2861 	WG_DLOG("mlen=%zu, encrypted_len=%zu\n", mlen, encrypted_len);
   2862 	error = wg_algo_aead_dec(decrypted_buf,
   2863 	    encrypted_len - WG_AUTHTAG_LEN /* can be 0 */,
   2864 	    wgs->wgs_tkey_recv, le64toh(wgmd->wgmd_counter), encrypted_buf,
   2865 	    encrypted_len, NULL, 0);
   2866 	if (error != 0) {
   2867 		WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
   2868 		    "%s: peer %s: failed to wg_algo_aead_dec\n",
   2869 		    if_name(&wg->wg_if), wgp->wgp_name);
   2870 		m_freem(n);
   2871 		goto out;
   2872 	}
   2873 	WG_DLOG("outsize=%u\n", (u_int)decrypted_len);
   2874 
   2875 	/* Packet is genuine.  Reject it if a replay or just too old.  */
   2876 	mutex_enter(&wgs->wgs_recvwin->lock);
   2877 	error = sliwin_update(&wgs->wgs_recvwin->window,
   2878 	    le64toh(wgmd->wgmd_counter));
   2879 	mutex_exit(&wgs->wgs_recvwin->lock);
   2880 	if (error) {
   2881 		WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
   2882 		    "%s: peer %s: replay or out-of-window packet: %"PRIu64"\n",
   2883 		    if_name(&wg->wg_if), wgp->wgp_name,
   2884 		    le64toh(wgmd->wgmd_counter));
   2885 		m_freem(n);
   2886 		goto out;
   2887 	}
   2888 
   2889 	/* We're done with m now; free it and chuck the pointers.  */
   2890 	m_freem(m);
   2891 	m = NULL;
   2892 	wgmd = NULL;
   2893 
   2894 	/*
   2895 	 * The packet is genuine.  Update the peer's endpoint if the
   2896 	 * source address changed.
   2897 	 *
   2898 	 * XXX How to prevent DoS by replaying genuine packets from the
   2899 	 * wrong source address?
   2900 	 */
   2901 	wg_update_endpoint_if_necessary(wgp, src);
   2902 
   2903 	/*
   2904 	 * Validate the encapsulated packet header and get the address
   2905 	 * family, or drop.
   2906 	 */
   2907 	ok = wg_validate_inner_packet(decrypted_buf, decrypted_len, &af);
   2908 	if (!ok) {
   2909 		m_freem(n);
   2910 		goto update_state;
   2911 	}
   2912 
   2913 	/* Submit it into our network stack if routable.  */
   2914 	ok = wg_validate_route(wg, wgp, af, decrypted_buf);
   2915 	if (ok) {
   2916 		wg->wg_ops->input(&wg->wg_if, n, af);
   2917 	} else {
   2918 		char addrstr[INET6_ADDRSTRLEN];
   2919 		memset(addrstr, 0, sizeof(addrstr));
   2920 		switch (af) {
   2921 #ifdef INET
   2922 		case AF_INET: {
   2923 			const struct ip *ip = (const struct ip *)decrypted_buf;
   2924 			IN_PRINT(addrstr, &ip->ip_src);
   2925 			break;
   2926 		}
   2927 #endif
   2928 #ifdef INET6
   2929 		case AF_INET6: {
   2930 			const struct ip6_hdr *ip6 =
   2931 			    (const struct ip6_hdr *)decrypted_buf;
   2932 			IN6_PRINT(addrstr, &ip6->ip6_src);
   2933 			break;
   2934 		}
   2935 #endif
   2936 		default:
   2937 			panic("invalid af=%d", af);
   2938 		}
   2939 		WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
   2940 		    "%s: peer %s: invalid source address (%s)\n",
   2941 		    if_name(&wg->wg_if), wgp->wgp_name, addrstr);
   2942 		m_freem(n);
   2943 		/*
   2944 		 * The inner address is invalid however the session is valid
   2945 		 * so continue the session processing below.
   2946 		 */
   2947 	}
   2948 	n = NULL;
   2949 
   2950 update_state:
   2951 	/* Update the state machine if necessary.  */
   2952 	if (__predict_false(state == WGS_STATE_INIT_PASSIVE)) {
   2953 		/*
   2954 		 * We were waiting for the initiator to send their
   2955 		 * first data transport message, and that has happened.
   2956 		 * Schedule a task to establish this session.
   2957 		 */
   2958 		wg_schedule_peer_task(wgp, WGP_TASK_ESTABLISH_SESSION);
   2959 	} else {
   2960 		if (__predict_false(wg_need_to_send_init_message(wgs))) {
   2961 			wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   2962 		}
   2963 		/*
   2964 		 * [W] 6.5 Passive Keepalive
   2965 		 * "If a peer has received a validly-authenticated transport
   2966 		 *  data message (section 5.4.6), but does not have any packets
   2967 		 *  itself to send back for KEEPALIVE-TIMEOUT seconds, it sends
   2968 		 *  a keepalive message."
   2969 		 */
   2970 		const uint32_t now = time_uptime32;
   2971 		const uint32_t time_last_data_sent =
   2972 		    atomic_load_relaxed(&wgs->wgs_time_last_data_sent);
   2973 		WG_DLOG("time_uptime32=%"PRIu32
   2974 		    " wgs_time_last_data_sent=%"PRIu32"\n",
   2975 		    now, time_last_data_sent);
   2976 		if ((now - time_last_data_sent) >= wg_keepalive_timeout) {
   2977 			WG_TRACE("Schedule sending keepalive message");
   2978 			/*
   2979 			 * We can't send a keepalive message here to avoid
   2980 			 * a deadlock;  we already hold the solock of a socket
   2981 			 * that is used to send the message.
   2982 			 */
   2983 			wg_schedule_peer_task(wgp,
   2984 			    WGP_TASK_SEND_KEEPALIVE_MESSAGE);
   2985 		}
   2986 	}
   2987 out:
   2988 	wg_put_session(wgs, &psref);
   2989 	m_freem(m);
   2990 	if (free_encrypted_buf)
   2991 		kmem_intr_free(encrypted_buf, encrypted_len);
   2992 }
   2993 
   2994 static void __noinline
   2995 wg_handle_msg_cookie(struct wg_softc *wg, const struct wg_msg_cookie *wgmc)
   2996 {
   2997 	struct wg_session *wgs;
   2998 	struct wg_peer *wgp;
   2999 	struct psref psref;
   3000 	int error;
   3001 	uint8_t key[WG_HASH_LEN];
   3002 	uint8_t cookie[WG_COOKIE_LEN];
   3003 
   3004 	WG_TRACE("cookie msg received");
   3005 
   3006 	/* Find the putative session.  */
   3007 	wgs = wg_lookup_session_by_index(wg, wgmc->wgmc_receiver, &psref);
   3008 	if (wgs == NULL) {
   3009 		WG_TRACE("No session found");
   3010 		return;
   3011 	}
   3012 
   3013 	/* Lock the peer so we can update the cookie state.  */
   3014 	wgp = wgs->wgs_peer;
   3015 	mutex_enter(wgp->wgp_lock);
   3016 
   3017 	if (!wgp->wgp_last_sent_mac1_valid) {
   3018 		WG_TRACE("No valid mac1 sent (or expired)");
   3019 		goto out;
   3020 	}
   3021 
   3022 	/*
   3023 	 * wgp_last_sent_mac1_valid is only set to true when we are
   3024 	 * transitioning to INIT_ACTIVE or INIT_PASSIVE, and always
   3025 	 * cleared on transition out of them.
   3026 	 */
   3027 	KASSERTMSG((wgs->wgs_state == WGS_STATE_INIT_ACTIVE ||
   3028 		wgs->wgs_state == WGS_STATE_INIT_PASSIVE),
   3029 	    "state=%d", wgs->wgs_state);
   3030 
   3031 	/* Decrypt the cookie and store it for later handshake retry.  */
   3032 	wg_algo_mac_cookie(key, sizeof(key), wgp->wgp_pubkey,
   3033 	    sizeof(wgp->wgp_pubkey));
   3034 	error = wg_algo_xaead_dec(cookie, sizeof(cookie), key,
   3035 	    wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie),
   3036 	    wgp->wgp_last_sent_mac1, sizeof(wgp->wgp_last_sent_mac1),
   3037 	    wgmc->wgmc_salt);
   3038 	if (error != 0) {
   3039 		WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
   3040 		    "%s: peer %s: wg_algo_aead_dec for cookie failed: "
   3041 		    "error=%d\n", if_name(&wg->wg_if), wgp->wgp_name, error);
   3042 		goto out;
   3043 	}
   3044 	/*
   3045 	 * [W] 6.6: Interaction with Cookie Reply System
   3046 	 * "it should simply store the decrypted cookie value from the cookie
   3047 	 *  reply message, and wait for the expiration of the REKEY-TIMEOUT
   3048 	 *  timer for retrying a handshake initiation message."
   3049 	 */
   3050 	wgp->wgp_latest_cookie_time = time_uptime;
   3051 	memcpy(wgp->wgp_latest_cookie, cookie, sizeof(wgp->wgp_latest_cookie));
   3052 out:
   3053 	mutex_exit(wgp->wgp_lock);
   3054 	wg_put_session(wgs, &psref);
   3055 }
   3056 
   3057 static struct mbuf *
   3058 wg_validate_msg_header(struct wg_softc *wg, struct mbuf *m)
   3059 {
   3060 	struct wg_msg wgm;
   3061 	size_t mbuflen;
   3062 	size_t msglen;
   3063 
   3064 	/*
   3065 	 * Get the mbuf chain length.  It is already guaranteed, by
   3066 	 * wg_overudp_cb, to be large enough for a struct wg_msg.
   3067 	 */
   3068 	mbuflen = m_length(m);
   3069 	KASSERT(mbuflen >= sizeof(struct wg_msg));
   3070 
   3071 	/*
   3072 	 * Copy the message header (32-bit message type) out -- we'll
   3073 	 * worry about contiguity and alignment later.
   3074 	 */
   3075 	m_copydata(m, 0, sizeof(wgm), &wgm);
   3076 	switch (le32toh(wgm.wgm_type)) {
   3077 	case WG_MSG_TYPE_INIT:
   3078 		msglen = sizeof(struct wg_msg_init);
   3079 		break;
   3080 	case WG_MSG_TYPE_RESP:
   3081 		msglen = sizeof(struct wg_msg_resp);
   3082 		break;
   3083 	case WG_MSG_TYPE_COOKIE:
   3084 		msglen = sizeof(struct wg_msg_cookie);
   3085 		break;
   3086 	case WG_MSG_TYPE_DATA:
   3087 		msglen = sizeof(struct wg_msg_data);
   3088 		break;
   3089 	default:
   3090 		WG_LOG_RATECHECK(&wg->wg_ppsratecheck, LOG_DEBUG,
   3091 		    "%s: Unexpected msg type: %u\n", if_name(&wg->wg_if),
   3092 		    le32toh(wgm.wgm_type));
   3093 		goto error;
   3094 	}
   3095 
   3096 	/* Verify the mbuf chain is long enough for this type of message.  */
   3097 	if (__predict_false(mbuflen < msglen)) {
   3098 		WG_DLOG("Invalid msg size: mbuflen=%zu type=%u\n", mbuflen,
   3099 		    le32toh(wgm.wgm_type));
   3100 		goto error;
   3101 	}
   3102 
   3103 	/* Make the message header contiguous if necessary.  */
   3104 	if (__predict_false(m->m_len < msglen)) {
   3105 		m = m_pullup(m, msglen);
   3106 		if (m == NULL)
   3107 			return NULL;
   3108 	}
   3109 
   3110 	return m;
   3111 
   3112 error:
   3113 	m_freem(m);
   3114 	return NULL;
   3115 }
   3116 
   3117 static void
   3118 wg_handle_packet(struct wg_softc *wg, struct mbuf *m,
   3119     const struct sockaddr *src)
   3120 {
   3121 	struct wg_msg *wgm;
   3122 
   3123 	KASSERT(curlwp->l_pflag & LP_BOUND);
   3124 
   3125 	m = wg_validate_msg_header(wg, m);
   3126 	if (__predict_false(m == NULL))
   3127 		return;
   3128 
   3129 	KASSERT(m->m_len >= sizeof(struct wg_msg));
   3130 	wgm = mtod(m, struct wg_msg *);
   3131 	switch (le32toh(wgm->wgm_type)) {
   3132 	case WG_MSG_TYPE_INIT:
   3133 		wg_handle_msg_init(wg, (struct wg_msg_init *)wgm, src);
   3134 		break;
   3135 	case WG_MSG_TYPE_RESP:
   3136 		wg_handle_msg_resp(wg, (struct wg_msg_resp *)wgm, src);
   3137 		break;
   3138 	case WG_MSG_TYPE_COOKIE:
   3139 		wg_handle_msg_cookie(wg, (struct wg_msg_cookie *)wgm);
   3140 		break;
   3141 	case WG_MSG_TYPE_DATA:
   3142 		wg_handle_msg_data(wg, m, src);
   3143 		/* wg_handle_msg_data frees m for us */
   3144 		return;
   3145 	default:
   3146 		panic("invalid message type: %d", le32toh(wgm->wgm_type));
   3147 	}
   3148 
   3149 	m_freem(m);
   3150 }
   3151 
   3152 static void
   3153 wg_receive_packets(struct wg_softc *wg, const int af)
   3154 {
   3155 
   3156 	for (;;) {
   3157 		int error, flags;
   3158 		struct socket *so;
   3159 		struct mbuf *m = NULL;
   3160 		struct uio dummy_uio;
   3161 		struct mbuf *paddr = NULL;
   3162 		struct sockaddr *src;
   3163 
   3164 		so = wg_get_so_by_af(wg, af);
   3165 		flags = MSG_DONTWAIT;
   3166 		dummy_uio.uio_resid = 1000000000;
   3167 
   3168 		error = so->so_receive(so, &paddr, &dummy_uio, &m, NULL,
   3169 		    &flags);
   3170 		if (error || m == NULL) {
   3171 			//if (error == EWOULDBLOCK)
   3172 			return;
   3173 		}
   3174 
   3175 		KASSERT(paddr != NULL);
   3176 		KASSERT(paddr->m_len >= sizeof(struct sockaddr));
   3177 		src = mtod(paddr, struct sockaddr *);
   3178 
   3179 		wg_handle_packet(wg, m, src);
   3180 	}
   3181 }
   3182 
   3183 static void
   3184 wg_get_peer(struct wg_peer *wgp, struct psref *psref)
   3185 {
   3186 
   3187 	psref_acquire(psref, &wgp->wgp_psref, wg_psref_class);
   3188 }
   3189 
   3190 static void
   3191 wg_put_peer(struct wg_peer *wgp, struct psref *psref)
   3192 {
   3193 
   3194 	psref_release(psref, &wgp->wgp_psref, wg_psref_class);
   3195 }
   3196 
   3197 static void
   3198 wg_task_send_init_message(struct wg_softc *wg, struct wg_peer *wgp)
   3199 {
   3200 	struct wg_session *wgs;
   3201 
   3202 	WG_TRACE("WGP_TASK_SEND_INIT_MESSAGE");
   3203 
   3204 	KASSERT(mutex_owned(wgp->wgp_lock));
   3205 
   3206 	if (!atomic_load_acquire(&wgp->wgp_endpoint_available)) {
   3207 		WGLOG(LOG_DEBUG, "%s: No endpoint available\n",
   3208 		    if_name(&wg->wg_if));
   3209 		/* XXX should do something? */
   3210 		return;
   3211 	}
   3212 
   3213 	/*
   3214 	 * If we already have an established session, there's no need
   3215 	 * to initiate a new one -- unless the rekey-after-time or
   3216 	 * rekey-after-messages limits have passed.
   3217 	 */
   3218 	wgs = wgp->wgp_session_stable;
   3219 	if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
   3220 	    !atomic_load_relaxed(&wgs->wgs_force_rekey))
   3221 		return;
   3222 
   3223 	/*
   3224 	 * Ensure we're initiating a new session.  If the unstable
   3225 	 * session is already INIT_ACTIVE or INIT_PASSIVE, this does
   3226 	 * nothing.
   3227 	 */
   3228 	wg_send_handshake_msg_init(wg, wgp);
   3229 }
   3230 
   3231 static void
   3232 wg_task_retry_handshake(struct wg_softc *wg, struct wg_peer *wgp)
   3233 {
   3234 	struct wg_session *wgs;
   3235 
   3236 	WG_TRACE("WGP_TASK_RETRY_HANDSHAKE");
   3237 
   3238 	KASSERT(mutex_owned(wgp->wgp_lock));
   3239 	KASSERT(wgp->wgp_handshake_start_time != 0);
   3240 
   3241 	wgs = wgp->wgp_session_unstable;
   3242 	if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE)
   3243 		return;
   3244 
   3245 	/*
   3246 	 * XXX no real need to assign a new index here, but we do need
   3247 	 * to transition to UNKNOWN temporarily
   3248 	 */
   3249 	wg_put_session_index(wg, wgs);
   3250 
   3251 	/* [W] 6.4 Handshake Initiation Retransmission */
   3252 	if ((time_uptime - wgp->wgp_handshake_start_time) >
   3253 	    wg_rekey_attempt_time) {
   3254 		/* Give up handshaking */
   3255 		wgp->wgp_handshake_start_time = 0;
   3256 		WG_TRACE("give up");
   3257 
   3258 		/*
   3259 		 * If a new data packet comes, handshaking will be retried
   3260 		 * and a new session would be established at that time,
   3261 		 * however we don't want to send pending packets then.
   3262 		 */
   3263 		wg_purge_pending_packets(wgp);
   3264 		return;
   3265 	}
   3266 
   3267 	wg_task_send_init_message(wg, wgp);
   3268 }
   3269 
   3270 static void
   3271 wg_task_establish_session(struct wg_softc *wg, struct wg_peer *wgp)
   3272 {
   3273 	struct wg_session *wgs, *wgs_prev;
   3274 	struct mbuf *m;
   3275 
   3276 	KASSERT(mutex_owned(wgp->wgp_lock));
   3277 
   3278 	wgs = wgp->wgp_session_unstable;
   3279 	if (wgs->wgs_state != WGS_STATE_INIT_PASSIVE)
   3280 		/* XXX Can this happen?  */
   3281 		return;
   3282 
   3283 	wgs->wgs_time_last_data_sent = 0;
   3284 	wgs->wgs_is_initiator = false;
   3285 
   3286 	/*
   3287 	 * Session was already ready to receive data.  Transition from
   3288 	 * INIT_PASSIVE to ESTABLISHED just so we can swap the
   3289 	 * sessions.
   3290 	 *
   3291 	 * atomic_store_relaxed because this doesn't affect the data rx
   3292 	 * path, wg_handle_msg_data -- changing from INIT_PASSIVE to
   3293 	 * ESTABLISHED makes no difference to the data rx path, and the
   3294 	 * transition to INIT_PASSIVE with store-release already
   3295 	 * published the state needed by the data rx path.
   3296 	 */
   3297 	WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_ESTABLISHED\n",
   3298 	    wgs->wgs_local_index, wgs->wgs_remote_index);
   3299 	atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
   3300 	WG_TRACE("WGS_STATE_ESTABLISHED");
   3301 
   3302 	/*
   3303 	 * Session is ready to send data too now that we have received
   3304 	 * the peer initiator's first data packet.
   3305 	 *
   3306 	 * Swap the sessions to publish the new one as the stable
   3307 	 * session for the data tx path, wg_output.
   3308 	 */
   3309 	wg_swap_sessions(wgp);
   3310 	KASSERT(wgs == wgp->wgp_session_stable);
   3311 	wgs_prev = wgp->wgp_session_unstable;
   3312 	getnanotime(&wgp->wgp_last_handshake_time);
   3313 	wgp->wgp_handshake_start_time = 0;
   3314 	wgp->wgp_last_sent_mac1_valid = false;
   3315 	wgp->wgp_last_sent_cookie_valid = false;
   3316 
   3317 	/* If we had a data packet queued up, send it.  */
   3318 	if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
   3319 		kpreempt_disable();
   3320 		const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
   3321 		M_SETCTX(m, wgp);
   3322 		if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
   3323 			WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
   3324 			    if_name(&wg->wg_if));
   3325 			m_freem(m);
   3326 		}
   3327 		kpreempt_enable();
   3328 	}
   3329 
   3330 	if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
   3331 		/*
   3332 		 * Transition ESTABLISHED->DESTROYING.  The session
   3333 		 * will remain usable for the data rx path to process
   3334 		 * packets still in flight to us, but we won't use it
   3335 		 * for data tx.
   3336 		 */
   3337 		WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
   3338 		    " -> WGS_STATE_DESTROYING\n",
   3339 		    wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
   3340 		atomic_store_relaxed(&wgs_prev->wgs_state,
   3341 		    WGS_STATE_DESTROYING);
   3342 	} else {
   3343 		KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
   3344 		    "state=%d", wgs_prev->wgs_state);
   3345 		WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
   3346 		    " -> WGS_STATE_UNKNOWN\n",
   3347 		    wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
   3348 		wgs_prev->wgs_local_index = 0; /* paranoia */
   3349 		wgs_prev->wgs_remote_index = 0; /* paranoia */
   3350 		wg_clear_states(wgs_prev); /* paranoia */
   3351 		wgs_prev->wgs_state = WGS_STATE_UNKNOWN;
   3352 	}
   3353 }
   3354 
   3355 static void
   3356 wg_task_endpoint_changed(struct wg_softc *wg, struct wg_peer *wgp)
   3357 {
   3358 
   3359 	WG_TRACE("WGP_TASK_ENDPOINT_CHANGED");
   3360 
   3361 	KASSERT(mutex_owned(wgp->wgp_lock));
   3362 
   3363 	if (atomic_load_relaxed(&wgp->wgp_endpoint_changing)) {
   3364 		pserialize_perform(wgp->wgp_psz);
   3365 		mutex_exit(wgp->wgp_lock);
   3366 		psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref,
   3367 		    wg_psref_class);
   3368 		psref_target_init(&wgp->wgp_endpoint0->wgsa_psref,
   3369 		    wg_psref_class);
   3370 		mutex_enter(wgp->wgp_lock);
   3371 		atomic_store_release(&wgp->wgp_endpoint_changing, 0);
   3372 	}
   3373 }
   3374 
   3375 static void
   3376 wg_task_send_keepalive_message(struct wg_softc *wg, struct wg_peer *wgp)
   3377 {
   3378 	struct wg_session *wgs;
   3379 
   3380 	WG_TRACE("WGP_TASK_SEND_KEEPALIVE_MESSAGE");
   3381 
   3382 	KASSERT(mutex_owned(wgp->wgp_lock));
   3383 
   3384 	wgs = wgp->wgp_session_stable;
   3385 	if (wgs->wgs_state != WGS_STATE_ESTABLISHED)
   3386 		return;
   3387 
   3388 	wg_send_keepalive_msg(wgp, wgs);
   3389 }
   3390 
   3391 static void
   3392 wg_task_destroy_prev_session(struct wg_softc *wg, struct wg_peer *wgp)
   3393 {
   3394 	struct wg_session *wgs;
   3395 	uint32_t age;
   3396 
   3397 	WG_TRACE("WGP_TASK_DESTROY_PREV_SESSION");
   3398 
   3399 	KASSERT(mutex_owned(wgp->wgp_lock));
   3400 
   3401 	/*
   3402 	 * If theres's any previous unstable session, i.e., one that
   3403 	 * was ESTABLISHED and is now DESTROYING, older than
   3404 	 * reject-after-time, destroy it.  Upcoming sessions are still
   3405 	 * in INIT_ACTIVE or INIT_PASSIVE -- we don't touch those here.
   3406 	 *
   3407 	 * No atomic for access to wgs_time_established because it is
   3408 	 * only updated under wgp_lock.
   3409 	 */
   3410 	wgs = wgp->wgp_session_unstable;
   3411 	KASSERT(wgs->wgs_state != WGS_STATE_ESTABLISHED);
   3412 	if (wgs->wgs_state == WGS_STATE_DESTROYING &&
   3413 	    ((age = (time_uptime32 - wgs->wgs_time_established)) >=
   3414 		wg_reject_after_time)) {
   3415 		WG_DLOG("destroying past session %"PRIu32" sec old\n", age);
   3416 		wg_put_session_index(wg, wgs);
   3417 		KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
   3418 		    wgs->wgs_state);
   3419 	}
   3420 
   3421 	/*
   3422 	 * If theres's any ESTABLISHED stable session older than
   3423 	 * reject-after-time, destroy it.  (The stable session can also
   3424 	 * be in UNKNOWN state -- nothing to do in that case)
   3425 	 */
   3426 	wgs = wgp->wgp_session_stable;
   3427 	KASSERT(wgs->wgs_state != WGS_STATE_INIT_ACTIVE);
   3428 	KASSERT(wgs->wgs_state != WGS_STATE_INIT_PASSIVE);
   3429 	KASSERT(wgs->wgs_state != WGS_STATE_DESTROYING);
   3430 	if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
   3431 	    ((age = (time_uptime32 - wgs->wgs_time_established)) >=
   3432 		wg_reject_after_time)) {
   3433 		WG_DLOG("destroying current session %"PRIu32" sec old\n", age);
   3434 		atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_DESTROYING);
   3435 		wg_put_session_index(wg, wgs);
   3436 		KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
   3437 		    wgs->wgs_state);
   3438 	}
   3439 
   3440 	/*
   3441 	 * If there's no sessions left, no need to have the timer run
   3442 	 * until the next time around -- halt it.
   3443 	 *
   3444 	 * It is only ever scheduled with wgp_lock held or in the
   3445 	 * callout itself, and callout_halt prevents rescheudling
   3446 	 * itself, so this never races with rescheduling.
   3447 	 */
   3448 	if (wgp->wgp_session_unstable->wgs_state == WGS_STATE_UNKNOWN &&
   3449 	    wgp->wgp_session_stable->wgs_state == WGS_STATE_UNKNOWN)
   3450 		callout_halt(&wgp->wgp_session_dtor_timer, NULL);
   3451 }
   3452 
   3453 static void
   3454 wg_peer_work(struct work *wk, void *cookie)
   3455 {
   3456 	struct wg_peer *wgp = container_of(wk, struct wg_peer, wgp_work);
   3457 	struct wg_softc *wg = wgp->wgp_sc;
   3458 	unsigned int tasks;
   3459 
   3460 	mutex_enter(wgp->wgp_intr_lock);
   3461 	while ((tasks = wgp->wgp_tasks) != 0) {
   3462 		wgp->wgp_tasks = 0;
   3463 		mutex_exit(wgp->wgp_intr_lock);
   3464 
   3465 		mutex_enter(wgp->wgp_lock);
   3466 		if (ISSET(tasks, WGP_TASK_SEND_INIT_MESSAGE))
   3467 			wg_task_send_init_message(wg, wgp);
   3468 		if (ISSET(tasks, WGP_TASK_RETRY_HANDSHAKE))
   3469 			wg_task_retry_handshake(wg, wgp);
   3470 		if (ISSET(tasks, WGP_TASK_ESTABLISH_SESSION))
   3471 			wg_task_establish_session(wg, wgp);
   3472 		if (ISSET(tasks, WGP_TASK_ENDPOINT_CHANGED))
   3473 			wg_task_endpoint_changed(wg, wgp);
   3474 		if (ISSET(tasks, WGP_TASK_SEND_KEEPALIVE_MESSAGE))
   3475 			wg_task_send_keepalive_message(wg, wgp);
   3476 		if (ISSET(tasks, WGP_TASK_DESTROY_PREV_SESSION))
   3477 			wg_task_destroy_prev_session(wg, wgp);
   3478 		mutex_exit(wgp->wgp_lock);
   3479 
   3480 		mutex_enter(wgp->wgp_intr_lock);
   3481 	}
   3482 	mutex_exit(wgp->wgp_intr_lock);
   3483 }
   3484 
   3485 static void
   3486 wg_job(struct threadpool_job *job)
   3487 {
   3488 	struct wg_softc *wg = container_of(job, struct wg_softc, wg_job);
   3489 	int bound, upcalls;
   3490 
   3491 	mutex_enter(wg->wg_intr_lock);
   3492 	while ((upcalls = wg->wg_upcalls) != 0) {
   3493 		wg->wg_upcalls = 0;
   3494 		mutex_exit(wg->wg_intr_lock);
   3495 		bound = curlwp_bind();
   3496 		if (ISSET(upcalls, WG_UPCALL_INET))
   3497 			wg_receive_packets(wg, AF_INET);
   3498 		if (ISSET(upcalls, WG_UPCALL_INET6))
   3499 			wg_receive_packets(wg, AF_INET6);
   3500 		curlwp_bindx(bound);
   3501 		mutex_enter(wg->wg_intr_lock);
   3502 	}
   3503 	threadpool_job_done(job);
   3504 	mutex_exit(wg->wg_intr_lock);
   3505 }
   3506 
   3507 static int
   3508 wg_bind_port(struct wg_softc *wg, const uint16_t port)
   3509 {
   3510 	int error = 0;
   3511 	uint16_t old_port = wg->wg_listen_port;
   3512 
   3513 	if (port != 0 && old_port == port)
   3514 		return 0;
   3515 
   3516 #ifdef INET
   3517 	struct sockaddr_in _sin, *sin = &_sin;
   3518 	sin->sin_len = sizeof(*sin);
   3519 	sin->sin_family = AF_INET;
   3520 	sin->sin_addr.s_addr = INADDR_ANY;
   3521 	sin->sin_port = htons(port);
   3522 
   3523 	error = sobind(wg->wg_so4, sintosa(sin), curlwp);
   3524 	if (error)
   3525 		return error;
   3526 #endif
   3527 
   3528 #ifdef INET6
   3529 	struct sockaddr_in6 _sin6, *sin6 = &_sin6;
   3530 	sin6->sin6_len = sizeof(*sin6);
   3531 	sin6->sin6_family = AF_INET6;
   3532 	sin6->sin6_addr = in6addr_any;
   3533 	sin6->sin6_port = htons(port);
   3534 
   3535 	error = sobind(wg->wg_so6, sin6tosa(sin6), curlwp);
   3536 	if (error)
   3537 		return error;
   3538 #endif
   3539 
   3540 	wg->wg_listen_port = port;
   3541 
   3542 	return error;
   3543 }
   3544 
   3545 static void
   3546 wg_so_upcall(struct socket *so, void *cookie, int events, int waitflag)
   3547 {
   3548 	struct wg_softc *wg = cookie;
   3549 	int reason;
   3550 
   3551 	reason = (so->so_proto->pr_domain->dom_family == AF_INET) ?
   3552 	    WG_UPCALL_INET :
   3553 	    WG_UPCALL_INET6;
   3554 
   3555 	mutex_enter(wg->wg_intr_lock);
   3556 	wg->wg_upcalls |= reason;
   3557 	threadpool_schedule_job(wg->wg_threadpool, &wg->wg_job);
   3558 	mutex_exit(wg->wg_intr_lock);
   3559 }
   3560 
   3561 static int
   3562 wg_overudp_cb(struct mbuf **mp, int offset, struct socket *so,
   3563     struct sockaddr *src, void *arg)
   3564 {
   3565 	struct wg_softc *wg = arg;
   3566 	struct wg_msg wgm;
   3567 	struct mbuf *m = *mp;
   3568 
   3569 	WG_TRACE("enter");
   3570 
   3571 	/* Verify the mbuf chain is long enough to have a wg msg header.  */
   3572 	KASSERT(offset <= m_length(m));
   3573 	if (__predict_false(m_length(m) - offset < sizeof(struct wg_msg))) {
   3574 		/* drop on the floor */
   3575 		m_freem(m);
   3576 		return -1;
   3577 	}
   3578 
   3579 	/*
   3580 	 * Copy the message header (32-bit message type) out -- we'll
   3581 	 * worry about contiguity and alignment later.
   3582 	 */
   3583 	m_copydata(m, offset, sizeof(struct wg_msg), &wgm);
   3584 	WG_DLOG("type=%d\n", le32toh(wgm.wgm_type));
   3585 
   3586 	/*
   3587 	 * Handle DATA packets promptly as they arrive, if they are in
   3588 	 * an active session.  Other packets may require expensive
   3589 	 * public-key crypto and are not as sensitive to latency, so
   3590 	 * defer them to the worker thread.
   3591 	 */
   3592 	switch (le32toh(wgm.wgm_type)) {
   3593 	case WG_MSG_TYPE_DATA:
   3594 		/* handle immediately */
   3595 		m_adj(m, offset);
   3596 		if (__predict_false(m->m_len < sizeof(struct wg_msg_data))) {
   3597 			m = m_pullup(m, sizeof(struct wg_msg_data));
   3598 			if (m == NULL)
   3599 				return -1;
   3600 		}
   3601 		wg_handle_msg_data(wg, m, src);
   3602 		*mp = NULL;
   3603 		return 1;
   3604 	case WG_MSG_TYPE_INIT:
   3605 	case WG_MSG_TYPE_RESP:
   3606 	case WG_MSG_TYPE_COOKIE:
   3607 		/* pass through to so_receive in wg_receive_packets */
   3608 		return 0;
   3609 	default:
   3610 		/* drop on the floor */
   3611 		m_freem(m);
   3612 		return -1;
   3613 	}
   3614 }
   3615 
   3616 static int
   3617 wg_socreate(struct wg_softc *wg, int af, struct socket **sop)
   3618 {
   3619 	int error;
   3620 	struct socket *so;
   3621 
   3622 	error = socreate(af, &so, SOCK_DGRAM, 0, curlwp, NULL);
   3623 	if (error != 0)
   3624 		return error;
   3625 
   3626 	solock(so);
   3627 	so->so_upcallarg = wg;
   3628 	so->so_upcall = wg_so_upcall;
   3629 	so->so_rcv.sb_flags |= SB_UPCALL;
   3630 	inpcb_register_overudp_cb(sotoinpcb(so), wg_overudp_cb, wg);
   3631 	sounlock(so);
   3632 
   3633 	*sop = so;
   3634 
   3635 	return 0;
   3636 }
   3637 
   3638 static bool
   3639 wg_session_hit_limits(struct wg_session *wgs)
   3640 {
   3641 	uint32_t time_established =
   3642 	    atomic_load_relaxed(&wgs->wgs_time_established);
   3643 
   3644 	/*
   3645 	 * [W] 6.2: Transport Message Limits
   3646 	 * "After REJECT-AFTER-MESSAGES transport data messages or after the
   3647 	 *  current secure session is REJECT-AFTER-TIME seconds old, whichever
   3648 	 *  comes first, WireGuard will refuse to send or receive any more
   3649 	 *  transport data messages using the current secure session, ..."
   3650 	 */
   3651 	KASSERT(time_established != 0 || time_uptime > UINT32_MAX);
   3652 	if ((time_uptime32 - time_established) > wg_reject_after_time) {
   3653 		WG_DLOG("The session hits REJECT_AFTER_TIME\n");
   3654 		return true;
   3655 	} else if (wg_session_get_send_counter(wgs) >
   3656 	    wg_reject_after_messages) {
   3657 		WG_DLOG("The session hits REJECT_AFTER_MESSAGES\n");
   3658 		return true;
   3659 	}
   3660 
   3661 	return false;
   3662 }
   3663 
   3664 static void
   3665 wgintr(void *cookie)
   3666 {
   3667 	struct wg_peer *wgp;
   3668 	struct wg_session *wgs;
   3669 	struct mbuf *m;
   3670 	struct psref psref;
   3671 
   3672 	while ((m = pktq_dequeue(wg_pktq)) != NULL) {
   3673 		wgp = M_GETCTX(m, struct wg_peer *);
   3674 		if ((wgs = wg_get_stable_session(wgp, &psref)) == NULL) {
   3675 			WG_TRACE("no stable session");
   3676 			wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3677 			goto next0;
   3678 		}
   3679 		if (__predict_false(wg_session_hit_limits(wgs))) {
   3680 			WG_TRACE("stable session hit limits");
   3681 			wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3682 			goto next1;
   3683 		}
   3684 		wg_send_data_msg(wgp, wgs, m);
   3685 		m = NULL;	/* consumed */
   3686 next1:		wg_put_session(wgs, &psref);
   3687 next0:		m_freem(m);
   3688 		/* XXX Yield to avoid userland starvation?  */
   3689 	}
   3690 }
   3691 
   3692 static void
   3693 wg_purge_pending_packets(struct wg_peer *wgp)
   3694 {
   3695 	struct mbuf *m;
   3696 
   3697 	m = atomic_swap_ptr(&wgp->wgp_pending, NULL);
   3698 	m_freem(m);
   3699 #ifdef ALTQ
   3700 	wg_start(&wgp->wgp_sc->wg_if);
   3701 #endif
   3702 	pktq_barrier(wg_pktq);
   3703 }
   3704 
   3705 static void
   3706 wg_handshake_timeout_timer(void *arg)
   3707 {
   3708 	struct wg_peer *wgp = arg;
   3709 
   3710 	WG_TRACE("enter");
   3711 
   3712 	wg_schedule_peer_task(wgp, WGP_TASK_RETRY_HANDSHAKE);
   3713 }
   3714 
   3715 static struct wg_peer *
   3716 wg_alloc_peer(struct wg_softc *wg)
   3717 {
   3718 	struct wg_peer *wgp;
   3719 
   3720 	wgp = kmem_zalloc(sizeof(*wgp), KM_SLEEP);
   3721 
   3722 	wgp->wgp_sc = wg;
   3723 	callout_init(&wgp->wgp_handshake_timeout_timer, CALLOUT_MPSAFE);
   3724 	callout_setfunc(&wgp->wgp_handshake_timeout_timer,
   3725 	    wg_handshake_timeout_timer, wgp);
   3726 	callout_init(&wgp->wgp_session_dtor_timer, CALLOUT_MPSAFE);
   3727 	callout_setfunc(&wgp->wgp_session_dtor_timer,
   3728 	    wg_session_dtor_timer, wgp);
   3729 	PSLIST_ENTRY_INIT(wgp, wgp_peerlist_entry);
   3730 	wgp->wgp_endpoint_changing = false;
   3731 	wgp->wgp_endpoint_available = false;
   3732 	wgp->wgp_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3733 	wgp->wgp_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
   3734 	wgp->wgp_psz = pserialize_create();
   3735 	psref_target_init(&wgp->wgp_psref, wg_psref_class);
   3736 
   3737 	wgp->wgp_endpoint = kmem_zalloc(sizeof(*wgp->wgp_endpoint), KM_SLEEP);
   3738 	wgp->wgp_endpoint0 = kmem_zalloc(sizeof(*wgp->wgp_endpoint0), KM_SLEEP);
   3739 	psref_target_init(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
   3740 	psref_target_init(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
   3741 
   3742 	struct wg_session *wgs;
   3743 	wgp->wgp_session_stable =
   3744 	    kmem_zalloc(sizeof(*wgp->wgp_session_stable), KM_SLEEP);
   3745 	wgp->wgp_session_unstable =
   3746 	    kmem_zalloc(sizeof(*wgp->wgp_session_unstable), KM_SLEEP);
   3747 	wgs = wgp->wgp_session_stable;
   3748 	wgs->wgs_peer = wgp;
   3749 	wgs->wgs_state = WGS_STATE_UNKNOWN;
   3750 	psref_target_init(&wgs->wgs_psref, wg_psref_class);
   3751 #ifndef __HAVE_ATOMIC64_LOADSTORE
   3752 	mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
   3753 #endif
   3754 	wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
   3755 	mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
   3756 
   3757 	wgs = wgp->wgp_session_unstable;
   3758 	wgs->wgs_peer = wgp;
   3759 	wgs->wgs_state = WGS_STATE_UNKNOWN;
   3760 	psref_target_init(&wgs->wgs_psref, wg_psref_class);
   3761 #ifndef __HAVE_ATOMIC64_LOADSTORE
   3762 	mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
   3763 #endif
   3764 	wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
   3765 	mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
   3766 
   3767 	return wgp;
   3768 }
   3769 
   3770 static void
   3771 wg_destroy_peer(struct wg_peer *wgp)
   3772 {
   3773 	struct wg_session *wgs;
   3774 	struct wg_softc *wg = wgp->wgp_sc;
   3775 
   3776 	/* Prevent new packets from this peer on any source address.  */
   3777 	rw_enter(wg->wg_rwlock, RW_WRITER);
   3778 	for (int i = 0; i < wgp->wgp_n_allowedips; i++) {
   3779 		struct wg_allowedip *wga = &wgp->wgp_allowedips[i];
   3780 		struct radix_node_head *rnh = wg_rnh(wg, wga->wga_family);
   3781 		struct radix_node *rn;
   3782 
   3783 		KASSERT(rnh != NULL);
   3784 		rn = rnh->rnh_deladdr(&wga->wga_sa_addr,
   3785 		    &wga->wga_sa_mask, rnh);
   3786 		if (rn == NULL) {
   3787 			char addrstr[128];
   3788 			sockaddr_format(&wga->wga_sa_addr, addrstr,
   3789 			    sizeof(addrstr));
   3790 			WGLOG(LOG_WARNING, "%s: Couldn't delete %s",
   3791 			    if_name(&wg->wg_if), addrstr);
   3792 		}
   3793 	}
   3794 	rw_exit(wg->wg_rwlock);
   3795 
   3796 	/* Purge pending packets.  */
   3797 	wg_purge_pending_packets(wgp);
   3798 
   3799 	/* Halt all packet processing and timeouts.  */
   3800 	callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
   3801 	callout_halt(&wgp->wgp_session_dtor_timer, NULL);
   3802 
   3803 	/* Wait for any queued work to complete.  */
   3804 	workqueue_wait(wg_wq, &wgp->wgp_work);
   3805 
   3806 	wgs = wgp->wgp_session_unstable;
   3807 	if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
   3808 		mutex_enter(wgp->wgp_lock);
   3809 		wg_destroy_session(wg, wgs);
   3810 		mutex_exit(wgp->wgp_lock);
   3811 	}
   3812 	mutex_destroy(&wgs->wgs_recvwin->lock);
   3813 	kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
   3814 #ifndef __HAVE_ATOMIC64_LOADSTORE
   3815 	mutex_destroy(&wgs->wgs_send_counter_lock);
   3816 #endif
   3817 	kmem_free(wgs, sizeof(*wgs));
   3818 
   3819 	wgs = wgp->wgp_session_stable;
   3820 	if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
   3821 		mutex_enter(wgp->wgp_lock);
   3822 		wg_destroy_session(wg, wgs);
   3823 		mutex_exit(wgp->wgp_lock);
   3824 	}
   3825 	mutex_destroy(&wgs->wgs_recvwin->lock);
   3826 	kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
   3827 #ifndef __HAVE_ATOMIC64_LOADSTORE
   3828 	mutex_destroy(&wgs->wgs_send_counter_lock);
   3829 #endif
   3830 	kmem_free(wgs, sizeof(*wgs));
   3831 
   3832 	psref_target_destroy(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
   3833 	psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
   3834 	kmem_free(wgp->wgp_endpoint, sizeof(*wgp->wgp_endpoint));
   3835 	kmem_free(wgp->wgp_endpoint0, sizeof(*wgp->wgp_endpoint0));
   3836 
   3837 	pserialize_destroy(wgp->wgp_psz);
   3838 	mutex_obj_free(wgp->wgp_intr_lock);
   3839 	mutex_obj_free(wgp->wgp_lock);
   3840 
   3841 	kmem_free(wgp, sizeof(*wgp));
   3842 }
   3843 
   3844 static void
   3845 wg_destroy_all_peers(struct wg_softc *wg)
   3846 {
   3847 	struct wg_peer *wgp, *wgp0 __diagused;
   3848 	void *garbage_byname, *garbage_bypubkey;
   3849 
   3850 restart:
   3851 	garbage_byname = garbage_bypubkey = NULL;
   3852 	mutex_enter(wg->wg_lock);
   3853 	WG_PEER_WRITER_FOREACH(wgp, wg) {
   3854 		if (wgp->wgp_name[0]) {
   3855 			wgp0 = thmap_del(wg->wg_peers_byname, wgp->wgp_name,
   3856 			    strlen(wgp->wgp_name));
   3857 			KASSERT(wgp0 == wgp);
   3858 			garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
   3859 		}
   3860 		wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
   3861 		    sizeof(wgp->wgp_pubkey));
   3862 		KASSERT(wgp0 == wgp);
   3863 		garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
   3864 		WG_PEER_WRITER_REMOVE(wgp);
   3865 		wg->wg_npeers--;
   3866 		mutex_enter(wgp->wgp_lock);
   3867 		pserialize_perform(wgp->wgp_psz);
   3868 		mutex_exit(wgp->wgp_lock);
   3869 		PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
   3870 		break;
   3871 	}
   3872 	mutex_exit(wg->wg_lock);
   3873 
   3874 	if (wgp == NULL)
   3875 		return;
   3876 
   3877 	psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
   3878 
   3879 	wg_destroy_peer(wgp);
   3880 	thmap_gc(wg->wg_peers_byname, garbage_byname);
   3881 	thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
   3882 
   3883 	goto restart;
   3884 }
   3885 
   3886 static int
   3887 wg_destroy_peer_name(struct wg_softc *wg, const char *name)
   3888 {
   3889 	struct wg_peer *wgp, *wgp0 __diagused;
   3890 	void *garbage_byname, *garbage_bypubkey;
   3891 
   3892 	mutex_enter(wg->wg_lock);
   3893 	wgp = thmap_del(wg->wg_peers_byname, name, strlen(name));
   3894 	if (wgp != NULL) {
   3895 		wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
   3896 		    sizeof(wgp->wgp_pubkey));
   3897 		KASSERT(wgp0 == wgp);
   3898 		garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
   3899 		garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
   3900 		WG_PEER_WRITER_REMOVE(wgp);
   3901 		wg->wg_npeers--;
   3902 		if (wg->wg_npeers == 0)
   3903 			if_link_state_change(&wg->wg_if, LINK_STATE_DOWN);
   3904 		mutex_enter(wgp->wgp_lock);
   3905 		pserialize_perform(wgp->wgp_psz);
   3906 		mutex_exit(wgp->wgp_lock);
   3907 		PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
   3908 	}
   3909 	mutex_exit(wg->wg_lock);
   3910 
   3911 	if (wgp == NULL)
   3912 		return ENOENT;
   3913 
   3914 	psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
   3915 
   3916 	wg_destroy_peer(wgp);
   3917 	thmap_gc(wg->wg_peers_byname, garbage_byname);
   3918 	thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
   3919 
   3920 	return 0;
   3921 }
   3922 
   3923 static int
   3924 wg_if_attach(struct wg_softc *wg)
   3925 {
   3926 
   3927 	wg->wg_if.if_addrlen = 0;
   3928 	wg->wg_if.if_mtu = WG_MTU;
   3929 	wg->wg_if.if_flags = IFF_MULTICAST;
   3930 	wg->wg_if.if_extflags = IFEF_MPSAFE;
   3931 	wg->wg_if.if_ioctl = wg_ioctl;
   3932 	wg->wg_if.if_output = wg_output;
   3933 	wg->wg_if.if_init = wg_init;
   3934 #ifdef ALTQ
   3935 	wg->wg_if.if_start = wg_start;
   3936 #endif
   3937 	wg->wg_if.if_stop = wg_stop;
   3938 	wg->wg_if.if_type = IFT_OTHER;
   3939 	wg->wg_if.if_dlt = DLT_NULL;
   3940 	wg->wg_if.if_softc = wg;
   3941 #ifdef ALTQ
   3942 	IFQ_SET_READY(&wg->wg_if.if_snd);
   3943 #endif
   3944 	if_initialize(&wg->wg_if);
   3945 
   3946 	wg->wg_if.if_link_state = LINK_STATE_DOWN;
   3947 	if_alloc_sadl(&wg->wg_if);
   3948 	if_register(&wg->wg_if);
   3949 
   3950 	bpf_attach(&wg->wg_if, DLT_NULL, sizeof(uint32_t));
   3951 
   3952 	return 0;
   3953 }
   3954 
   3955 static void
   3956 wg_if_detach(struct wg_softc *wg)
   3957 {
   3958 	struct ifnet *ifp = &wg->wg_if;
   3959 
   3960 	bpf_detach(ifp);
   3961 	if_detach(ifp);
   3962 }
   3963 
   3964 static int
   3965 wg_clone_create(struct if_clone *ifc, int unit)
   3966 {
   3967 	struct wg_softc *wg;
   3968 	int error;
   3969 
   3970 	wg_guarantee_initialized();
   3971 
   3972 	error = wg_count_inc();
   3973 	if (error)
   3974 		return error;
   3975 
   3976 	wg = kmem_zalloc(sizeof(*wg), KM_SLEEP);
   3977 
   3978 	if_initname(&wg->wg_if, ifc->ifc_name, unit);
   3979 
   3980 	PSLIST_INIT(&wg->wg_peers);
   3981 	wg->wg_peers_bypubkey = thmap_create(0, NULL, THMAP_NOCOPY);
   3982 	wg->wg_peers_byname = thmap_create(0, NULL, THMAP_NOCOPY);
   3983 	wg->wg_sessions_byindex = thmap_create(0, NULL, THMAP_NOCOPY);
   3984 	wg->wg_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3985 	wg->wg_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
   3986 	wg->wg_rwlock = rw_obj_alloc();
   3987 	threadpool_job_init(&wg->wg_job, wg_job, wg->wg_intr_lock,
   3988 	    "%s", if_name(&wg->wg_if));
   3989 	wg->wg_ops = &wg_ops_rumpkernel;
   3990 
   3991 	error = threadpool_get(&wg->wg_threadpool, PRI_NONE);
   3992 	if (error)
   3993 		goto fail0;
   3994 
   3995 #ifdef INET
   3996 	error = wg_socreate(wg, AF_INET, &wg->wg_so4);
   3997 	if (error)
   3998 		goto fail1;
   3999 	rn_inithead((void **)&wg->wg_rtable_ipv4,
   4000 	    offsetof(struct sockaddr_in, sin_addr) * NBBY);
   4001 #endif
   4002 #ifdef INET6
   4003 	error = wg_socreate(wg, AF_INET6, &wg->wg_so6);
   4004 	if (error)
   4005 		goto fail2;
   4006 	rn_inithead((void **)&wg->wg_rtable_ipv6,
   4007 	    offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
   4008 #endif
   4009 
   4010 	error = wg_if_attach(wg);
   4011 	if (error)
   4012 		goto fail3;
   4013 
   4014 	return 0;
   4015 
   4016 fail4: __unused
   4017 	wg_destroy_all_peers(wg);
   4018 	wg_if_detach(wg);
   4019 fail3:
   4020 #ifdef INET6
   4021 	solock(wg->wg_so6);
   4022 	wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
   4023 	sounlock(wg->wg_so6);
   4024 #endif
   4025 #ifdef INET
   4026 	solock(wg->wg_so4);
   4027 	wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
   4028 	sounlock(wg->wg_so4);
   4029 #endif
   4030 	mutex_enter(wg->wg_intr_lock);
   4031 	threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
   4032 	mutex_exit(wg->wg_intr_lock);
   4033 #ifdef INET6
   4034 	if (wg->wg_rtable_ipv6 != NULL)
   4035 		free(wg->wg_rtable_ipv6, M_RTABLE);
   4036 	soclose(wg->wg_so6);
   4037 fail2:
   4038 #endif
   4039 #ifdef INET
   4040 	if (wg->wg_rtable_ipv4 != NULL)
   4041 		free(wg->wg_rtable_ipv4, M_RTABLE);
   4042 	soclose(wg->wg_so4);
   4043 fail1:
   4044 #endif
   4045 	threadpool_put(wg->wg_threadpool, PRI_NONE);
   4046 fail0:	threadpool_job_destroy(&wg->wg_job);
   4047 	rw_obj_free(wg->wg_rwlock);
   4048 	mutex_obj_free(wg->wg_intr_lock);
   4049 	mutex_obj_free(wg->wg_lock);
   4050 	thmap_destroy(wg->wg_sessions_byindex);
   4051 	thmap_destroy(wg->wg_peers_byname);
   4052 	thmap_destroy(wg->wg_peers_bypubkey);
   4053 	PSLIST_DESTROY(&wg->wg_peers);
   4054 	kmem_free(wg, sizeof(*wg));
   4055 	wg_count_dec();
   4056 	return error;
   4057 }
   4058 
   4059 static int
   4060 wg_clone_destroy(struct ifnet *ifp)
   4061 {
   4062 	struct wg_softc *wg = container_of(ifp, struct wg_softc, wg_if);
   4063 
   4064 #ifdef WG_RUMPKERNEL
   4065 	if (wg_user_mode(wg)) {
   4066 		rumpuser_wg_destroy(wg->wg_user);
   4067 		wg->wg_user = NULL;
   4068 	}
   4069 #endif
   4070 
   4071 	wg_destroy_all_peers(wg);
   4072 	wg_if_detach(wg);
   4073 #ifdef INET6
   4074 	solock(wg->wg_so6);
   4075 	wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
   4076 	sounlock(wg->wg_so6);
   4077 #endif
   4078 #ifdef INET
   4079 	solock(wg->wg_so4);
   4080 	wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
   4081 	sounlock(wg->wg_so4);
   4082 #endif
   4083 	mutex_enter(wg->wg_intr_lock);
   4084 	threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
   4085 	mutex_exit(wg->wg_intr_lock);
   4086 #ifdef INET6
   4087 	if (wg->wg_rtable_ipv6 != NULL)
   4088 		free(wg->wg_rtable_ipv6, M_RTABLE);
   4089 	soclose(wg->wg_so6);
   4090 #endif
   4091 #ifdef INET
   4092 	if (wg->wg_rtable_ipv4 != NULL)
   4093 		free(wg->wg_rtable_ipv4, M_RTABLE);
   4094 	soclose(wg->wg_so4);
   4095 #endif
   4096 	threadpool_put(wg->wg_threadpool, PRI_NONE);
   4097 	threadpool_job_destroy(&wg->wg_job);
   4098 	rw_obj_free(wg->wg_rwlock);
   4099 	mutex_obj_free(wg->wg_intr_lock);
   4100 	mutex_obj_free(wg->wg_lock);
   4101 	thmap_destroy(wg->wg_sessions_byindex);
   4102 	thmap_destroy(wg->wg_peers_byname);
   4103 	thmap_destroy(wg->wg_peers_bypubkey);
   4104 	PSLIST_DESTROY(&wg->wg_peers);
   4105 	kmem_free(wg, sizeof(*wg));
   4106 	wg_count_dec();
   4107 
   4108 	return 0;
   4109 }
   4110 
   4111 static struct wg_peer *
   4112 wg_pick_peer_by_sa(struct wg_softc *wg, const struct sockaddr *sa,
   4113     struct psref *psref)
   4114 {
   4115 	struct radix_node_head *rnh;
   4116 	struct radix_node *rn;
   4117 	struct wg_peer *wgp = NULL;
   4118 	struct wg_allowedip *wga;
   4119 
   4120 #ifdef WG_DEBUG_LOG
   4121 	char addrstr[128];
   4122 	sockaddr_format(sa, addrstr, sizeof(addrstr));
   4123 	WG_DLOG("sa=%s\n", addrstr);
   4124 #endif
   4125 
   4126 	rw_enter(wg->wg_rwlock, RW_READER);
   4127 
   4128 	rnh = wg_rnh(wg, sa->sa_family);
   4129 	if (rnh == NULL)
   4130 		goto out;
   4131 
   4132 	rn = rnh->rnh_matchaddr(sa, rnh);
   4133 	if (rn == NULL || (rn->rn_flags & RNF_ROOT) != 0)
   4134 		goto out;
   4135 
   4136 	WG_TRACE("success");
   4137 
   4138 	wga = container_of(rn, struct wg_allowedip, wga_nodes[0]);
   4139 	wgp = wga->wga_peer;
   4140 	wg_get_peer(wgp, psref);
   4141 
   4142 out:
   4143 	rw_exit(wg->wg_rwlock);
   4144 	return wgp;
   4145 }
   4146 
   4147 static void
   4148 wg_fill_msg_data(struct wg_softc *wg, struct wg_peer *wgp,
   4149     struct wg_session *wgs, struct wg_msg_data *wgmd)
   4150 {
   4151 
   4152 	memset(wgmd, 0, sizeof(*wgmd));
   4153 	wgmd->wgmd_type = htole32(WG_MSG_TYPE_DATA);
   4154 	wgmd->wgmd_receiver = wgs->wgs_remote_index;
   4155 	/* [W] 5.4.6: msg.counter := Nm^send */
   4156 	/* [W] 5.4.6: Nm^send := Nm^send + 1 */
   4157 	wgmd->wgmd_counter = htole64(wg_session_inc_send_counter(wgs));
   4158 	WG_DLOG("counter=%"PRIu64"\n", le64toh(wgmd->wgmd_counter));
   4159 }
   4160 
   4161 static int
   4162 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
   4163     const struct rtentry *rt)
   4164 {
   4165 	struct wg_softc *wg = ifp->if_softc;
   4166 	struct wg_peer *wgp = NULL;
   4167 	struct wg_session *wgs = NULL;
   4168 	struct psref wgp_psref, wgs_psref;
   4169 	int bound;
   4170 	int error;
   4171 
   4172 	bound = curlwp_bind();
   4173 
   4174 	/* TODO make the nest limit configurable via sysctl */
   4175 	error = if_tunnel_check_nesting(ifp, m, 1);
   4176 	if (error) {
   4177 		WGLOG(LOG_ERR,
   4178 		    "%s: tunneling loop detected and packet dropped\n",
   4179 		    if_name(&wg->wg_if));
   4180 		goto out0;
   4181 	}
   4182 
   4183 #ifdef ALTQ
   4184 	bool altq = atomic_load_relaxed(&ifp->if_snd.altq_flags)
   4185 	    & ALTQF_ENABLED;
   4186 	if (altq)
   4187 		IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
   4188 #endif
   4189 
   4190 	bpf_mtap_af(ifp, dst->sa_family, m, BPF_D_OUT);
   4191 
   4192 	m->m_flags &= ~(M_BCAST|M_MCAST);
   4193 
   4194 	wgp = wg_pick_peer_by_sa(wg, dst, &wgp_psref);
   4195 	if (wgp == NULL) {
   4196 		WG_TRACE("peer not found");
   4197 		error = EHOSTUNREACH;
   4198 		goto out0;
   4199 	}
   4200 
   4201 	/* Clear checksum-offload flags. */
   4202 	m->m_pkthdr.csum_flags = 0;
   4203 	m->m_pkthdr.csum_data = 0;
   4204 
   4205 	/* Check whether there's an established session.  */
   4206 	wgs = wg_get_stable_session(wgp, &wgs_psref);
   4207 	if (wgs == NULL) {
   4208 		/*
   4209 		 * No established session.  If we're the first to try
   4210 		 * sending data, schedule a handshake and queue the
   4211 		 * packet for when the handshake is done; otherwise
   4212 		 * just drop the packet and let the ongoing handshake
   4213 		 * attempt continue.  We could queue more data packets
   4214 		 * but it's not clear that's worthwhile.
   4215 		 */
   4216 		if (atomic_cas_ptr(&wgp->wgp_pending, NULL, m) == NULL) {
   4217 			m = NULL; /* consume */
   4218 			WG_TRACE("queued first packet; init handshake");
   4219 			wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   4220 		} else {
   4221 			WG_TRACE("first packet already queued, dropping");
   4222 		}
   4223 		goto out1;
   4224 	}
   4225 
   4226 	/* There's an established session.  Toss it in the queue.  */
   4227 #ifdef ALTQ
   4228 	if (altq) {
   4229 		mutex_enter(ifp->if_snd.ifq_lock);
   4230 		if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
   4231 			M_SETCTX(m, wgp);
   4232 			ALTQ_ENQUEUE(&ifp->if_snd, m, error);
   4233 			m = NULL; /* consume */
   4234 		}
   4235 		mutex_exit(ifp->if_snd.ifq_lock);
   4236 		if (m == NULL) {
   4237 			wg_start(ifp);
   4238 			goto out2;
   4239 		}
   4240 	}
   4241 #endif
   4242 	kpreempt_disable();
   4243 	const uint32_t h = curcpu()->ci_index;	// pktq_rps_hash(m)
   4244 	M_SETCTX(m, wgp);
   4245 	if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
   4246 		WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
   4247 		    if_name(&wg->wg_if));
   4248 		error = ENOBUFS;
   4249 		goto out3;
   4250 	}
   4251 	m = NULL;		/* consumed */
   4252 	error = 0;
   4253 out3:	kpreempt_enable();
   4254 
   4255 #ifdef ALTQ
   4256 out2:
   4257 #endif
   4258 	wg_put_session(wgs, &wgs_psref);
   4259 out1:	wg_put_peer(wgp, &wgp_psref);
   4260 out0:	m_freem(m);
   4261 	curlwp_bindx(bound);
   4262 	return error;
   4263 }
   4264 
   4265 static int
   4266 wg_send_udp(struct wg_peer *wgp, struct mbuf *m)
   4267 {
   4268 	struct psref psref;
   4269 	struct wg_sockaddr *wgsa;
   4270 	int error;
   4271 	struct socket *so;
   4272 
   4273 	wgsa = wg_get_endpoint_sa(wgp, &psref);
   4274 	so = wg_get_so_by_peer(wgp, wgsa);
   4275 	solock(so);
   4276 	switch (wgsatosa(wgsa)->sa_family) {
   4277 #ifdef INET
   4278 	case AF_INET:
   4279 		error = udp_send(so, m, wgsatosa(wgsa), NULL, curlwp);
   4280 		break;
   4281 #endif
   4282 #ifdef INET6
   4283 	case AF_INET6:
   4284 		error = udp6_output(sotoinpcb(so), m, wgsatosin6(wgsa),
   4285 		    NULL, curlwp);
   4286 		break;
   4287 #endif
   4288 	default:
   4289 		m_freem(m);
   4290 		error = EPFNOSUPPORT;
   4291 	}
   4292 	sounlock(so);
   4293 	wg_put_sa(wgp, wgsa, &psref);
   4294 
   4295 	return error;
   4296 }
   4297 
   4298 /* Inspired by pppoe_get_mbuf */
   4299 static struct mbuf *
   4300 wg_get_mbuf(size_t leading_len, size_t len)
   4301 {
   4302 	struct mbuf *m;
   4303 
   4304 	KASSERT(leading_len <= MCLBYTES);
   4305 	KASSERT(len <= MCLBYTES - leading_len);
   4306 
   4307 	m = m_gethdr(M_DONTWAIT, MT_DATA);
   4308 	if (m == NULL)
   4309 		return NULL;
   4310 	if (len + leading_len > MHLEN) {
   4311 		m_clget(m, M_DONTWAIT);
   4312 		if ((m->m_flags & M_EXT) == 0) {
   4313 			m_free(m);
   4314 			return NULL;
   4315 		}
   4316 	}
   4317 	m->m_data += leading_len;
   4318 	m->m_pkthdr.len = m->m_len = len;
   4319 
   4320 	return m;
   4321 }
   4322 
   4323 static void
   4324 wg_send_data_msg(struct wg_peer *wgp, struct wg_session *wgs, struct mbuf *m)
   4325 {
   4326 	struct wg_softc *wg = wgp->wgp_sc;
   4327 	int error;
   4328 	size_t inner_len, padded_len, encrypted_len;
   4329 	char *padded_buf = NULL;
   4330 	size_t mlen;
   4331 	struct wg_msg_data *wgmd;
   4332 	bool free_padded_buf = false;
   4333 	struct mbuf *n;
   4334 	size_t leading_len = max_hdr + sizeof(struct udphdr);
   4335 
   4336 	mlen = m_length(m);
   4337 	inner_len = mlen;
   4338 	padded_len = roundup(mlen, 16);
   4339 	encrypted_len = padded_len + WG_AUTHTAG_LEN;
   4340 	WG_DLOG("inner=%zu, padded=%zu, encrypted_len=%zu\n",
   4341 	    inner_len, padded_len, encrypted_len);
   4342 	if (mlen != 0) {
   4343 		bool success;
   4344 		success = m_ensure_contig(&m, padded_len);
   4345 		if (success) {
   4346 			padded_buf = mtod(m, char *);
   4347 		} else {
   4348 			padded_buf = kmem_intr_alloc(padded_len, KM_NOSLEEP);
   4349 			if (padded_buf == NULL) {
   4350 				error = ENOBUFS;
   4351 				goto out;
   4352 			}
   4353 			free_padded_buf = true;
   4354 			m_copydata(m, 0, mlen, padded_buf);
   4355 		}
   4356 		memset(padded_buf + mlen, 0, padded_len - inner_len);
   4357 	}
   4358 
   4359 	n = wg_get_mbuf(leading_len, sizeof(*wgmd) + encrypted_len);
   4360 	if (n == NULL) {
   4361 		error = ENOBUFS;
   4362 		goto out;
   4363 	}
   4364 	KASSERT(n->m_len >= sizeof(*wgmd));
   4365 	wgmd = mtod(n, struct wg_msg_data *);
   4366 	wg_fill_msg_data(wg, wgp, wgs, wgmd);
   4367 
   4368 	/* [W] 5.4.6: AEAD(Tm^send, Nm^send, P, e) */
   4369 	wg_algo_aead_enc((char *)wgmd + sizeof(*wgmd), encrypted_len,
   4370 	    wgs->wgs_tkey_send, le64toh(wgmd->wgmd_counter),
   4371 	    padded_buf, padded_len,
   4372 	    NULL, 0);
   4373 
   4374 	error = wg->wg_ops->send_data_msg(wgp, n); /* consumes n */
   4375 	if (error) {
   4376 		WG_DLOG("send_data_msg failed, error=%d\n", error);
   4377 		goto out;
   4378 	}
   4379 
   4380 	/*
   4381 	 * Packet was sent out -- count it in the interface statistics.
   4382 	 */
   4383 	if_statadd(&wg->wg_if, if_obytes, mlen);
   4384 	if_statinc(&wg->wg_if, if_opackets);
   4385 
   4386 	/*
   4387 	 * Record when we last sent data, for determining when we need
   4388 	 * to send a passive keepalive.
   4389 	 *
   4390 	 * Other logic assumes that wgs_time_last_data_sent is zero iff
   4391 	 * we have never sent data on this session.  Early at boot, if
   4392 	 * wg(4) starts operating within <1sec, or after 136 years of
   4393 	 * uptime, we may observe time_uptime32 = 0.  In that case,
   4394 	 * pretend we observed 1 instead.  That way, we correctly
   4395 	 * indicate we have sent data on this session; the only logic
   4396 	 * this might adversely affect is the keepalive timeout
   4397 	 * detection, which might spuriously send a keepalive during
   4398 	 * one second every 136 years.  All of this is very silly, of
   4399 	 * course, but the cost to guaranteeing wgs_time_last_data_sent
   4400 	 * is nonzero is negligible here.
   4401 	 */
   4402 	const uint32_t now = time_uptime32;
   4403 	atomic_store_relaxed(&wgs->wgs_time_last_data_sent, MAX(now, 1));
   4404 
   4405 	/*
   4406 	 * Check rekey-after-time.
   4407 	 */
   4408 	if (wgs->wgs_is_initiator &&
   4409 	    ((time_uptime32 -
   4410 		atomic_load_relaxed(&wgs->wgs_time_established)) >=
   4411 		wg_rekey_after_time)) {
   4412 		/*
   4413 		 * [W] 6.2 Transport Message Limits
   4414 		 * "if a peer is the initiator of a current secure
   4415 		 *  session, WireGuard will send a handshake initiation
   4416 		 *  message to begin a new secure session if, after
   4417 		 *  transmitting a transport data message, the current
   4418 		 *  secure session is REKEY-AFTER-TIME seconds old,"
   4419 		 */
   4420 		WG_TRACE("rekey after time");
   4421 		atomic_store_relaxed(&wgs->wgs_force_rekey, true);
   4422 		wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   4423 	}
   4424 
   4425 	/*
   4426 	 * Check rekey-after-messages.
   4427 	 */
   4428 	if (wg_session_get_send_counter(wgs) >= wg_rekey_after_messages) {
   4429 		/*
   4430 		 * [W] 6.2 Transport Message Limits
   4431 		 * "WireGuard will try to create a new session, by
   4432 		 *  sending a handshake initiation message (section
   4433 		 *  5.4.2), after it has sent REKEY-AFTER-MESSAGES
   4434 		 *  transport data messages..."
   4435 		 */
   4436 		WG_TRACE("rekey after messages");
   4437 		atomic_store_relaxed(&wgs->wgs_force_rekey, true);
   4438 		wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   4439 	}
   4440 
   4441 out:	m_freem(m);
   4442 	if (free_padded_buf)
   4443 		kmem_intr_free(padded_buf, padded_len);
   4444 }
   4445 
   4446 static void
   4447 wg_input(struct ifnet *ifp, struct mbuf *m, const int af)
   4448 {
   4449 	pktqueue_t *pktq;
   4450 	size_t pktlen;
   4451 
   4452 	KASSERT(af == AF_INET || af == AF_INET6);
   4453 
   4454 	WG_TRACE("");
   4455 
   4456 	m_set_rcvif(m, ifp);
   4457 	pktlen = m->m_pkthdr.len;
   4458 
   4459 	bpf_mtap_af(ifp, af, m, BPF_D_IN);
   4460 
   4461 	switch (af) {
   4462 #ifdef INET
   4463 	case AF_INET:
   4464 		pktq = ip_pktq;
   4465 		break;
   4466 #endif
   4467 #ifdef INET6
   4468 	case AF_INET6:
   4469 		pktq = ip6_pktq;
   4470 		break;
   4471 #endif
   4472 	default:
   4473 		panic("invalid af=%d", af);
   4474 	}
   4475 
   4476 	kpreempt_disable();
   4477 	const u_int h = curcpu()->ci_index;
   4478 	if (__predict_true(pktq_enqueue(pktq, m, h))) {
   4479 		if_statadd(ifp, if_ibytes, pktlen);
   4480 		if_statinc(ifp, if_ipackets);
   4481 	} else {
   4482 		m_freem(m);
   4483 	}
   4484 	kpreempt_enable();
   4485 }
   4486 
   4487 static void
   4488 wg_calc_pubkey(uint8_t pubkey[static WG_STATIC_KEY_LEN],
   4489     const uint8_t privkey[static WG_STATIC_KEY_LEN])
   4490 {
   4491 
   4492 	crypto_scalarmult_base(pubkey, privkey);
   4493 }
   4494 
   4495 static int
   4496 wg_rtable_add_route(struct wg_softc *wg, struct wg_allowedip *wga)
   4497 {
   4498 	struct radix_node_head *rnh;
   4499 	struct radix_node *rn;
   4500 	int error = 0;
   4501 
   4502 	rw_enter(wg->wg_rwlock, RW_WRITER);
   4503 	rnh = wg_rnh(wg, wga->wga_family);
   4504 	KASSERT(rnh != NULL);
   4505 	rn = rnh->rnh_addaddr(&wga->wga_sa_addr, &wga->wga_sa_mask, rnh,
   4506 	    wga->wga_nodes);
   4507 	rw_exit(wg->wg_rwlock);
   4508 
   4509 	if (rn == NULL)
   4510 		error = EEXIST;
   4511 
   4512 	return error;
   4513 }
   4514 
   4515 static int
   4516 wg_handle_prop_peer(struct wg_softc *wg, prop_dictionary_t peer,
   4517     struct wg_peer **wgpp)
   4518 {
   4519 	int error = 0;
   4520 	const void *pubkey;
   4521 	size_t pubkey_len;
   4522 	const void *psk;
   4523 	size_t psk_len;
   4524 	const char *name = NULL;
   4525 
   4526 	if (prop_dictionary_get_string(peer, "name", &name)) {
   4527 		if (strlen(name) > WG_PEER_NAME_MAXLEN) {
   4528 			error = EINVAL;
   4529 			goto out;
   4530 		}
   4531 	}
   4532 
   4533 	if (!prop_dictionary_get_data(peer, "public_key",
   4534 		&pubkey, &pubkey_len)) {
   4535 		error = EINVAL;
   4536 		goto out;
   4537 	}
   4538 #ifdef WG_DEBUG_DUMP
   4539         if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
   4540 		char *hex = gethexdump(pubkey, pubkey_len);
   4541 		log(LOG_DEBUG, "pubkey=%p, pubkey_len=%zu\n%s\n",
   4542 		    pubkey, pubkey_len, hex);
   4543 		puthexdump(hex, pubkey, pubkey_len);
   4544 	}
   4545 #endif
   4546 
   4547 	struct wg_peer *wgp = wg_alloc_peer(wg);
   4548 	memcpy(wgp->wgp_pubkey, pubkey, sizeof(wgp->wgp_pubkey));
   4549 	if (name != NULL)
   4550 		strncpy(wgp->wgp_name, name, sizeof(wgp->wgp_name));
   4551 
   4552 	if (prop_dictionary_get_data(peer, "preshared_key", &psk, &psk_len)) {
   4553 		if (psk_len != sizeof(wgp->wgp_psk)) {
   4554 			error = EINVAL;
   4555 			goto out;
   4556 		}
   4557 		memcpy(wgp->wgp_psk, psk, sizeof(wgp->wgp_psk));
   4558 	}
   4559 
   4560 	const void *addr;
   4561 	size_t addr_len;
   4562 	struct wg_sockaddr *wgsa = wgp->wgp_endpoint;
   4563 
   4564 	if (!prop_dictionary_get_data(peer, "endpoint", &addr, &addr_len))
   4565 		goto skip_endpoint;
   4566 	if (addr_len < sizeof(*wgsatosa(wgsa)) ||
   4567 	    addr_len > sizeof(*wgsatoss(wgsa))) {
   4568 		error = EINVAL;
   4569 		goto out;
   4570 	}
   4571 	memcpy(wgsatoss(wgsa), addr, addr_len);
   4572 	switch (wgsa_family(wgsa)) {
   4573 #ifdef INET
   4574 	case AF_INET:
   4575 		break;
   4576 #endif
   4577 #ifdef INET6
   4578 	case AF_INET6:
   4579 		break;
   4580 #endif
   4581 	default:
   4582 		error = EPFNOSUPPORT;
   4583 		goto out;
   4584 	}
   4585 	if (addr_len != sockaddr_getsize_by_family(wgsa_family(wgsa))) {
   4586 		error = EINVAL;
   4587 		goto out;
   4588 	}
   4589     {
   4590 	char addrstr[128];
   4591 	sockaddr_format(wgsatosa(wgsa), addrstr, sizeof(addrstr));
   4592 	WG_DLOG("addr=%s\n", addrstr);
   4593     }
   4594 	wgp->wgp_endpoint_available = true;
   4595 
   4596 	prop_array_t allowedips;
   4597 skip_endpoint:
   4598 	allowedips = prop_dictionary_get(peer, "allowedips");
   4599 	if (allowedips == NULL)
   4600 		goto skip;
   4601 
   4602 	prop_object_iterator_t _it = prop_array_iterator(allowedips);
   4603 	prop_dictionary_t prop_allowedip;
   4604 	int j = 0;
   4605 	while ((prop_allowedip = prop_object_iterator_next(_it)) != NULL) {
   4606 		struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
   4607 
   4608 		if (!prop_dictionary_get_int(prop_allowedip, "family",
   4609 			&wga->wga_family))
   4610 			continue;
   4611 		if (!prop_dictionary_get_data(prop_allowedip, "ip",
   4612 			&addr, &addr_len))
   4613 			continue;
   4614 		if (!prop_dictionary_get_uint8(prop_allowedip, "cidr",
   4615 			&wga->wga_cidr))
   4616 			continue;
   4617 
   4618 		switch (wga->wga_family) {
   4619 #ifdef INET
   4620 		case AF_INET: {
   4621 			struct sockaddr_in sin;
   4622 			char addrstr[128];
   4623 			struct in_addr mask;
   4624 			struct sockaddr_in sin_mask;
   4625 
   4626 			if (addr_len != sizeof(struct in_addr))
   4627 				return EINVAL;
   4628 			memcpy(&wga->wga_addr4, addr, addr_len);
   4629 
   4630 			sockaddr_in_init(&sin, (const struct in_addr *)addr,
   4631 			    0);
   4632 			sockaddr_copy(&wga->wga_sa_addr,
   4633 			    sizeof(sin), sintosa(&sin));
   4634 
   4635 			sockaddr_format(sintosa(&sin),
   4636 			    addrstr, sizeof(addrstr));
   4637 			WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
   4638 
   4639 			in_len2mask(&mask, wga->wga_cidr);
   4640 			sockaddr_in_init(&sin_mask, &mask, 0);
   4641 			sockaddr_copy(&wga->wga_sa_mask,
   4642 			    sizeof(sin_mask), sintosa(&sin_mask));
   4643 
   4644 			break;
   4645 		    }
   4646 #endif
   4647 #ifdef INET6
   4648 		case AF_INET6: {
   4649 			struct sockaddr_in6 sin6;
   4650 			char addrstr[128];
   4651 			struct in6_addr mask;
   4652 			struct sockaddr_in6 sin6_mask;
   4653 
   4654 			if (addr_len != sizeof(struct in6_addr))
   4655 				return EINVAL;
   4656 			memcpy(&wga->wga_addr6, addr, addr_len);
   4657 
   4658 			sockaddr_in6_init(&sin6, (const struct in6_addr *)addr,
   4659 			    0, 0, 0);
   4660 			sockaddr_copy(&wga->wga_sa_addr,
   4661 			    sizeof(sin6), sin6tosa(&sin6));
   4662 
   4663 			sockaddr_format(sin6tosa(&sin6),
   4664 			    addrstr, sizeof(addrstr));
   4665 			WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
   4666 
   4667 			in6_prefixlen2mask(&mask, wga->wga_cidr);
   4668 			sockaddr_in6_init(&sin6_mask, &mask, 0, 0, 0);
   4669 			sockaddr_copy(&wga->wga_sa_mask,
   4670 			    sizeof(sin6_mask), sin6tosa(&sin6_mask));
   4671 
   4672 			break;
   4673 		    }
   4674 #endif
   4675 		default:
   4676 			error = EINVAL;
   4677 			goto out;
   4678 		}
   4679 		wga->wga_peer = wgp;
   4680 
   4681 		error = wg_rtable_add_route(wg, wga);
   4682 		if (error != 0)
   4683 			goto out;
   4684 
   4685 		j++;
   4686 	}
   4687 	wgp->wgp_n_allowedips = j;
   4688 skip:
   4689 	*wgpp = wgp;
   4690 out:
   4691 	return error;
   4692 }
   4693 
   4694 static int
   4695 wg_alloc_prop_buf(char **_buf, struct ifdrv *ifd)
   4696 {
   4697 	int error;
   4698 	char *buf;
   4699 
   4700 	WG_DLOG("buf=%p, len=%zu\n", ifd->ifd_data, ifd->ifd_len);
   4701 	if (ifd->ifd_len >= WG_MAX_PROPLEN)
   4702 		return E2BIG;
   4703 	buf = kmem_alloc(ifd->ifd_len + 1, KM_SLEEP);
   4704 	error = copyin(ifd->ifd_data, buf, ifd->ifd_len);
   4705 	if (error != 0)
   4706 		return error;
   4707 	buf[ifd->ifd_len] = '\0';
   4708 #ifdef WG_DEBUG_DUMP
   4709 	if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
   4710 		log(LOG_DEBUG, "%.*s\n", (int)MIN(INT_MAX, ifd->ifd_len),
   4711 		    (const char *)buf);
   4712 	}
   4713 #endif
   4714 	*_buf = buf;
   4715 	return 0;
   4716 }
   4717 
   4718 static int
   4719 wg_ioctl_set_private_key(struct wg_softc *wg, struct ifdrv *ifd)
   4720 {
   4721 	int error;
   4722 	prop_dictionary_t prop_dict;
   4723 	char *buf = NULL;
   4724 	const void *privkey;
   4725 	size_t privkey_len;
   4726 
   4727 	error = wg_alloc_prop_buf(&buf, ifd);
   4728 	if (error != 0)
   4729 		return error;
   4730 	error = EINVAL;
   4731 	prop_dict = prop_dictionary_internalize(buf);
   4732 	if (prop_dict == NULL)
   4733 		goto out;
   4734 	if (!prop_dictionary_get_data(prop_dict, "private_key",
   4735 		&privkey, &privkey_len))
   4736 		goto out;
   4737 #ifdef WG_DEBUG_DUMP
   4738 	if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
   4739 		char *hex = gethexdump(privkey, privkey_len);
   4740 		log(LOG_DEBUG, "privkey=%p, privkey_len=%zu\n%s\n",
   4741 		    privkey, privkey_len, hex);
   4742 		puthexdump(hex, privkey, privkey_len);
   4743 	}
   4744 #endif
   4745 	if (privkey_len != WG_STATIC_KEY_LEN)
   4746 		goto out;
   4747 	memcpy(wg->wg_privkey, privkey, WG_STATIC_KEY_LEN);
   4748 	wg_calc_pubkey(wg->wg_pubkey, wg->wg_privkey);
   4749 	error = 0;
   4750 
   4751 out:
   4752 	kmem_free(buf, ifd->ifd_len + 1);
   4753 	return error;
   4754 }
   4755 
   4756 static int
   4757 wg_ioctl_set_listen_port(struct wg_softc *wg, struct ifdrv *ifd)
   4758 {
   4759 	int error;
   4760 	prop_dictionary_t prop_dict;
   4761 	char *buf = NULL;
   4762 	uint16_t port;
   4763 
   4764 	error = wg_alloc_prop_buf(&buf, ifd);
   4765 	if (error != 0)
   4766 		return error;
   4767 	error = EINVAL;
   4768 	prop_dict = prop_dictionary_internalize(buf);
   4769 	if (prop_dict == NULL)
   4770 		goto out;
   4771 	if (!prop_dictionary_get_uint16(prop_dict, "listen_port", &port))
   4772 		goto out;
   4773 
   4774 	error = wg->wg_ops->bind_port(wg, (uint16_t)port);
   4775 
   4776 out:
   4777 	kmem_free(buf, ifd->ifd_len + 1);
   4778 	return error;
   4779 }
   4780 
   4781 static int
   4782 wg_ioctl_add_peer(struct wg_softc *wg, struct ifdrv *ifd)
   4783 {
   4784 	int error;
   4785 	prop_dictionary_t prop_dict;
   4786 	char *buf = NULL;
   4787 	struct wg_peer *wgp = NULL, *wgp0 __diagused;
   4788 
   4789 	error = wg_alloc_prop_buf(&buf, ifd);
   4790 	if (error != 0)
   4791 		return error;
   4792 	error = EINVAL;
   4793 	prop_dict = prop_dictionary_internalize(buf);
   4794 	if (prop_dict == NULL)
   4795 		goto out;
   4796 
   4797 	error = wg_handle_prop_peer(wg, prop_dict, &wgp);
   4798 	if (error != 0)
   4799 		goto out;
   4800 
   4801 	mutex_enter(wg->wg_lock);
   4802 	if (thmap_get(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
   4803 		sizeof(wgp->wgp_pubkey)) != NULL ||
   4804 	    (wgp->wgp_name[0] &&
   4805 		thmap_get(wg->wg_peers_byname, wgp->wgp_name,
   4806 		    strlen(wgp->wgp_name)) != NULL)) {
   4807 		mutex_exit(wg->wg_lock);
   4808 		wg_destroy_peer(wgp);
   4809 		error = EEXIST;
   4810 		goto out;
   4811 	}
   4812 	wgp0 = thmap_put(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
   4813 	    sizeof(wgp->wgp_pubkey), wgp);
   4814 	KASSERT(wgp0 == wgp);
   4815 	if (wgp->wgp_name[0]) {
   4816 		wgp0 = thmap_put(wg->wg_peers_byname, wgp->wgp_name,
   4817 		    strlen(wgp->wgp_name), wgp);
   4818 		KASSERT(wgp0 == wgp);
   4819 	}
   4820 	WG_PEER_WRITER_INSERT_HEAD(wgp, wg);
   4821 	wg->wg_npeers++;
   4822 	mutex_exit(wg->wg_lock);
   4823 
   4824 	if_link_state_change(&wg->wg_if, LINK_STATE_UP);
   4825 
   4826 out:
   4827 	kmem_free(buf, ifd->ifd_len + 1);
   4828 	return error;
   4829 }
   4830 
   4831 static int
   4832 wg_ioctl_delete_peer(struct wg_softc *wg, struct ifdrv *ifd)
   4833 {
   4834 	int error;
   4835 	prop_dictionary_t prop_dict;
   4836 	char *buf = NULL;
   4837 	const char *name;
   4838 
   4839 	error = wg_alloc_prop_buf(&buf, ifd);
   4840 	if (error != 0)
   4841 		return error;
   4842 	error = EINVAL;
   4843 	prop_dict = prop_dictionary_internalize(buf);
   4844 	if (prop_dict == NULL)
   4845 		goto out;
   4846 
   4847 	if (!prop_dictionary_get_string(prop_dict, "name", &name))
   4848 		goto out;
   4849 	if (strlen(name) > WG_PEER_NAME_MAXLEN)
   4850 		goto out;
   4851 
   4852 	error = wg_destroy_peer_name(wg, name);
   4853 out:
   4854 	kmem_free(buf, ifd->ifd_len + 1);
   4855 	return error;
   4856 }
   4857 
   4858 static bool
   4859 wg_is_authorized(struct wg_softc *wg, u_long cmd)
   4860 {
   4861 	int au = cmd == SIOCGDRVSPEC ?
   4862 	    KAUTH_REQ_NETWORK_INTERFACE_WG_GETPRIV :
   4863 	    KAUTH_REQ_NETWORK_INTERFACE_WG_SETPRIV;
   4864 	return kauth_authorize_network(kauth_cred_get(),
   4865 	    KAUTH_NETWORK_INTERFACE_WG, au, &wg->wg_if,
   4866 	    (void *)cmd, NULL) == 0;
   4867 }
   4868 
   4869 static int
   4870 wg_ioctl_get(struct wg_softc *wg, struct ifdrv *ifd)
   4871 {
   4872 	int error = ENOMEM;
   4873 	prop_dictionary_t prop_dict;
   4874 	prop_array_t peers = NULL;
   4875 	char *buf;
   4876 	struct wg_peer *wgp;
   4877 	int s, i;
   4878 
   4879 	prop_dict = prop_dictionary_create();
   4880 	if (prop_dict == NULL)
   4881 		goto error;
   4882 
   4883 	if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
   4884 		if (!prop_dictionary_set_data(prop_dict, "private_key",
   4885 			wg->wg_privkey, WG_STATIC_KEY_LEN))
   4886 			goto error;
   4887 	}
   4888 
   4889 	if (wg->wg_listen_port != 0) {
   4890 		if (!prop_dictionary_set_uint16(prop_dict, "listen_port",
   4891 			wg->wg_listen_port))
   4892 			goto error;
   4893 	}
   4894 
   4895 	if (wg->wg_npeers == 0)
   4896 		goto skip_peers;
   4897 
   4898 	peers = prop_array_create();
   4899 	if (peers == NULL)
   4900 		goto error;
   4901 
   4902 	s = pserialize_read_enter();
   4903 	i = 0;
   4904 	WG_PEER_READER_FOREACH(wgp, wg) {
   4905 		struct wg_sockaddr *wgsa;
   4906 		struct psref wgp_psref, wgsa_psref;
   4907 		prop_dictionary_t prop_peer;
   4908 
   4909 		wg_get_peer(wgp, &wgp_psref);
   4910 		pserialize_read_exit(s);
   4911 
   4912 		prop_peer = prop_dictionary_create();
   4913 		if (prop_peer == NULL)
   4914 			goto next;
   4915 
   4916 		if (strlen(wgp->wgp_name) > 0) {
   4917 			if (!prop_dictionary_set_string(prop_peer, "name",
   4918 				wgp->wgp_name))
   4919 				goto next;
   4920 		}
   4921 
   4922 		if (!prop_dictionary_set_data(prop_peer, "public_key",
   4923 			wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey)))
   4924 			goto next;
   4925 
   4926 		uint8_t psk_zero[WG_PRESHARED_KEY_LEN] = {0};
   4927 		if (!consttime_memequal(wgp->wgp_psk, psk_zero,
   4928 			sizeof(wgp->wgp_psk))) {
   4929 			if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
   4930 				if (!prop_dictionary_set_data(prop_peer,
   4931 					"preshared_key",
   4932 					wgp->wgp_psk, sizeof(wgp->wgp_psk)))
   4933 					goto next;
   4934 			}
   4935 		}
   4936 
   4937 		wgsa = wg_get_endpoint_sa(wgp, &wgsa_psref);
   4938 		CTASSERT(AF_UNSPEC == 0);
   4939 		if (wgsa_family(wgsa) != 0 /*AF_UNSPEC*/ &&
   4940 		    !prop_dictionary_set_data(prop_peer, "endpoint",
   4941 			wgsatoss(wgsa),
   4942 			sockaddr_getsize_by_family(wgsa_family(wgsa)))) {
   4943 			wg_put_sa(wgp, wgsa, &wgsa_psref);
   4944 			goto next;
   4945 		}
   4946 		wg_put_sa(wgp, wgsa, &wgsa_psref);
   4947 
   4948 		const struct timespec *t = &wgp->wgp_last_handshake_time;
   4949 
   4950 		if (!prop_dictionary_set_uint64(prop_peer,
   4951 			"last_handshake_time_sec", (uint64_t)t->tv_sec))
   4952 			goto next;
   4953 		if (!prop_dictionary_set_uint32(prop_peer,
   4954 			"last_handshake_time_nsec", (uint32_t)t->tv_nsec))
   4955 			goto next;
   4956 
   4957 		if (wgp->wgp_n_allowedips == 0)
   4958 			goto skip_allowedips;
   4959 
   4960 		prop_array_t allowedips = prop_array_create();
   4961 		if (allowedips == NULL)
   4962 			goto next;
   4963 		for (int j = 0; j < wgp->wgp_n_allowedips; j++) {
   4964 			struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
   4965 			prop_dictionary_t prop_allowedip;
   4966 
   4967 			prop_allowedip = prop_dictionary_create();
   4968 			if (prop_allowedip == NULL)
   4969 				break;
   4970 
   4971 			if (!prop_dictionary_set_int(prop_allowedip, "family",
   4972 				wga->wga_family))
   4973 				goto _next;
   4974 			if (!prop_dictionary_set_uint8(prop_allowedip, "cidr",
   4975 				wga->wga_cidr))
   4976 				goto _next;
   4977 
   4978 			switch (wga->wga_family) {
   4979 #ifdef INET
   4980 			case AF_INET:
   4981 				if (!prop_dictionary_set_data(prop_allowedip,
   4982 					"ip", &wga->wga_addr4,
   4983 					sizeof(wga->wga_addr4)))
   4984 					goto _next;
   4985 				break;
   4986 #endif
   4987 #ifdef INET6
   4988 			case AF_INET6:
   4989 				if (!prop_dictionary_set_data(prop_allowedip,
   4990 					"ip", &wga->wga_addr6,
   4991 					sizeof(wga->wga_addr6)))
   4992 					goto _next;
   4993 				break;
   4994 #endif
   4995 			default:
   4996 				panic("invalid af=%d", wga->wga_family);
   4997 			}
   4998 			prop_array_set(allowedips, j, prop_allowedip);
   4999 		_next:
   5000 			prop_object_release(prop_allowedip);
   5001 		}
   5002 		prop_dictionary_set(prop_peer, "allowedips", allowedips);
   5003 		prop_object_release(allowedips);
   5004 
   5005 	skip_allowedips:
   5006 
   5007 		prop_array_set(peers, i, prop_peer);
   5008 	next:
   5009 		if (prop_peer)
   5010 			prop_object_release(prop_peer);
   5011 		i++;
   5012 
   5013 		s = pserialize_read_enter();
   5014 		wg_put_peer(wgp, &wgp_psref);
   5015 	}
   5016 	pserialize_read_exit(s);
   5017 
   5018 	prop_dictionary_set(prop_dict, "peers", peers);
   5019 	prop_object_release(peers);
   5020 	peers = NULL;
   5021 
   5022 skip_peers:
   5023 	buf = prop_dictionary_externalize(prop_dict);
   5024 	if (buf == NULL)
   5025 		goto error;
   5026 	if (ifd->ifd_len < (strlen(buf) + 1)) {
   5027 		error = EINVAL;
   5028 		goto error;
   5029 	}
   5030 	error = copyout(buf, ifd->ifd_data, strlen(buf) + 1);
   5031 
   5032 	free(buf, 0);
   5033 error:
   5034 	if (peers != NULL)
   5035 		prop_object_release(peers);
   5036 	if (prop_dict != NULL)
   5037 		prop_object_release(prop_dict);
   5038 
   5039 	return error;
   5040 }
   5041 
   5042 static int
   5043 wg_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   5044 {
   5045 	struct wg_softc *wg = ifp->if_softc;
   5046 	struct ifreq *ifr = data;
   5047 	struct ifaddr *ifa = data;
   5048 	struct ifdrv *ifd = data;
   5049 	int error = 0;
   5050 
   5051 	switch (cmd) {
   5052 	case SIOCINITIFADDR:
   5053 		if (ifa->ifa_addr->sa_family != AF_LINK &&
   5054 		    (ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
   5055 		    (IFF_UP | IFF_RUNNING)) {
   5056 			ifp->if_flags |= IFF_UP;
   5057 			error = if_init(ifp);
   5058 		}
   5059 		return error;
   5060 	case SIOCADDMULTI:
   5061 	case SIOCDELMULTI:
   5062 		switch (ifr->ifr_addr.sa_family) {
   5063 #ifdef INET
   5064 		case AF_INET:	/* IP supports Multicast */
   5065 			break;
   5066 #endif
   5067 #ifdef INET6
   5068 		case AF_INET6:	/* IP6 supports Multicast */
   5069 			break;
   5070 #endif
   5071 		default:  /* Other protocols doesn't support Multicast */
   5072 			error = EAFNOSUPPORT;
   5073 			break;
   5074 		}
   5075 		return error;
   5076 	case SIOCSDRVSPEC:
   5077 		if (!wg_is_authorized(wg, cmd)) {
   5078 			return EPERM;
   5079 		}
   5080 		switch (ifd->ifd_cmd) {
   5081 		case WG_IOCTL_SET_PRIVATE_KEY:
   5082 			error = wg_ioctl_set_private_key(wg, ifd);
   5083 			break;
   5084 		case WG_IOCTL_SET_LISTEN_PORT:
   5085 			error = wg_ioctl_set_listen_port(wg, ifd);
   5086 			break;
   5087 		case WG_IOCTL_ADD_PEER:
   5088 			error = wg_ioctl_add_peer(wg, ifd);
   5089 			break;
   5090 		case WG_IOCTL_DELETE_PEER:
   5091 			error = wg_ioctl_delete_peer(wg, ifd);
   5092 			break;
   5093 		default:
   5094 			error = EINVAL;
   5095 			break;
   5096 		}
   5097 		return error;
   5098 	case SIOCGDRVSPEC:
   5099 		return wg_ioctl_get(wg, ifd);
   5100 	case SIOCSIFFLAGS:
   5101 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
   5102 			break;
   5103 		switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
   5104 		case IFF_RUNNING:
   5105 			/*
   5106 			 * If interface is marked down and it is running,
   5107 			 * then stop and disable it.
   5108 			 */
   5109 			if_stop(ifp, 1);
   5110 			break;
   5111 		case IFF_UP:
   5112 			/*
   5113 			 * If interface is marked up and it is stopped, then
   5114 			 * start it.
   5115 			 */
   5116 			error = if_init(ifp);
   5117 			break;
   5118 		default:
   5119 			break;
   5120 		}
   5121 		return error;
   5122 #ifdef WG_RUMPKERNEL
   5123 	case SIOCSLINKSTR:
   5124 		error = wg_ioctl_linkstr(wg, ifd);
   5125 		if (error)
   5126 			return error;
   5127 		wg->wg_ops = &wg_ops_rumpuser;
   5128 		return 0;
   5129 #endif
   5130 	default:
   5131 		break;
   5132 	}
   5133 
   5134 	error = ifioctl_common(ifp, cmd, data);
   5135 
   5136 #ifdef WG_RUMPKERNEL
   5137 	if (!wg_user_mode(wg))
   5138 		return error;
   5139 
   5140 	/* Do the same to the corresponding tun device on the host */
   5141 	/*
   5142 	 * XXX Actually the command has not been handled yet.  It
   5143 	 *     will be handled via pr_ioctl form doifioctl later.
   5144 	 */
   5145 	switch (cmd) {
   5146 #ifdef INET
   5147 	case SIOCAIFADDR:
   5148 	case SIOCDIFADDR: {
   5149 		struct in_aliasreq _ifra = *(const struct in_aliasreq *)data;
   5150 		struct in_aliasreq *ifra = &_ifra;
   5151 		KASSERT(error == ENOTTY);
   5152 		strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
   5153 		    IFNAMSIZ);
   5154 		error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET);
   5155 		if (error == 0)
   5156 			error = ENOTTY;
   5157 		break;
   5158 	}
   5159 #endif
   5160 #ifdef INET6
   5161 	case SIOCAIFADDR_IN6:
   5162 	case SIOCDIFADDR_IN6: {
   5163 		struct in6_aliasreq _ifra = *(const struct in6_aliasreq *)data;
   5164 		struct in6_aliasreq *ifra = &_ifra;
   5165 		KASSERT(error == ENOTTY);
   5166 		strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
   5167 		    IFNAMSIZ);
   5168 		error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET6);
   5169 		if (error == 0)
   5170 			error = ENOTTY;
   5171 		break;
   5172 	}
   5173 #endif
   5174 	default:
   5175 		break;
   5176 	}
   5177 #endif /* WG_RUMPKERNEL */
   5178 
   5179 	return error;
   5180 }
   5181 
   5182 static int
   5183 wg_init(struct ifnet *ifp)
   5184 {
   5185 
   5186 	ifp->if_flags |= IFF_RUNNING;
   5187 
   5188 	/* TODO flush pending packets. */
   5189 	return 0;
   5190 }
   5191 
   5192 #ifdef ALTQ
   5193 static void
   5194 wg_start(struct ifnet *ifp)
   5195 {
   5196 	struct mbuf *m;
   5197 
   5198 	for (;;) {
   5199 		IFQ_DEQUEUE(&ifp->if_snd, m);
   5200 		if (m == NULL)
   5201 			break;
   5202 
   5203 		kpreempt_disable();
   5204 		const uint32_t h = curcpu()->ci_index;	// pktq_rps_hash(m)
   5205 		if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
   5206 			WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
   5207 			    if_name(ifp));
   5208 			m_freem(m);
   5209 		}
   5210 		kpreempt_enable();
   5211 	}
   5212 }
   5213 #endif
   5214 
   5215 static void
   5216 wg_stop(struct ifnet *ifp, int disable)
   5217 {
   5218 
   5219 	KASSERT((ifp->if_flags & IFF_RUNNING) != 0);
   5220 	ifp->if_flags &= ~IFF_RUNNING;
   5221 
   5222 	/* Need to do something? */
   5223 }
   5224 
   5225 #ifdef WG_DEBUG_PARAMS
   5226 SYSCTL_SETUP(sysctl_net_wg_setup, "sysctl net.wg setup")
   5227 {
   5228 	const struct sysctlnode *node = NULL;
   5229 
   5230 	sysctl_createv(clog, 0, NULL, &node,
   5231 	    CTLFLAG_PERMANENT,
   5232 	    CTLTYPE_NODE, "wg",
   5233 	    SYSCTL_DESCR("wg(4)"),
   5234 	    NULL, 0, NULL, 0,
   5235 	    CTL_NET, CTL_CREATE, CTL_EOL);
   5236 	sysctl_createv(clog, 0, &node, NULL,
   5237 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5238 	    CTLTYPE_QUAD, "rekey_after_messages",
   5239 	    SYSCTL_DESCR("session liftime by messages"),
   5240 	    NULL, 0, &wg_rekey_after_messages, 0, CTL_CREATE, CTL_EOL);
   5241 	sysctl_createv(clog, 0, &node, NULL,
   5242 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5243 	    CTLTYPE_INT, "rekey_after_time",
   5244 	    SYSCTL_DESCR("session liftime"),
   5245 	    NULL, 0, &wg_rekey_after_time, 0, CTL_CREATE, CTL_EOL);
   5246 	sysctl_createv(clog, 0, &node, NULL,
   5247 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5248 	    CTLTYPE_INT, "rekey_timeout",
   5249 	    SYSCTL_DESCR("session handshake retry time"),
   5250 	    NULL, 0, &wg_rekey_timeout, 0, CTL_CREATE, CTL_EOL);
   5251 	sysctl_createv(clog, 0, &node, NULL,
   5252 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5253 	    CTLTYPE_INT, "rekey_attempt_time",
   5254 	    SYSCTL_DESCR("session handshake timeout"),
   5255 	    NULL, 0, &wg_rekey_attempt_time, 0, CTL_CREATE, CTL_EOL);
   5256 	sysctl_createv(clog, 0, &node, NULL,
   5257 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5258 	    CTLTYPE_INT, "keepalive_timeout",
   5259 	    SYSCTL_DESCR("keepalive timeout"),
   5260 	    NULL, 0, &wg_keepalive_timeout, 0, CTL_CREATE, CTL_EOL);
   5261 	sysctl_createv(clog, 0, &node, NULL,
   5262 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5263 	    CTLTYPE_BOOL, "force_underload",
   5264 	    SYSCTL_DESCR("force to detemine under load"),
   5265 	    NULL, 0, &wg_force_underload, 0, CTL_CREATE, CTL_EOL);
   5266 	sysctl_createv(clog, 0, &node, NULL,
   5267 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   5268 	    CTLTYPE_INT, "debug",
   5269 	    SYSCTL_DESCR("set debug flags 1=log 2=trace 4=dump 8=packet"),
   5270 	    NULL, 0, &wg_debug, 0, CTL_CREATE, CTL_EOL);
   5271 }
   5272 #endif
   5273 
   5274 #ifdef WG_RUMPKERNEL
   5275 static bool
   5276 wg_user_mode(struct wg_softc *wg)
   5277 {
   5278 
   5279 	return wg->wg_user != NULL;
   5280 }
   5281 
   5282 static int
   5283 wg_ioctl_linkstr(struct wg_softc *wg, struct ifdrv *ifd)
   5284 {
   5285 	struct ifnet *ifp = &wg->wg_if;
   5286 	int error;
   5287 
   5288 	if (ifp->if_flags & IFF_UP)
   5289 		return EBUSY;
   5290 
   5291 	if (ifd->ifd_cmd == IFLINKSTR_UNSET) {
   5292 		/* XXX do nothing */
   5293 		return 0;
   5294 	} else if (ifd->ifd_cmd != 0) {
   5295 		return EINVAL;
   5296 	} else if (wg->wg_user != NULL) {
   5297 		return EBUSY;
   5298 	}
   5299 
   5300 	/* Assume \0 included */
   5301 	if (ifd->ifd_len > IFNAMSIZ) {
   5302 		return E2BIG;
   5303 	} else if (ifd->ifd_len < 1) {
   5304 		return EINVAL;
   5305 	}
   5306 
   5307 	char tun_name[IFNAMSIZ];
   5308 	error = copyinstr(ifd->ifd_data, tun_name, ifd->ifd_len, NULL);
   5309 	if (error != 0)
   5310 		return error;
   5311 
   5312 	if (strncmp(tun_name, "tun", 3) != 0)
   5313 		return EINVAL;
   5314 
   5315 	error = rumpuser_wg_create(tun_name, wg, &wg->wg_user);
   5316 
   5317 	return error;
   5318 }
   5319 
   5320 static int
   5321 wg_send_user(struct wg_peer *wgp, struct mbuf *m)
   5322 {
   5323 	int error;
   5324 	struct psref psref;
   5325 	struct wg_sockaddr *wgsa;
   5326 	struct wg_softc *wg = wgp->wgp_sc;
   5327 	struct iovec iov[1];
   5328 
   5329 	wgsa = wg_get_endpoint_sa(wgp, &psref);
   5330 
   5331 	iov[0].iov_base = mtod(m, void *);
   5332 	iov[0].iov_len = m->m_len;
   5333 
   5334 	/* Send messages to a peer via an ordinary socket. */
   5335 	error = rumpuser_wg_send_peer(wg->wg_user, wgsatosa(wgsa), iov, 1);
   5336 
   5337 	wg_put_sa(wgp, wgsa, &psref);
   5338 
   5339 	m_freem(m);
   5340 
   5341 	return error;
   5342 }
   5343 
   5344 static void
   5345 wg_input_user(struct ifnet *ifp, struct mbuf *m, const int af)
   5346 {
   5347 	struct wg_softc *wg = ifp->if_softc;
   5348 	struct iovec iov[2];
   5349 	struct sockaddr_storage ss;
   5350 
   5351 	KASSERT(af == AF_INET || af == AF_INET6);
   5352 
   5353 	WG_TRACE("");
   5354 
   5355 	switch (af) {
   5356 #ifdef INET
   5357 	case AF_INET: {
   5358 		struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
   5359 		struct ip *ip;
   5360 
   5361 		KASSERT(m->m_len >= sizeof(struct ip));
   5362 		ip = mtod(m, struct ip *);
   5363 		sockaddr_in_init(sin, &ip->ip_dst, 0);
   5364 		break;
   5365 	}
   5366 #endif
   5367 #ifdef INET6
   5368 	case AF_INET6: {
   5369 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
   5370 		struct ip6_hdr *ip6;
   5371 
   5372 		KASSERT(m->m_len >= sizeof(struct ip6_hdr));
   5373 		ip6 = mtod(m, struct ip6_hdr *);
   5374 		sockaddr_in6_init(sin6, &ip6->ip6_dst, 0, 0, 0);
   5375 		break;
   5376 	}
   5377 #endif
   5378 	default:
   5379 		goto out;
   5380 	}
   5381 
   5382 	iov[0].iov_base = &ss;
   5383 	iov[0].iov_len = ss.ss_len;
   5384 	iov[1].iov_base = mtod(m, void *);
   5385 	iov[1].iov_len = m->m_len;
   5386 
   5387 	WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
   5388 
   5389 	/* Send decrypted packets to users via a tun. */
   5390 	rumpuser_wg_send_user(wg->wg_user, iov, 2);
   5391 
   5392 out:	m_freem(m);
   5393 }
   5394 
   5395 static int
   5396 wg_bind_port_user(struct wg_softc *wg, const uint16_t port)
   5397 {
   5398 	int error;
   5399 	uint16_t old_port = wg->wg_listen_port;
   5400 
   5401 	if (port != 0 && old_port == port)
   5402 		return 0;
   5403 
   5404 	error = rumpuser_wg_sock_bind(wg->wg_user, port);
   5405 	if (error)
   5406 		return error;
   5407 
   5408 	wg->wg_listen_port = port;
   5409 	return 0;
   5410 }
   5411 
   5412 /*
   5413  * Receive user packets.
   5414  */
   5415 void
   5416 rumpkern_wg_recv_user(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
   5417 {
   5418 	struct ifnet *ifp = &wg->wg_if;
   5419 	struct mbuf *m;
   5420 	const struct sockaddr *dst;
   5421 	int error;
   5422 
   5423 	WG_TRACE("");
   5424 
   5425 	dst = iov[0].iov_base;
   5426 
   5427 	m = m_gethdr(M_DONTWAIT, MT_DATA);
   5428 	if (m == NULL)
   5429 		return;
   5430 	m->m_len = m->m_pkthdr.len = 0;
   5431 	m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
   5432 
   5433 	WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
   5434 	WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
   5435 
   5436 	error = wg_output(ifp, m, dst, NULL); /* consumes m */
   5437 	if (error)
   5438 		WG_DLOG("wg_output failed, error=%d\n", error);
   5439 }
   5440 
   5441 /*
   5442  * Receive packets from a peer.
   5443  */
   5444 void
   5445 rumpkern_wg_recv_peer(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
   5446 {
   5447 	struct mbuf *m;
   5448 	const struct sockaddr *src;
   5449 	int bound;
   5450 
   5451 	WG_TRACE("");
   5452 
   5453 	src = iov[0].iov_base;
   5454 
   5455 	m = m_gethdr(M_DONTWAIT, MT_DATA);
   5456 	if (m == NULL)
   5457 		return;
   5458 	m->m_len = m->m_pkthdr.len = 0;
   5459 	m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
   5460 
   5461 	WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
   5462 	WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
   5463 
   5464 	bound = curlwp_bind();
   5465 	wg_handle_packet(wg, m, src);
   5466 	curlwp_bindx(bound);
   5467 }
   5468 #endif /* WG_RUMPKERNEL */
   5469 
   5470 /*
   5471  * Module infrastructure
   5472  */
   5473 #include "if_module.h"
   5474 
   5475 IF_MODULE(MODULE_CLASS_DRIVER, wg, "sodium,blake2s")
   5476