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