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