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