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