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