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