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