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