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