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