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