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