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