Home | History | Annotate | Line # | Download | only in net
if_wg.c revision 1.12
      1 /*	$NetBSD: if_wg.c,v 1.12 2020/08/20 21:34:32 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.12 2020/08/20 21:34:32 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_task_send_init_message(struct wg_softc *wg, struct wg_peer *wgp)
   2637 {
   2638 	struct psref psref;
   2639 	struct wg_session *wgs;
   2640 
   2641 	WG_TRACE("WGP_TASK_SEND_INIT_MESSAGE");
   2642 
   2643 	if (!wgp->wgp_endpoint_available) {
   2644 		WGLOG(LOG_DEBUG, "No endpoint available\n");
   2645 		/* XXX should do something? */
   2646 		return;
   2647 	}
   2648 
   2649 	wgs = wg_get_stable_session(wgp, &psref);
   2650 	if (wgs->wgs_state == WGS_STATE_UNKNOWN) {
   2651 		wg_put_session(wgs, &psref);
   2652 		wg_send_handshake_msg_init(wg, wgp);
   2653 	} else {
   2654 		wg_put_session(wgs, &psref);
   2655 		/* rekey */
   2656 		wgs = wg_get_unstable_session(wgp, &psref);
   2657 		if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE)
   2658 			wg_send_handshake_msg_init(wg, wgp);
   2659 		wg_put_session(wgs, &psref);
   2660 	}
   2661 }
   2662 
   2663 static void
   2664 wg_task_endpoint_changed(struct wg_softc *wg, struct wg_peer *wgp)
   2665 {
   2666 
   2667 	WG_TRACE("WGP_TASK_ENDPOINT_CHANGED");
   2668 
   2669 	mutex_enter(wgp->wgp_lock);
   2670 	if (wgp->wgp_endpoint_changing) {
   2671 		pserialize_perform(wgp->wgp_psz);
   2672 		psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref,
   2673 		    wg_psref_class);
   2674 		psref_target_init(&wgp->wgp_endpoint0->wgsa_psref,
   2675 		    wg_psref_class);
   2676 		wgp->wgp_endpoint_changing = false;
   2677 	}
   2678 	mutex_exit(wgp->wgp_lock);
   2679 }
   2680 
   2681 static void
   2682 wg_task_send_keepalive_message(struct wg_softc *wg, struct wg_peer *wgp)
   2683 {
   2684 	struct psref psref;
   2685 	struct wg_session *wgs;
   2686 
   2687 	WG_TRACE("WGP_TASK_SEND_KEEPALIVE_MESSAGE");
   2688 
   2689 	wgs = wg_get_stable_session(wgp, &psref);
   2690 	wg_send_keepalive_msg(wgp, wgs);
   2691 	wg_put_session(wgs, &psref);
   2692 }
   2693 
   2694 static void
   2695 wg_task_destroy_prev_session(struct wg_softc *wg, struct wg_peer *wgp)
   2696 {
   2697 	struct wg_session *wgs;
   2698 
   2699 	WG_TRACE("WGP_TASK_DESTROY_PREV_SESSION");
   2700 
   2701 	mutex_enter(wgp->wgp_lock);
   2702 	wgs = wgp->wgp_session_unstable;
   2703 	mutex_enter(wgs->wgs_lock);
   2704 	if (wgs->wgs_state == WGS_STATE_DESTROYING) {
   2705 		pserialize_perform(wgp->wgp_psz);
   2706 		psref_target_destroy(&wgs->wgs_psref, wg_psref_class);
   2707 		psref_target_init(&wgs->wgs_psref, wg_psref_class);
   2708 		wg_clear_states(wgs);
   2709 		wgs->wgs_state = WGS_STATE_UNKNOWN;
   2710 	}
   2711 	mutex_exit(wgs->wgs_lock);
   2712 	mutex_exit(wgp->wgp_lock);
   2713 }
   2714 
   2715 static void
   2716 wg_process_peer_tasks(struct wg_softc *wg)
   2717 {
   2718 	struct wg_peer *wgp;
   2719 	int s;
   2720 
   2721 	/* XXX should avoid checking all peers */
   2722 	s = pserialize_read_enter();
   2723 	WG_PEER_READER_FOREACH(wgp, wg) {
   2724 		struct psref psref;
   2725 		unsigned int tasks;
   2726 
   2727 		if (wgp->wgp_tasks == 0)
   2728 			continue;
   2729 
   2730 		wg_get_peer(wgp, &psref);
   2731 		pserialize_read_exit(s);
   2732 
   2733 	restart:
   2734 		tasks = atomic_swap_uint(&wgp->wgp_tasks, 0);
   2735 		KASSERT(tasks != 0);
   2736 
   2737 		WG_DLOG("tasks=%x\n", tasks);
   2738 
   2739 		if (ISSET(tasks, WGP_TASK_SEND_INIT_MESSAGE))
   2740 			wg_task_send_init_message(wg, wgp);
   2741 		if (ISSET(tasks, WGP_TASK_ENDPOINT_CHANGED))
   2742 			wg_task_endpoint_changed(wg, wgp);
   2743 		if (ISSET(tasks, WGP_TASK_SEND_KEEPALIVE_MESSAGE))
   2744 			wg_task_send_keepalive_message(wg, wgp);
   2745 		if (ISSET(tasks, WGP_TASK_DESTROY_PREV_SESSION))
   2746 			wg_task_destroy_prev_session(wg, wgp);
   2747 
   2748 		/* New tasks may be scheduled during processing tasks */
   2749 		WG_DLOG("wgp_tasks=%d\n", wgp->wgp_tasks);
   2750 		if (wgp->wgp_tasks != 0)
   2751 			goto restart;
   2752 
   2753 		s = pserialize_read_enter();
   2754 		wg_put_peer(wgp, &psref);
   2755 	}
   2756 	pserialize_read_exit(s);
   2757 }
   2758 
   2759 static void
   2760 wg_worker(void *arg)
   2761 {
   2762 	struct wg_softc *wg = arg;
   2763 	struct wg_worker *wgw = wg->wg_worker;
   2764 	bool todie = false;
   2765 
   2766 	KASSERT(wg != NULL);
   2767 	KASSERT(wgw != NULL);
   2768 
   2769 	while (!todie) {
   2770 		int reasons;
   2771 		int bound;
   2772 
   2773 		mutex_enter(&wgw->wgw_lock);
   2774 		/* New tasks may come during task handling */
   2775 		while ((reasons = wgw->wgw_wakeup_reasons) == 0 &&
   2776 		    !(todie = wgw->wgw_todie))
   2777 			cv_wait(&wgw->wgw_cv, &wgw->wgw_lock);
   2778 		wgw->wgw_wakeup_reasons = 0;
   2779 		mutex_exit(&wgw->wgw_lock);
   2780 
   2781 		bound = curlwp_bind();
   2782 		if (ISSET(reasons, WG_WAKEUP_REASON_RECEIVE_PACKETS_IPV4))
   2783 			wg_receive_packets(wg, AF_INET);
   2784 		if (ISSET(reasons, WG_WAKEUP_REASON_RECEIVE_PACKETS_IPV6))
   2785 			wg_receive_packets(wg, AF_INET6);
   2786 		if (ISSET(reasons, WG_WAKEUP_REASON_PEER))
   2787 			wg_process_peer_tasks(wg);
   2788 		curlwp_bindx(bound);
   2789 	}
   2790 	kthread_exit(0);
   2791 }
   2792 
   2793 static void
   2794 wg_wakeup_worker(struct wg_worker *wgw, const int reason)
   2795 {
   2796 
   2797 	mutex_enter(&wgw->wgw_lock);
   2798 	wgw->wgw_wakeup_reasons |= reason;
   2799 	cv_broadcast(&wgw->wgw_cv);
   2800 	mutex_exit(&wgw->wgw_lock);
   2801 }
   2802 
   2803 static int
   2804 wg_bind_port(struct wg_softc *wg, const uint16_t port)
   2805 {
   2806 	int error;
   2807 	struct wg_worker *wgw = wg->wg_worker;
   2808 	uint16_t old_port = wg->wg_listen_port;
   2809 
   2810 	if (port != 0 && old_port == port)
   2811 		return 0;
   2812 
   2813 	struct sockaddr_in _sin, *sin = &_sin;
   2814 	sin->sin_len = sizeof(*sin);
   2815 	sin->sin_family = AF_INET;
   2816 	sin->sin_addr.s_addr = INADDR_ANY;
   2817 	sin->sin_port = htons(port);
   2818 
   2819 	error = sobind(wgw->wgw_so4, sintosa(sin), curlwp);
   2820 	if (error != 0)
   2821 		return error;
   2822 
   2823 #ifdef INET6
   2824 	struct sockaddr_in6 _sin6, *sin6 = &_sin6;
   2825 	sin6->sin6_len = sizeof(*sin6);
   2826 	sin6->sin6_family = AF_INET6;
   2827 	sin6->sin6_addr = in6addr_any;
   2828 	sin6->sin6_port = htons(port);
   2829 
   2830 	error = sobind(wgw->wgw_so6, sin6tosa(sin6), curlwp);
   2831 	if (error != 0)
   2832 		return error;
   2833 #endif
   2834 
   2835 	wg->wg_listen_port = port;
   2836 
   2837 	return 0;
   2838 }
   2839 
   2840 static void
   2841 wg_so_upcall(struct socket *so, void *arg, int events, int waitflag)
   2842 {
   2843 	struct wg_worker *wgw = arg;
   2844 	int reason;
   2845 
   2846 	reason = (so->so_proto->pr_domain->dom_family == AF_INET) ?
   2847 	    WG_WAKEUP_REASON_RECEIVE_PACKETS_IPV4 :
   2848 	    WG_WAKEUP_REASON_RECEIVE_PACKETS_IPV6;
   2849 	wg_wakeup_worker(wgw, reason);
   2850 }
   2851 
   2852 static int
   2853 wg_overudp_cb(struct mbuf **mp, int offset, struct socket *so,
   2854     struct sockaddr *src, void *arg)
   2855 {
   2856 	struct wg_softc *wg = arg;
   2857 	struct wg_msg wgm;
   2858 	struct mbuf *m = *mp;
   2859 
   2860 	WG_TRACE("enter");
   2861 
   2862 	m_copydata(m, offset, sizeof(struct wg_msg), &wgm);
   2863 	WG_DLOG("type=%d\n", wgm.wgm_type);
   2864 
   2865 	switch (wgm.wgm_type) {
   2866 	case WG_MSG_TYPE_DATA:
   2867 		m_adj(m, offset);
   2868 		wg_handle_msg_data(wg, m, src);
   2869 		*mp = NULL;
   2870 		return 1;
   2871 	default:
   2872 		break;
   2873 	}
   2874 
   2875 	return 0;
   2876 }
   2877 
   2878 static int
   2879 wg_worker_socreate(struct wg_softc *wg, struct wg_worker *wgw, const int af,
   2880     struct socket **sop)
   2881 {
   2882 	int error;
   2883 	struct socket *so;
   2884 
   2885 	error = socreate(af, &so, SOCK_DGRAM, 0, curlwp, NULL);
   2886 	if (error != 0)
   2887 		return error;
   2888 
   2889 	solock(so);
   2890 	so->so_upcallarg = wgw;
   2891 	so->so_upcall = wg_so_upcall;
   2892 	so->so_rcv.sb_flags |= SB_UPCALL;
   2893 	if (af == AF_INET)
   2894 		in_pcb_register_overudp_cb(sotoinpcb(so), wg_overudp_cb, wg);
   2895 #if INET6
   2896 	else
   2897 		in6_pcb_register_overudp_cb(sotoin6pcb(so), wg_overudp_cb, wg);
   2898 #endif
   2899 	sounlock(so);
   2900 
   2901 	*sop = so;
   2902 
   2903 	return 0;
   2904 }
   2905 
   2906 static int
   2907 wg_worker_init(struct wg_softc *wg)
   2908 {
   2909 	int error;
   2910 	struct wg_worker *wgw;
   2911 	const char *ifname = wg->wg_if.if_xname;
   2912 	struct socket *so;
   2913 
   2914 	wgw = kmem_zalloc(sizeof(struct wg_worker), KM_SLEEP);
   2915 
   2916 	mutex_init(&wgw->wgw_lock, MUTEX_DEFAULT, IPL_NONE);
   2917 	cv_init(&wgw->wgw_cv, ifname);
   2918 	wgw->wgw_todie = false;
   2919 	wgw->wgw_wakeup_reasons = 0;
   2920 
   2921 	error = wg_worker_socreate(wg, wgw, AF_INET, &so);
   2922 	if (error != 0)
   2923 		goto error;
   2924 	wgw->wgw_so4 = so;
   2925 #ifdef INET6
   2926 	error = wg_worker_socreate(wg, wgw, AF_INET6, &so);
   2927 	if (error != 0)
   2928 		goto error;
   2929 	wgw->wgw_so6 = so;
   2930 #endif
   2931 
   2932 	wg->wg_worker = wgw;
   2933 
   2934 	error = kthread_create(PRI_NONE, KTHREAD_MPSAFE | KTHREAD_MUSTJOIN,
   2935 	    NULL, wg_worker, wg, &wg->wg_worker_lwp, "%s", ifname);
   2936 	if (error != 0)
   2937 		goto error;
   2938 
   2939 	return 0;
   2940 
   2941 error:
   2942 #ifdef INET6
   2943 	if (wgw->wgw_so6 != NULL)
   2944 		soclose(wgw->wgw_so6);
   2945 #endif
   2946 	if (wgw->wgw_so4 != NULL)
   2947 		soclose(wgw->wgw_so4);
   2948 	cv_destroy(&wgw->wgw_cv);
   2949 	mutex_destroy(&wgw->wgw_lock);
   2950 
   2951 	return error;
   2952 }
   2953 
   2954 static void
   2955 wg_worker_destroy(struct wg_softc *wg)
   2956 {
   2957 	struct wg_worker *wgw = wg->wg_worker;
   2958 
   2959 	mutex_enter(&wgw->wgw_lock);
   2960 	wgw->wgw_todie = true;
   2961 	wgw->wgw_wakeup_reasons = 0;
   2962 	cv_broadcast(&wgw->wgw_cv);
   2963 	mutex_exit(&wgw->wgw_lock);
   2964 
   2965 	kthread_join(wg->wg_worker_lwp);
   2966 
   2967 #ifdef INET6
   2968 	soclose(wgw->wgw_so6);
   2969 #endif
   2970 	soclose(wgw->wgw_so4);
   2971 	cv_destroy(&wgw->wgw_cv);
   2972 	mutex_destroy(&wgw->wgw_lock);
   2973 	kmem_free(wg->wg_worker, sizeof(struct wg_worker));
   2974 	wg->wg_worker = NULL;
   2975 }
   2976 
   2977 static bool
   2978 wg_session_hit_limits(struct wg_session *wgs)
   2979 {
   2980 
   2981 	/*
   2982 	 * [W] 6.2: Transport Message Limits
   2983 	 * "After REJECT-AFTER-MESSAGES transport data messages or after the
   2984 	 *  current secure session is REJECT-AFTER-TIME seconds old, whichever
   2985 	 *  comes first, WireGuard will refuse to send any more transport data
   2986 	 *  messages using the current secure session, ..."
   2987 	 */
   2988 	KASSERT(wgs->wgs_time_established != 0);
   2989 	if ((time_uptime - wgs->wgs_time_established) > wg_reject_after_time) {
   2990 		WG_DLOG("The session hits REJECT_AFTER_TIME\n");
   2991 		return true;
   2992 	} else if (wgs->wgs_send_counter > wg_reject_after_messages) {
   2993 		WG_DLOG("The session hits REJECT_AFTER_MESSAGES\n");
   2994 		return true;
   2995 	}
   2996 
   2997 	return false;
   2998 }
   2999 
   3000 static void
   3001 wg_peer_softint(void *arg)
   3002 {
   3003 	struct wg_peer *wgp = (struct wg_peer *)arg;
   3004 	struct wg_session *wgs;
   3005 	struct mbuf *m;
   3006 	struct psref psref;
   3007 
   3008 	wgs = wg_get_stable_session(wgp, &psref);
   3009 	if (wgs->wgs_state != WGS_STATE_ESTABLISHED) {
   3010 		/* XXX how to treat? */
   3011 		WG_TRACE("skipped");
   3012 		goto out;
   3013 	}
   3014 	if (wg_session_hit_limits(wgs)) {
   3015 		wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3016 		goto out;
   3017 	}
   3018 	WG_TRACE("running");
   3019 
   3020 	while ((m = pcq_get(wgp->wgp_q)) != NULL) {
   3021 		wg_send_data_msg(wgp, wgs, m);
   3022 	}
   3023 out:
   3024 	wg_put_session(wgs, &psref);
   3025 }
   3026 
   3027 static void
   3028 wg_rekey_timer(void *arg)
   3029 {
   3030 	struct wg_peer *wgp = arg;
   3031 
   3032 	mutex_enter(wgp->wgp_lock);
   3033 	if (__predict_true(wgp->wgp_state != WGP_STATE_DESTROYING)) {
   3034 		wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3035 	}
   3036 	mutex_exit(wgp->wgp_lock);
   3037 }
   3038 
   3039 static void
   3040 wg_purge_pending_packets(struct wg_peer *wgp)
   3041 {
   3042 	struct mbuf *m;
   3043 
   3044 	while ((m = pcq_get(wgp->wgp_q)) != NULL) {
   3045 		m_freem(m);
   3046 	}
   3047 }
   3048 
   3049 static void
   3050 wg_handshake_timeout_timer(void *arg)
   3051 {
   3052 	struct wg_peer *wgp = arg;
   3053 	struct wg_session *wgs;
   3054 	struct psref psref;
   3055 
   3056 	WG_TRACE("enter");
   3057 
   3058 	mutex_enter(wgp->wgp_lock);
   3059 	if (__predict_false(wgp->wgp_state == WGP_STATE_DESTROYING)) {
   3060 		mutex_exit(wgp->wgp_lock);
   3061 		return;
   3062 	}
   3063 	mutex_exit(wgp->wgp_lock);
   3064 
   3065 	KASSERT(wgp->wgp_handshake_start_time != 0);
   3066 	wgs = wg_get_unstable_session(wgp, &psref);
   3067 	KASSERT(wgs->wgs_state == WGS_STATE_INIT_ACTIVE);
   3068 
   3069 	/* [W] 6.4 Handshake Initiation Retransmission */
   3070 	if ((time_uptime - wgp->wgp_handshake_start_time) >
   3071 	    wg_rekey_attempt_time) {
   3072 		/* Give up handshaking */
   3073 		wgs->wgs_state = WGS_STATE_UNKNOWN;
   3074 		wg_clear_states(wgs);
   3075 		wgp->wgp_state = WGP_STATE_GIVEUP;
   3076 		wgp->wgp_handshake_start_time = 0;
   3077 		wg_put_session(wgs, &psref);
   3078 		WG_TRACE("give up");
   3079 		/*
   3080 		 * If a new data packet comes, handshaking will be retried
   3081 		 * and a new session would be established at that time,
   3082 		 * however we don't want to send pending packets then.
   3083 		 */
   3084 		wg_purge_pending_packets(wgp);
   3085 		return;
   3086 	}
   3087 
   3088 	/* No response for an initiation message sent, retry handshaking */
   3089 	wgs->wgs_state = WGS_STATE_UNKNOWN;
   3090 	wg_clear_states(wgs);
   3091 	wg_put_session(wgs, &psref);
   3092 
   3093 	wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3094 }
   3095 
   3096 static struct wg_peer *
   3097 wg_alloc_peer(struct wg_softc *wg)
   3098 {
   3099 	struct wg_peer *wgp;
   3100 
   3101 	wgp = kmem_zalloc(sizeof(*wgp), KM_SLEEP);
   3102 
   3103 	wgp->wgp_sc = wg;
   3104 	wgp->wgp_state = WGP_STATE_INIT;
   3105 	wgp->wgp_q = pcq_create(1024, KM_SLEEP);
   3106 	wgp->wgp_si = softint_establish(SOFTINT_NET, wg_peer_softint, wgp);
   3107 	callout_init(&wgp->wgp_rekey_timer, CALLOUT_MPSAFE);
   3108 	callout_setfunc(&wgp->wgp_rekey_timer, wg_rekey_timer, wgp);
   3109 	callout_init(&wgp->wgp_handshake_timeout_timer, CALLOUT_MPSAFE);
   3110 	callout_setfunc(&wgp->wgp_handshake_timeout_timer,
   3111 	    wg_handshake_timeout_timer, wgp);
   3112 	callout_init(&wgp->wgp_session_dtor_timer, CALLOUT_MPSAFE);
   3113 	callout_setfunc(&wgp->wgp_session_dtor_timer,
   3114 	    wg_session_dtor_timer, wgp);
   3115 	PSLIST_ENTRY_INIT(wgp, wgp_peerlist_entry);
   3116 	wgp->wgp_endpoint_changing = false;
   3117 	wgp->wgp_endpoint_available = false;
   3118 	wgp->wgp_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3119 	wgp->wgp_psz = pserialize_create();
   3120 	psref_target_init(&wgp->wgp_psref, wg_psref_class);
   3121 
   3122 	wgp->wgp_endpoint = kmem_zalloc(sizeof(*wgp->wgp_endpoint), KM_SLEEP);
   3123 	wgp->wgp_endpoint0 = kmem_zalloc(sizeof(*wgp->wgp_endpoint0), KM_SLEEP);
   3124 	psref_target_init(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
   3125 	psref_target_init(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
   3126 
   3127 	struct wg_session *wgs;
   3128 	wgp->wgp_session_stable = kmem_zalloc(sizeof(struct wg_session), KM_SLEEP);
   3129 	wgp->wgp_session_unstable = kmem_zalloc(sizeof(struct wg_session), KM_SLEEP);
   3130 	wgs = wgp->wgp_session_stable;
   3131 	wgs->wgs_peer = wgp;
   3132 	wgs->wgs_state = WGS_STATE_UNKNOWN;
   3133 	psref_target_init(&wgs->wgs_psref, wg_psref_class);
   3134 	wgs->wgs_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3135 	wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
   3136 	mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_NONE);
   3137 
   3138 	wgs = wgp->wgp_session_unstable;
   3139 	wgs->wgs_peer = wgp;
   3140 	wgs->wgs_state = WGS_STATE_UNKNOWN;
   3141 	psref_target_init(&wgs->wgs_psref, wg_psref_class);
   3142 	wgs->wgs_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3143 	wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
   3144 	mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_NONE);
   3145 
   3146 	return wgp;
   3147 }
   3148 
   3149 static void
   3150 wg_destroy_peer(struct wg_peer *wgp)
   3151 {
   3152 	struct wg_session *wgs;
   3153 	struct wg_softc *wg = wgp->wgp_sc;
   3154 
   3155 	rw_enter(wg->wg_rwlock, RW_WRITER);
   3156 	for (int i = 0; i < wgp->wgp_n_allowedips; i++) {
   3157 		struct wg_allowedip *wga = &wgp->wgp_allowedips[i];
   3158 		struct radix_node_head *rnh = wg_rnh(wg, wga->wga_family);
   3159 		struct radix_node *rn;
   3160 
   3161 		KASSERT(rnh != NULL);
   3162 		rn = rnh->rnh_deladdr(&wga->wga_sa_addr,
   3163 		    &wga->wga_sa_mask, rnh);
   3164 		if (rn == NULL) {
   3165 			char addrstr[128];
   3166 			sockaddr_format(&wga->wga_sa_addr, addrstr,
   3167 			    sizeof(addrstr));
   3168 			WGLOG(LOG_WARNING, "Couldn't delete %s", addrstr);
   3169 		}
   3170 	}
   3171 	rw_exit(wg->wg_rwlock);
   3172 
   3173 	softint_disestablish(wgp->wgp_si);
   3174 	callout_halt(&wgp->wgp_rekey_timer, NULL);
   3175 	callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
   3176 	callout_halt(&wgp->wgp_session_dtor_timer, NULL);
   3177 
   3178 	wgs = wgp->wgp_session_unstable;
   3179 	psref_target_destroy(&wgs->wgs_psref, wg_psref_class);
   3180 	mutex_obj_free(wgs->wgs_lock);
   3181 	mutex_destroy(&wgs->wgs_recvwin->lock);
   3182 	kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
   3183 	kmem_free(wgs, sizeof(*wgs));
   3184 	wgs = wgp->wgp_session_stable;
   3185 	psref_target_destroy(&wgs->wgs_psref, wg_psref_class);
   3186 	mutex_obj_free(wgs->wgs_lock);
   3187 	mutex_destroy(&wgs->wgs_recvwin->lock);
   3188 	kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
   3189 	kmem_free(wgs, sizeof(*wgs));
   3190 
   3191 	psref_target_destroy(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
   3192 	psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
   3193 	kmem_free(wgp->wgp_endpoint, sizeof(*wgp->wgp_endpoint));
   3194 	kmem_free(wgp->wgp_endpoint0, sizeof(*wgp->wgp_endpoint0));
   3195 
   3196 	pserialize_destroy(wgp->wgp_psz);
   3197 	pcq_destroy(wgp->wgp_q);
   3198 	mutex_obj_free(wgp->wgp_lock);
   3199 
   3200 	kmem_free(wgp, sizeof(*wgp));
   3201 }
   3202 
   3203 static void
   3204 wg_destroy_all_peers(struct wg_softc *wg)
   3205 {
   3206 	struct wg_peer *wgp;
   3207 
   3208 restart:
   3209 	mutex_enter(wg->wg_lock);
   3210 	WG_PEER_WRITER_FOREACH(wgp, wg) {
   3211 		WG_PEER_WRITER_REMOVE(wgp);
   3212 		mutex_enter(wgp->wgp_lock);
   3213 		wgp->wgp_state = WGP_STATE_DESTROYING;
   3214 		pserialize_perform(wgp->wgp_psz);
   3215 		mutex_exit(wgp->wgp_lock);
   3216 		PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
   3217 		break;
   3218 	}
   3219 	mutex_exit(wg->wg_lock);
   3220 
   3221 	if (wgp == NULL)
   3222 		return;
   3223 
   3224 	psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
   3225 
   3226 	wg_destroy_peer(wgp);
   3227 
   3228 	goto restart;
   3229 }
   3230 
   3231 static int
   3232 wg_destroy_peer_name(struct wg_softc *wg, const char *name)
   3233 {
   3234 	struct wg_peer *wgp;
   3235 
   3236 	mutex_enter(wg->wg_lock);
   3237 	WG_PEER_WRITER_FOREACH(wgp, wg) {
   3238 		if (strcmp(wgp->wgp_name, name) == 0)
   3239 			break;
   3240 	}
   3241 	if (wgp != NULL) {
   3242 		WG_PEER_WRITER_REMOVE(wgp);
   3243 		wg->wg_npeers--;
   3244 		mutex_enter(wgp->wgp_lock);
   3245 		wgp->wgp_state = WGP_STATE_DESTROYING;
   3246 		pserialize_perform(wgp->wgp_psz);
   3247 		mutex_exit(wgp->wgp_lock);
   3248 		PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
   3249 	}
   3250 	mutex_exit(wg->wg_lock);
   3251 
   3252 	if (wgp == NULL)
   3253 		return ENOENT;
   3254 
   3255 	psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
   3256 
   3257 	wg_destroy_peer(wgp);
   3258 
   3259 	return 0;
   3260 }
   3261 
   3262 static int
   3263 wg_if_attach(struct wg_softc *wg)
   3264 {
   3265 	int error;
   3266 
   3267 	wg->wg_if.if_addrlen = 0;
   3268 	wg->wg_if.if_mtu = WG_MTU;
   3269 	wg->wg_if.if_flags = IFF_POINTOPOINT;
   3270 	wg->wg_if.if_extflags = IFEF_NO_LINK_STATE_CHANGE;
   3271 	wg->wg_if.if_extflags |= IFEF_MPSAFE;
   3272 	wg->wg_if.if_ioctl = wg_ioctl;
   3273 	wg->wg_if.if_output = wg_output;
   3274 	wg->wg_if.if_init = wg_init;
   3275 	wg->wg_if.if_stop = wg_stop;
   3276 	wg->wg_if.if_type = IFT_WIREGUARD;
   3277 	wg->wg_if.if_dlt = DLT_NULL;
   3278 	wg->wg_if.if_softc = wg;
   3279 	IFQ_SET_READY(&wg->wg_if.if_snd);
   3280 
   3281 	error = if_initialize(&wg->wg_if);
   3282 	if (error != 0)
   3283 		return error;
   3284 
   3285 	if_alloc_sadl(&wg->wg_if);
   3286 	if_register(&wg->wg_if);
   3287 
   3288 	bpf_attach(&wg->wg_if, DLT_NULL, sizeof(uint32_t));
   3289 
   3290 	return 0;
   3291 }
   3292 
   3293 static int
   3294 wg_clone_create(struct if_clone *ifc, int unit)
   3295 {
   3296 	struct wg_softc *wg;
   3297 	int error;
   3298 
   3299 	wg = kmem_zalloc(sizeof(struct wg_softc), KM_SLEEP);
   3300 
   3301 	if_initname(&wg->wg_if, ifc->ifc_name, unit);
   3302 
   3303 	error = wg_worker_init(wg);
   3304 	if (error != 0) {
   3305 		kmem_free(wg, sizeof(struct wg_softc));
   3306 		return error;
   3307 	}
   3308 
   3309 	rn_inithead((void **)&wg->wg_rtable_ipv4,
   3310 	    offsetof(struct sockaddr_in, sin_addr) * NBBY);
   3311 #ifdef INET6
   3312 	rn_inithead((void **)&wg->wg_rtable_ipv6,
   3313 	    offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
   3314 #endif
   3315 
   3316 	PSLIST_INIT(&wg->wg_peers);
   3317 	wg->wg_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
   3318 	wg->wg_rwlock = rw_obj_alloc();
   3319 	wg->wg_ops = &wg_ops_rumpkernel;
   3320 
   3321 	error = wg_if_attach(wg);
   3322 	if (error != 0) {
   3323 		wg_worker_destroy(wg);
   3324 		if (wg->wg_rtable_ipv4 != NULL)
   3325 			free(wg->wg_rtable_ipv4, M_RTABLE);
   3326 		if (wg->wg_rtable_ipv6 != NULL)
   3327 			free(wg->wg_rtable_ipv6, M_RTABLE);
   3328 		PSLIST_DESTROY(&wg->wg_peers);
   3329 		mutex_obj_free(wg->wg_lock);
   3330 		kmem_free(wg, sizeof(struct wg_softc));
   3331 		return error;
   3332 	}
   3333 
   3334 	mutex_enter(&wg_softcs.lock);
   3335 	LIST_INSERT_HEAD(&wg_softcs.list, wg, wg_list);
   3336 	mutex_exit(&wg_softcs.lock);
   3337 
   3338 	return 0;
   3339 }
   3340 
   3341 static int
   3342 wg_clone_destroy(struct ifnet *ifp)
   3343 {
   3344 	struct wg_softc *wg = (void *) ifp;
   3345 
   3346 	mutex_enter(&wg_softcs.lock);
   3347 	LIST_REMOVE(wg, wg_list);
   3348 	mutex_exit(&wg_softcs.lock);
   3349 
   3350 #ifdef WG_RUMPKERNEL
   3351 	if (wg_user_mode(wg)) {
   3352 		rumpuser_wg_destroy(wg->wg_user);
   3353 		wg->wg_user = NULL;
   3354 	}
   3355 #endif
   3356 
   3357 	bpf_detach(ifp);
   3358 	if_detach(ifp);
   3359 	wg_worker_destroy(wg);
   3360 	wg_destroy_all_peers(wg);
   3361 	if (wg->wg_rtable_ipv4 != NULL)
   3362 		free(wg->wg_rtable_ipv4, M_RTABLE);
   3363 	if (wg->wg_rtable_ipv6 != NULL)
   3364 		free(wg->wg_rtable_ipv6, M_RTABLE);
   3365 
   3366 	PSLIST_DESTROY(&wg->wg_peers);
   3367 	mutex_obj_free(wg->wg_lock);
   3368 	rw_obj_free(wg->wg_rwlock);
   3369 
   3370 	kmem_free(wg, sizeof(struct wg_softc));
   3371 
   3372 	return 0;
   3373 }
   3374 
   3375 static struct wg_peer *
   3376 wg_pick_peer_by_sa(struct wg_softc *wg, const struct sockaddr *sa,
   3377     struct psref *psref)
   3378 {
   3379 	struct radix_node_head *rnh;
   3380 	struct radix_node *rn;
   3381 	struct wg_peer *wgp = NULL;
   3382 	struct wg_allowedip *wga;
   3383 
   3384 #ifdef WG_DEBUG_LOG
   3385 	char addrstr[128];
   3386 	sockaddr_format(sa, addrstr, sizeof(addrstr));
   3387 	WG_DLOG("sa=%s\n", addrstr);
   3388 #endif
   3389 
   3390 	rw_enter(wg->wg_rwlock, RW_READER);
   3391 
   3392 	rnh = wg_rnh(wg, sa->sa_family);
   3393 	if (rnh == NULL)
   3394 		goto out;
   3395 
   3396 	rn = rnh->rnh_matchaddr(sa, rnh);
   3397 	if (rn == NULL || (rn->rn_flags & RNF_ROOT) != 0)
   3398 		goto out;
   3399 
   3400 	WG_TRACE("success");
   3401 
   3402 	wga = (struct wg_allowedip *)rn;
   3403 	wgp = wga->wga_peer;
   3404 	wg_get_peer(wgp, psref);
   3405 
   3406 out:
   3407 	rw_exit(wg->wg_rwlock);
   3408 	return wgp;
   3409 }
   3410 
   3411 static void
   3412 wg_fill_msg_data(struct wg_softc *wg, struct wg_peer *wgp,
   3413     struct wg_session *wgs, struct wg_msg_data *wgmd)
   3414 {
   3415 
   3416 	memset(wgmd, 0, sizeof(*wgmd));
   3417 	wgmd->wgmd_type = WG_MSG_TYPE_DATA;
   3418 	wgmd->wgmd_receiver = wgs->wgs_receiver_index;
   3419 	/* [W] 5.4.6: msg.counter := Nm^send */
   3420 	/* [W] 5.4.6: Nm^send := Nm^send + 1 */
   3421 	wgmd->wgmd_counter = atomic_inc_64_nv(&wgs->wgs_send_counter) - 1;
   3422 	WG_DLOG("counter=%"PRIu64"\n", wgmd->wgmd_counter);
   3423 }
   3424 
   3425 static int
   3426 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
   3427     const struct rtentry *rt)
   3428 {
   3429 	struct wg_softc *wg = ifp->if_softc;
   3430 	int error = 0;
   3431 	int bound;
   3432 	struct psref psref;
   3433 
   3434 	/* TODO make the nest limit configurable via sysctl */
   3435 	error = if_tunnel_check_nesting(ifp, m, 1);
   3436 	if (error != 0) {
   3437 		m_freem(m);
   3438 		WGLOG(LOG_ERR, "tunneling loop detected and packet dropped\n");
   3439 		return error;
   3440 	}
   3441 
   3442 	bound = curlwp_bind();
   3443 
   3444 	IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
   3445 
   3446 	bpf_mtap_af(ifp, dst->sa_family, m, BPF_D_OUT);
   3447 
   3448 	m->m_flags &= ~(M_BCAST|M_MCAST);
   3449 
   3450 	struct wg_peer *wgp = wg_pick_peer_by_sa(wg, dst, &psref);
   3451 	if (wgp == NULL) {
   3452 		WG_TRACE("peer not found");
   3453 		error = EHOSTUNREACH;
   3454 		goto error;
   3455 	}
   3456 
   3457 	/* Clear checksum-offload flags. */
   3458 	m->m_pkthdr.csum_flags = 0;
   3459 	m->m_pkthdr.csum_data = 0;
   3460 
   3461 	if (!pcq_put(wgp->wgp_q, m)) {
   3462 		error = ENOBUFS;
   3463 		goto error;
   3464 	}
   3465 
   3466 	struct psref psref_wgs;
   3467 	struct wg_session *wgs;
   3468 	wgs = wg_get_stable_session(wgp, &psref_wgs);
   3469 	if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
   3470 	    !wg_session_hit_limits(wgs)) {
   3471 		kpreempt_disable();
   3472 		softint_schedule(wgp->wgp_si);
   3473 		kpreempt_enable();
   3474 		WG_TRACE("softint scheduled");
   3475 	} else {
   3476 		wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3477 		WG_TRACE("softint NOT scheduled");
   3478 	}
   3479 	wg_put_session(wgs, &psref_wgs);
   3480 	wg_put_peer(wgp, &psref);
   3481 
   3482 	return 0;
   3483 
   3484 error:
   3485 	if (wgp != NULL)
   3486 		wg_put_peer(wgp, &psref);
   3487 	if (m != NULL)
   3488 		m_freem(m);
   3489 	curlwp_bindx(bound);
   3490 	return error;
   3491 }
   3492 
   3493 static int
   3494 wg_send_udp(struct wg_peer *wgp, struct mbuf *m)
   3495 {
   3496 	struct psref psref;
   3497 	struct wg_sockaddr *wgsa;
   3498 	int error;
   3499 	struct socket *so = wg_get_so_by_peer(wgp);
   3500 
   3501 	solock(so);
   3502 	wgsa = wg_get_endpoint_sa(wgp, &psref);
   3503 	if (wgsatosa(wgsa)->sa_family == AF_INET) {
   3504 		error = udp_send(so, m, wgsatosa(wgsa), NULL, curlwp);
   3505 	} else {
   3506 #ifdef INET6
   3507 		error = udp6_output(sotoin6pcb(so), m, wgsatosin6(wgsa),
   3508 		    NULL, curlwp);
   3509 #else
   3510 		error = EPROTONOSUPPORT;
   3511 #endif
   3512 	}
   3513 	wg_put_sa(wgp, wgsa, &psref);
   3514 	sounlock(so);
   3515 
   3516 	return error;
   3517 }
   3518 
   3519 /* Inspired by pppoe_get_mbuf */
   3520 static struct mbuf *
   3521 wg_get_mbuf(size_t leading_len, size_t len)
   3522 {
   3523 	struct mbuf *m;
   3524 
   3525 	m = m_gethdr(M_DONTWAIT, MT_DATA);
   3526 	if (m == NULL)
   3527 		return NULL;
   3528 	if (len + leading_len > MHLEN) {
   3529 		m_clget(m, M_DONTWAIT);
   3530 		if ((m->m_flags & M_EXT) == 0) {
   3531 			m_free(m);
   3532 			return NULL;
   3533 		}
   3534 	}
   3535 	m->m_data += leading_len;
   3536 	m->m_pkthdr.len = m->m_len = len;
   3537 
   3538 	return m;
   3539 }
   3540 
   3541 static int
   3542 wg_send_data_msg(struct wg_peer *wgp, struct wg_session *wgs,
   3543     struct mbuf *m)
   3544 {
   3545 	struct wg_softc *wg = wgp->wgp_sc;
   3546 	int error;
   3547 	size_t inner_len, padded_len, encrypted_len;
   3548 	char *padded_buf = NULL;
   3549 	size_t mlen;
   3550 	struct wg_msg_data *wgmd;
   3551 	bool free_padded_buf = false;
   3552 	struct mbuf *n;
   3553 	size_t leading_len = max_linkhdr + sizeof(struct ip6_hdr) +
   3554 	    sizeof(struct udphdr);
   3555 
   3556 	mlen = m_length(m);
   3557 	inner_len = mlen;
   3558 	padded_len = roundup(mlen, 16);
   3559 	encrypted_len = padded_len + WG_AUTHTAG_LEN;
   3560 	WG_DLOG("inner=%lu, padded=%lu, encrypted_len=%lu\n",
   3561 	    inner_len, padded_len, encrypted_len);
   3562 	if (mlen != 0) {
   3563 		bool success;
   3564 		success = m_ensure_contig(&m, padded_len);
   3565 		if (success) {
   3566 			padded_buf = mtod(m, char *);
   3567 		} else {
   3568 			padded_buf = kmem_intr_alloc(padded_len, KM_NOSLEEP);
   3569 			if (padded_buf == NULL) {
   3570 				error = ENOBUFS;
   3571 				goto end;
   3572 			}
   3573 			free_padded_buf = true;
   3574 			m_copydata(m, 0, mlen, padded_buf);
   3575 		}
   3576 		memset(padded_buf + mlen, 0, padded_len - inner_len);
   3577 	}
   3578 
   3579 	n = wg_get_mbuf(leading_len, sizeof(*wgmd) + encrypted_len);
   3580 	if (n == NULL) {
   3581 		error = ENOBUFS;
   3582 		goto end;
   3583 	}
   3584 	wgmd = mtod(n, struct wg_msg_data *);
   3585 	wg_fill_msg_data(wg, wgp, wgs, wgmd);
   3586 	/* [W] 5.4.6: AEAD(Tm^send, Nm^send, P, e) */
   3587 	wg_algo_aead_enc((char *)wgmd + sizeof(*wgmd), encrypted_len,
   3588 	    wgs->wgs_tkey_send, wgmd->wgmd_counter, padded_buf, padded_len,
   3589 	    NULL, 0);
   3590 
   3591 	error = wg->wg_ops->send_data_msg(wgp, n);
   3592 	if (error == 0) {
   3593 		struct ifnet *ifp = &wg->wg_if;
   3594 		if_statadd(ifp, if_obytes, mlen);
   3595 		if_statinc(ifp, if_opackets);
   3596 		if (wgs->wgs_is_initiator && wgs->wgs_time_last_data_sent == 0) {
   3597 			/*
   3598 			 * [W] 6.2 Transport Message Limits
   3599 			 * "if a peer is the initiator of a current secure
   3600 			 *  session, WireGuard will send a handshake initiation
   3601 			 *  message to begin a new secure session if, after
   3602 			 *  transmitting a transport data message, the current
   3603 			 *  secure session is REKEY-AFTER-TIME seconds old,"
   3604 			 */
   3605 			wg_schedule_rekey_timer(wgp);
   3606 		}
   3607 		wgs->wgs_time_last_data_sent = time_uptime;
   3608 		if (wgs->wgs_send_counter >= wg_rekey_after_messages) {
   3609 			/*
   3610 			 * [W] 6.2 Transport Message Limits
   3611 			 * "WireGuard will try to create a new session, by
   3612 			 *  sending a handshake initiation message (section
   3613 			 *  5.4.2), after it has sent REKEY-AFTER-MESSAGES
   3614 			 *  transport data messages..."
   3615 			 */
   3616 			wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
   3617 		}
   3618 	}
   3619 end:
   3620 	m_freem(m);
   3621 	if (free_padded_buf)
   3622 		kmem_intr_free(padded_buf, padded_len);
   3623 	return error;
   3624 }
   3625 
   3626 static void
   3627 wg_input(struct ifnet *ifp, struct mbuf *m, const int af)
   3628 {
   3629 	pktqueue_t *pktq;
   3630 	size_t pktlen;
   3631 
   3632 	KASSERT(af == AF_INET || af == AF_INET6);
   3633 
   3634 	WG_TRACE("");
   3635 
   3636 	m_set_rcvif(m, ifp);
   3637 	pktlen = m->m_pkthdr.len;
   3638 
   3639 	bpf_mtap_af(ifp, af, m, BPF_D_IN);
   3640 
   3641 	switch (af) {
   3642 	case AF_INET:
   3643 		pktq = ip_pktq;
   3644 		break;
   3645 #ifdef INET6
   3646 	case AF_INET6:
   3647 		pktq = ip6_pktq;
   3648 		break;
   3649 #endif
   3650 	default:
   3651 		panic("invalid af=%d", af);
   3652 	}
   3653 
   3654 	const u_int h = curcpu()->ci_index;
   3655 	if (__predict_true(pktq_enqueue(pktq, m, h))) {
   3656 		if_statadd(ifp, if_ibytes, pktlen);
   3657 		if_statinc(ifp, if_ipackets);
   3658 	} else {
   3659 		m_freem(m);
   3660 	}
   3661 }
   3662 
   3663 static void
   3664 wg_calc_pubkey(uint8_t pubkey[WG_STATIC_KEY_LEN],
   3665     const uint8_t privkey[WG_STATIC_KEY_LEN])
   3666 {
   3667 
   3668 	crypto_scalarmult_base(pubkey, privkey);
   3669 }
   3670 
   3671 static int
   3672 wg_rtable_add_route(struct wg_softc *wg, struct wg_allowedip *wga)
   3673 {
   3674 	struct radix_node_head *rnh;
   3675 	struct radix_node *rn;
   3676 	int error = 0;
   3677 
   3678 	rw_enter(wg->wg_rwlock, RW_WRITER);
   3679 	rnh = wg_rnh(wg, wga->wga_family);
   3680 	KASSERT(rnh != NULL);
   3681 	rn = rnh->rnh_addaddr(&wga->wga_sa_addr, &wga->wga_sa_mask, rnh,
   3682 	    wga->wga_nodes);
   3683 	rw_exit(wg->wg_rwlock);
   3684 
   3685 	if (rn == NULL)
   3686 		error = EEXIST;
   3687 
   3688 	return error;
   3689 }
   3690 
   3691 static int
   3692 wg_handle_prop_peer(struct wg_softc *wg, prop_dictionary_t peer,
   3693     struct wg_peer **wgpp)
   3694 {
   3695 	int error = 0;
   3696 	const void *pubkey;
   3697 	size_t pubkey_len;
   3698 	const void *psk;
   3699 	size_t psk_len;
   3700 	const char *name = NULL;
   3701 
   3702 	if (prop_dictionary_get_string(peer, "name", &name)) {
   3703 		if (strlen(name) > WG_PEER_NAME_MAXLEN) {
   3704 			error = EINVAL;
   3705 			goto out;
   3706 		}
   3707 	}
   3708 
   3709 	if (!prop_dictionary_get_data(peer, "public_key",
   3710 		&pubkey, &pubkey_len)) {
   3711 		error = EINVAL;
   3712 		goto out;
   3713 	}
   3714 #ifdef WG_DEBUG_DUMP
   3715 	log(LOG_DEBUG, "pubkey=%p, pubkey_len=%lu\n", pubkey, pubkey_len);
   3716 	for (int _i = 0; _i < pubkey_len; _i++)
   3717 		log(LOG_DEBUG, "%c", ((const char *)pubkey)[_i]);
   3718 	log(LOG_DEBUG, "\n");
   3719 #endif
   3720 
   3721 	struct wg_peer *wgp = wg_alloc_peer(wg);
   3722 	memcpy(wgp->wgp_pubkey, pubkey, sizeof(wgp->wgp_pubkey));
   3723 	if (name != NULL)
   3724 		strncpy(wgp->wgp_name, name, sizeof(wgp->wgp_name));
   3725 
   3726 	if (prop_dictionary_get_data(peer, "preshared_key", &psk, &psk_len)) {
   3727 		if (psk_len != sizeof(wgp->wgp_psk)) {
   3728 			error = EINVAL;
   3729 			goto out;
   3730 		}
   3731 		memcpy(wgp->wgp_psk, psk, sizeof(wgp->wgp_psk));
   3732 	}
   3733 
   3734 	struct sockaddr_storage sockaddr;
   3735 	const void *addr;
   3736 	size_t addr_len;
   3737 
   3738 	if (!prop_dictionary_get_data(peer, "endpoint", &addr, &addr_len))
   3739 		goto skip_endpoint;
   3740 	memcpy(&sockaddr, addr, addr_len);
   3741 	switch (sockaddr.ss_family) {
   3742 	case AF_INET: {
   3743 		struct sockaddr_in sin;
   3744 		sockaddr_copy(sintosa(&sin), sizeof(sin),
   3745 		    (struct sockaddr *)&sockaddr);
   3746 		sockaddr_copy(sintosa(&wgp->wgp_sin),
   3747 		    sizeof(wgp->wgp_sin), (struct sockaddr *)&sockaddr);
   3748 		char addrstr[128];
   3749 		sockaddr_format(sintosa(&sin), addrstr, sizeof(addrstr));
   3750 		WG_DLOG("addr=%s\n", addrstr);
   3751 		break;
   3752 	    }
   3753 #ifdef INET6
   3754 	case AF_INET6: {
   3755 		struct sockaddr_in6 sin6;
   3756 		char addrstr[128];
   3757 		sockaddr_copy(sintosa(&sin6), sizeof(sin6),
   3758 		    (struct sockaddr *)&sockaddr);
   3759 		sockaddr_format(sintosa(&sin6), addrstr, sizeof(addrstr));
   3760 		WG_DLOG("addr=%s\n", addrstr);
   3761 		sockaddr_copy(sin6tosa(&wgp->wgp_sin6),
   3762 		    sizeof(wgp->wgp_sin6), (struct sockaddr *)&sockaddr);
   3763 		break;
   3764 	    }
   3765 #endif
   3766 	default:
   3767 		break;
   3768 	}
   3769 	wgp->wgp_endpoint_available = true;
   3770 
   3771 	prop_array_t allowedips;
   3772 skip_endpoint:
   3773 	allowedips = prop_dictionary_get(peer, "allowedips");
   3774 	if (allowedips == NULL)
   3775 		goto skip;
   3776 
   3777 	prop_object_iterator_t _it = prop_array_iterator(allowedips);
   3778 	prop_dictionary_t prop_allowedip;
   3779 	int j = 0;
   3780 	while ((prop_allowedip = prop_object_iterator_next(_it)) != NULL) {
   3781 		struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
   3782 
   3783 		if (!prop_dictionary_get_int(prop_allowedip, "family",
   3784 			&wga->wga_family))
   3785 			continue;
   3786 		if (!prop_dictionary_get_data(prop_allowedip, "ip",
   3787 			&addr, &addr_len))
   3788 			continue;
   3789 		if (!prop_dictionary_get_uint8(prop_allowedip, "cidr",
   3790 			&wga->wga_cidr))
   3791 			continue;
   3792 
   3793 		switch (wga->wga_family) {
   3794 		case AF_INET: {
   3795 			struct sockaddr_in sin;
   3796 			char addrstr[128];
   3797 			struct in_addr mask;
   3798 			struct sockaddr_in sin_mask;
   3799 
   3800 			if (addr_len != sizeof(struct in_addr))
   3801 				return EINVAL;
   3802 			memcpy(&wga->wga_addr4, addr, addr_len);
   3803 
   3804 			sockaddr_in_init(&sin, (const struct in_addr *)addr,
   3805 			    0);
   3806 			sockaddr_copy(&wga->wga_sa_addr,
   3807 			    sizeof(sin), sintosa(&sin));
   3808 
   3809 			sockaddr_format(sintosa(&sin),
   3810 			    addrstr, sizeof(addrstr));
   3811 			WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
   3812 
   3813 			in_len2mask(&mask, wga->wga_cidr);
   3814 			sockaddr_in_init(&sin_mask, &mask, 0);
   3815 			sockaddr_copy(&wga->wga_sa_mask,
   3816 			    sizeof(sin_mask), sintosa(&sin_mask));
   3817 
   3818 			break;
   3819 		    }
   3820 #ifdef INET6
   3821 		case AF_INET6: {
   3822 			struct sockaddr_in6 sin6;
   3823 			char addrstr[128];
   3824 			struct in6_addr mask;
   3825 			struct sockaddr_in6 sin6_mask;
   3826 
   3827 			if (addr_len != sizeof(struct in6_addr))
   3828 				return EINVAL;
   3829 			memcpy(&wga->wga_addr6, addr, addr_len);
   3830 
   3831 			sockaddr_in6_init(&sin6, (const struct in6_addr *)addr,
   3832 			    0, 0, 0);
   3833 			sockaddr_copy(&wga->wga_sa_addr,
   3834 			    sizeof(sin6), sin6tosa(&sin6));
   3835 
   3836 			sockaddr_format(sin6tosa(&sin6),
   3837 			    addrstr, sizeof(addrstr));
   3838 			WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
   3839 
   3840 			in6_prefixlen2mask(&mask, wga->wga_cidr);
   3841 			sockaddr_in6_init(&sin6_mask, &mask, 0, 0, 0);
   3842 			sockaddr_copy(&wga->wga_sa_mask,
   3843 			    sizeof(sin6_mask), sin6tosa(&sin6_mask));
   3844 
   3845 			break;
   3846 		    }
   3847 #endif
   3848 		default:
   3849 			error = EINVAL;
   3850 			goto out;
   3851 		}
   3852 		wga->wga_peer = wgp;
   3853 
   3854 		error = wg_rtable_add_route(wg, wga);
   3855 		if (error != 0)
   3856 			goto out;
   3857 
   3858 		j++;
   3859 	}
   3860 	wgp->wgp_n_allowedips = j;
   3861 skip:
   3862 	*wgpp = wgp;
   3863 out:
   3864 	return error;
   3865 }
   3866 
   3867 static int
   3868 wg_alloc_prop_buf(char **_buf, struct ifdrv *ifd)
   3869 {
   3870 	int error;
   3871 	char *buf;
   3872 
   3873 	WG_DLOG("buf=%p, len=%lu\n", ifd->ifd_data, ifd->ifd_len);
   3874 	buf = kmem_alloc(ifd->ifd_len + 1, KM_SLEEP);
   3875 	error = copyin(ifd->ifd_data, buf, ifd->ifd_len);
   3876 	if (error != 0)
   3877 		return error;
   3878 	buf[ifd->ifd_len] = '\0';
   3879 #ifdef WG_DEBUG_DUMP
   3880 	for (int i = 0; i < ifd->ifd_len; i++)
   3881 		log(LOG_DEBUG, "%c", buf[i]);
   3882 	log(LOG_DEBUG, "\n");
   3883 #endif
   3884 	*_buf = buf;
   3885 	return 0;
   3886 }
   3887 
   3888 static int
   3889 wg_ioctl_set_private_key(struct wg_softc *wg, struct ifdrv *ifd)
   3890 {
   3891 	int error;
   3892 	prop_dictionary_t prop_dict;
   3893 	char *buf = NULL;
   3894 	const void *privkey;
   3895 	size_t privkey_len;
   3896 
   3897 	error = wg_alloc_prop_buf(&buf, ifd);
   3898 	if (error != 0)
   3899 		return error;
   3900 	error = EINVAL;
   3901 	prop_dict = prop_dictionary_internalize(buf);
   3902 	if (prop_dict == NULL)
   3903 		goto out;
   3904 	if (!prop_dictionary_get_data(prop_dict, "private_key",
   3905 		&privkey, &privkey_len))
   3906 		goto out;
   3907 #ifdef WG_DEBUG_DUMP
   3908 	log(LOG_DEBUG, "privkey=%p, privkey_len=%lu\n", privkey, privkey_len);
   3909 	for (int i = 0; i < privkey_len; i++)
   3910 		log(LOG_DEBUG, "%c", ((const char *)privkey)[i]);
   3911 	log(LOG_DEBUG, "\n");
   3912 #endif
   3913 	if (privkey_len != WG_STATIC_KEY_LEN)
   3914 		goto out;
   3915 	memcpy(wg->wg_privkey, privkey, WG_STATIC_KEY_LEN);
   3916 	wg_calc_pubkey(wg->wg_pubkey, wg->wg_privkey);
   3917 	error = 0;
   3918 
   3919 out:
   3920 	kmem_free(buf, ifd->ifd_len + 1);
   3921 	return error;
   3922 }
   3923 
   3924 static int
   3925 wg_ioctl_set_listen_port(struct wg_softc *wg, struct ifdrv *ifd)
   3926 {
   3927 	int error;
   3928 	prop_dictionary_t prop_dict;
   3929 	char *buf = NULL;
   3930 	uint16_t port;
   3931 
   3932 	error = wg_alloc_prop_buf(&buf, ifd);
   3933 	if (error != 0)
   3934 		return error;
   3935 	error = EINVAL;
   3936 	prop_dict = prop_dictionary_internalize(buf);
   3937 	if (prop_dict == NULL)
   3938 		goto out;
   3939 	if (!prop_dictionary_get_uint16(prop_dict, "listen_port", &port))
   3940 		goto out;
   3941 
   3942 	error = wg->wg_ops->bind_port(wg, (uint16_t)port);
   3943 
   3944 out:
   3945 	kmem_free(buf, ifd->ifd_len + 1);
   3946 	return error;
   3947 }
   3948 
   3949 static int
   3950 wg_ioctl_add_peer(struct wg_softc *wg, struct ifdrv *ifd)
   3951 {
   3952 	int error;
   3953 	prop_dictionary_t prop_dict;
   3954 	char *buf = NULL;
   3955 	struct wg_peer *wgp = NULL;
   3956 
   3957 	error = wg_alloc_prop_buf(&buf, ifd);
   3958 	if (error != 0)
   3959 		return error;
   3960 	error = EINVAL;
   3961 	prop_dict = prop_dictionary_internalize(buf);
   3962 	if (prop_dict == NULL)
   3963 		goto out;
   3964 
   3965 	error = wg_handle_prop_peer(wg, prop_dict, &wgp);
   3966 	if (error != 0)
   3967 		goto out;
   3968 
   3969 	mutex_enter(wg->wg_lock);
   3970 	WG_PEER_WRITER_INSERT_HEAD(wgp, wg);
   3971 	wg->wg_npeers++;
   3972 	mutex_exit(wg->wg_lock);
   3973 
   3974 out:
   3975 	kmem_free(buf, ifd->ifd_len + 1);
   3976 	return error;
   3977 }
   3978 
   3979 static int
   3980 wg_ioctl_delete_peer(struct wg_softc *wg, struct ifdrv *ifd)
   3981 {
   3982 	int error;
   3983 	prop_dictionary_t prop_dict;
   3984 	char *buf = NULL;
   3985 	const char *name;
   3986 
   3987 	error = wg_alloc_prop_buf(&buf, ifd);
   3988 	if (error != 0)
   3989 		return error;
   3990 	error = EINVAL;
   3991 	prop_dict = prop_dictionary_internalize(buf);
   3992 	if (prop_dict == NULL)
   3993 		goto out;
   3994 
   3995 	if (!prop_dictionary_get_string(prop_dict, "name", &name))
   3996 		goto out;
   3997 	if (strlen(name) > WG_PEER_NAME_MAXLEN)
   3998 		goto out;
   3999 
   4000 	error = wg_destroy_peer_name(wg, name);
   4001 out:
   4002 	kmem_free(buf, ifd->ifd_len + 1);
   4003 	return error;
   4004 }
   4005 
   4006 static int
   4007 wg_ioctl_get(struct wg_softc *wg, struct ifdrv *ifd)
   4008 {
   4009 	int error = ENOMEM;
   4010 	prop_dictionary_t prop_dict;
   4011 	prop_array_t peers;
   4012 	char *buf;
   4013 	struct wg_peer *wgp;
   4014 	int s, i;
   4015 
   4016 	prop_dict = prop_dictionary_create();
   4017 	if (prop_dict == NULL)
   4018 		goto error;
   4019 
   4020 	if (!prop_dictionary_set_data(prop_dict, "private_key", wg->wg_privkey,
   4021 		WG_STATIC_KEY_LEN))
   4022 		goto error;
   4023 
   4024 	if (wg->wg_listen_port != 0) {
   4025 		if (!prop_dictionary_set_uint16(prop_dict, "listen_port",
   4026 			wg->wg_listen_port))
   4027 			goto error;
   4028 	}
   4029 
   4030 	if (wg->wg_npeers == 0)
   4031 		goto skip_peers;
   4032 
   4033 	peers = prop_array_create();
   4034 	if (peers == NULL)
   4035 		goto error;
   4036 
   4037 	s = pserialize_read_enter();
   4038 	i = 0;
   4039 	WG_PEER_READER_FOREACH(wgp, wg) {
   4040 		struct psref psref;
   4041 		prop_dictionary_t prop_peer;
   4042 
   4043 		wg_get_peer(wgp, &psref);
   4044 		pserialize_read_exit(s);
   4045 
   4046 		prop_peer = prop_dictionary_create();
   4047 		if (prop_peer == NULL)
   4048 			goto next;
   4049 
   4050 		if (strlen(wgp->wgp_name) > 0) {
   4051 			if (!prop_dictionary_set_string(prop_peer, "name",
   4052 				wgp->wgp_name))
   4053 				goto next;
   4054 		}
   4055 
   4056 		if (!prop_dictionary_set_data(prop_peer, "public_key",
   4057 			wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey)))
   4058 			goto next;
   4059 
   4060 		uint8_t psk_zero[WG_PRESHARED_KEY_LEN] = {0};
   4061 		if (memcmp(wgp->wgp_psk, psk_zero, sizeof(wgp->wgp_psk) != 0)) {
   4062 			if (!prop_dictionary_set_data(prop_peer,
   4063 				"preshared_key",
   4064 				wgp->wgp_psk, sizeof(wgp->wgp_psk)))
   4065 				goto next;
   4066 		}
   4067 
   4068 		switch (wgp->wgp_sa.sa_family) {
   4069 		case AF_INET:
   4070 			if (!prop_dictionary_set_data(prop_peer, "endpoint",
   4071 				&wgp->wgp_sin, sizeof(wgp->wgp_sin)))
   4072 				goto next;
   4073 			break;
   4074 #ifdef INET6
   4075 		case AF_INET6:
   4076 			if (!prop_dictionary_set_data(prop_peer, "endpoint",
   4077 				&wgp->wgp_sin6, sizeof(wgp->wgp_sin6)))
   4078 				goto next;
   4079 			break;
   4080 #endif
   4081 		}
   4082 
   4083 		const struct timespec *t = &wgp->wgp_last_handshake_time;
   4084 
   4085 		if (!prop_dictionary_set_uint64(prop_peer,
   4086 			"last_handshake_time_sec", t->tv_sec))
   4087 			goto next;
   4088 		if (!prop_dictionary_set_uint32(prop_peer,
   4089 			"last_handshake_time_nsec", t->tv_nsec))
   4090 			goto next;
   4091 
   4092 		if (wgp->wgp_n_allowedips == 0)
   4093 			goto skip_allowedips;
   4094 
   4095 		prop_array_t allowedips = prop_array_create();
   4096 		if (allowedips == NULL)
   4097 			goto next;
   4098 		for (int j = 0; j < wgp->wgp_n_allowedips; j++) {
   4099 			struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
   4100 			prop_dictionary_t prop_allowedip;
   4101 
   4102 			prop_allowedip = prop_dictionary_create();
   4103 			if (prop_allowedip == NULL)
   4104 				break;
   4105 
   4106 			if (!prop_dictionary_set_int(prop_allowedip, "family",
   4107 				wga->wga_family))
   4108 				goto _next;
   4109 			if (!prop_dictionary_set_uint8(prop_allowedip, "cidr",
   4110 				wga->wga_cidr))
   4111 				goto _next;
   4112 
   4113 			switch (wga->wga_family) {
   4114 			case AF_INET:
   4115 				if (!prop_dictionary_set_data(prop_allowedip,
   4116 					"ip", &wga->wga_addr4,
   4117 					sizeof(wga->wga_addr4)))
   4118 					goto _next;
   4119 				break;
   4120 #ifdef INET6
   4121 			case AF_INET6:
   4122 				if (!prop_dictionary_set_data(prop_allowedip,
   4123 					"ip", &wga->wga_addr6,
   4124 					sizeof(wga->wga_addr6)))
   4125 					goto _next;
   4126 				break;
   4127 #endif
   4128 			default:
   4129 				break;
   4130 			}
   4131 			prop_array_set(allowedips, j, prop_allowedip);
   4132 		_next:
   4133 			prop_object_release(prop_allowedip);
   4134 		}
   4135 		prop_dictionary_set(prop_peer, "allowedips", allowedips);
   4136 		prop_object_release(allowedips);
   4137 
   4138 	skip_allowedips:
   4139 
   4140 		prop_array_set(peers, i, prop_peer);
   4141 	next:
   4142 		if (prop_peer)
   4143 			prop_object_release(prop_peer);
   4144 		i++;
   4145 
   4146 		s = pserialize_read_enter();
   4147 		wg_put_peer(wgp, &psref);
   4148 	}
   4149 	pserialize_read_exit(s);
   4150 
   4151 	prop_dictionary_set(prop_dict, "peers", peers);
   4152 	prop_object_release(peers);
   4153 	peers = NULL;
   4154 
   4155 skip_peers:
   4156 	buf = prop_dictionary_externalize(prop_dict);
   4157 	if (buf == NULL)
   4158 		goto error;
   4159 	if (ifd->ifd_len < (strlen(buf) + 1)) {
   4160 		error = EINVAL;
   4161 		goto error;
   4162 	}
   4163 	error = copyout(buf, ifd->ifd_data, strlen(buf) + 1);
   4164 
   4165 	free(buf, 0);
   4166 error:
   4167 	if (peers != NULL)
   4168 		prop_object_release(peers);
   4169 	if (prop_dict != NULL)
   4170 		prop_object_release(prop_dict);
   4171 
   4172 	return error;
   4173 }
   4174 
   4175 static int
   4176 wg_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   4177 {
   4178 	struct wg_softc *wg = ifp->if_softc;
   4179 	struct ifreq *ifr = data;
   4180 	struct ifaddr *ifa = data;
   4181 	struct ifdrv *ifd = data;
   4182 	int error = 0;
   4183 
   4184 	switch (cmd) {
   4185 	case SIOCINITIFADDR:
   4186 		if (ifa->ifa_addr->sa_family != AF_LINK &&
   4187 		    (ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
   4188 		    (IFF_UP | IFF_RUNNING)) {
   4189 			ifp->if_flags |= IFF_UP;
   4190 			error = ifp->if_init(ifp);
   4191 		}
   4192 		break;
   4193 
   4194 	case SIOCADDMULTI:
   4195 	case SIOCDELMULTI:
   4196 		switch (ifr->ifr_addr.sa_family) {
   4197 		case AF_INET:	/* IP supports Multicast */
   4198 			break;
   4199 #ifdef INET6
   4200 		case AF_INET6:	/* IP6 supports Multicast */
   4201 			break;
   4202 #endif
   4203 		default:  /* Other protocols doesn't support Multicast */
   4204 			error = EAFNOSUPPORT;
   4205 			break;
   4206 		}
   4207 		break;
   4208 
   4209 	case SIOCSDRVSPEC:
   4210 		switch (ifd->ifd_cmd) {
   4211 		case WG_IOCTL_SET_PRIVATE_KEY:
   4212 			error = wg_ioctl_set_private_key(wg, ifd);
   4213 			break;
   4214 		case WG_IOCTL_SET_LISTEN_PORT:
   4215 			error = wg_ioctl_set_listen_port(wg, ifd);
   4216 			break;
   4217 		case WG_IOCTL_ADD_PEER:
   4218 			error = wg_ioctl_add_peer(wg, ifd);
   4219 			break;
   4220 		case WG_IOCTL_DELETE_PEER:
   4221 			error = wg_ioctl_delete_peer(wg, ifd);
   4222 			break;
   4223 		default:
   4224 			error = EINVAL;
   4225 			break;
   4226 		}
   4227 		break;
   4228 	case SIOCGDRVSPEC:
   4229 		error = wg_ioctl_get(wg, ifd);
   4230 		break;
   4231 
   4232 	case SIOCSIFFLAGS:
   4233 		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
   4234 			break;
   4235 		switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
   4236 		case IFF_RUNNING:
   4237 			/*
   4238 			 * If interface is marked down and it is running,
   4239 			 * then stop and disable it.
   4240 			 */
   4241 			(*ifp->if_stop)(ifp, 1);
   4242 			break;
   4243 		case IFF_UP:
   4244 			/*
   4245 			 * If interface is marked up and it is stopped, then
   4246 			 * start it.
   4247 			 */
   4248 			error = (*ifp->if_init)(ifp);
   4249 			break;
   4250 		default:
   4251 			break;
   4252 		}
   4253 		break;
   4254 
   4255 #ifdef WG_RUMPKERNEL
   4256 	case SIOCSLINKSTR:
   4257 		error = wg_ioctl_linkstr(wg, ifd);
   4258 		if (error == 0)
   4259 			wg->wg_ops = &wg_ops_rumpuser;
   4260 		break;
   4261 #endif
   4262 
   4263 	default:
   4264 		error = ifioctl_common(ifp, cmd, data);
   4265 
   4266 #ifdef WG_RUMPKERNEL
   4267 		if (!wg_user_mode(wg))
   4268 			break;
   4269 		/* Do the same to the corresponding tun device on the host */
   4270 		/*
   4271 		 * XXX Actually the command has not been handled yet.  It
   4272 		 *     will be handled via pr_ioctl form doifioctl later.
   4273 		 */
   4274 		switch (cmd) {
   4275 		case SIOCAIFADDR:
   4276 		case SIOCDIFADDR: {
   4277 			struct in_aliasreq _ifra = *(struct in_aliasreq *)data;
   4278 			struct in_aliasreq *ifra = &_ifra;
   4279 			KASSERT(error == ENOTTY);
   4280 			strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user), IFNAMSIZ);
   4281 			error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET);
   4282 			if (error == 0)
   4283 				error = ENOTTY;
   4284 			break;
   4285 		    }
   4286 #ifdef INET6
   4287 		case SIOCAIFADDR_IN6:
   4288 		case SIOCDIFADDR_IN6: {
   4289 			struct in6_aliasreq _ifra = *(struct in6_aliasreq *)data;
   4290 			struct in6_aliasreq *ifra = &_ifra;
   4291 			KASSERT(error == ENOTTY);
   4292 			strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user), IFNAMSIZ);
   4293 			error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET6);
   4294 			if (error == 0)
   4295 				error = ENOTTY;
   4296 			break;
   4297 		    }
   4298 #endif
   4299 		}
   4300 #endif /* WG_RUMPKERNEL */
   4301 	}
   4302 
   4303 	return error;
   4304 }
   4305 
   4306 static int
   4307 wg_init(struct ifnet *ifp)
   4308 {
   4309 
   4310 	ifp->if_flags |= IFF_RUNNING;
   4311 
   4312 	/* TODO flush pending packets. */
   4313 	return 0;
   4314 }
   4315 
   4316 static void
   4317 wg_stop(struct ifnet *ifp, int disable)
   4318 {
   4319 
   4320 	KASSERT((ifp->if_flags & IFF_RUNNING) != 0);
   4321 	ifp->if_flags &= ~IFF_RUNNING;
   4322 
   4323 	/* Need to do something? */
   4324 }
   4325 
   4326 #ifdef WG_DEBUG_PARAMS
   4327 SYSCTL_SETUP(sysctl_net_wireguard_setup, "sysctl net.wireguard setup")
   4328 {
   4329 	const struct sysctlnode *node = NULL;
   4330 
   4331 	sysctl_createv(clog, 0, NULL, &node,
   4332 	    CTLFLAG_PERMANENT,
   4333 	    CTLTYPE_NODE, "wireguard",
   4334 	    SYSCTL_DESCR("WireGuard"),
   4335 	    NULL, 0, NULL, 0,
   4336 	    CTL_NET, CTL_CREATE, CTL_EOL);
   4337 	sysctl_createv(clog, 0, &node, NULL,
   4338 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   4339 	    CTLTYPE_LONG, "rekey_after_messages",
   4340 	    SYSCTL_DESCR("session liftime by messages"),
   4341 	    NULL, 0, &wg_rekey_after_messages, 0, CTL_CREATE, CTL_EOL);
   4342 	sysctl_createv(clog, 0, &node, NULL,
   4343 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   4344 	    CTLTYPE_LONG, "rekey_after_time",
   4345 	    SYSCTL_DESCR("session liftime"),
   4346 	    NULL, 0, &wg_rekey_after_time, 0, CTL_CREATE, CTL_EOL);
   4347 	sysctl_createv(clog, 0, &node, NULL,
   4348 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   4349 	    CTLTYPE_LONG, "rekey_timeout",
   4350 	    SYSCTL_DESCR("session handshake retry time"),
   4351 	    NULL, 0, &wg_rekey_timeout, 0, CTL_CREATE, CTL_EOL);
   4352 	sysctl_createv(clog, 0, &node, NULL,
   4353 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   4354 	    CTLTYPE_LONG, "rekey_attempt_time",
   4355 	    SYSCTL_DESCR("session handshake timeout"),
   4356 	    NULL, 0, &wg_rekey_attempt_time, 0, CTL_CREATE, CTL_EOL);
   4357 	sysctl_createv(clog, 0, &node, NULL,
   4358 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   4359 	    CTLTYPE_LONG, "keepalive_timeout",
   4360 	    SYSCTL_DESCR("keepalive timeout"),
   4361 	    NULL, 0, &wg_keepalive_timeout, 0, CTL_CREATE, CTL_EOL);
   4362 	sysctl_createv(clog, 0, &node, NULL,
   4363 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   4364 	    CTLTYPE_BOOL, "force_underload",
   4365 	    SYSCTL_DESCR("force to detemine under load"),
   4366 	    NULL, 0, &wg_force_underload, 0, CTL_CREATE, CTL_EOL);
   4367 }
   4368 #endif
   4369 
   4370 #ifdef WG_RUMPKERNEL
   4371 static bool
   4372 wg_user_mode(struct wg_softc *wg)
   4373 {
   4374 
   4375 	return wg->wg_user != NULL;
   4376 }
   4377 
   4378 static int
   4379 wg_ioctl_linkstr(struct wg_softc *wg, struct ifdrv *ifd)
   4380 {
   4381 	struct ifnet *ifp = &wg->wg_if;
   4382 	int error;
   4383 
   4384 	if (ifp->if_flags & IFF_UP)
   4385 		return EBUSY;
   4386 
   4387 	if (ifd->ifd_cmd == IFLINKSTR_UNSET) {
   4388 		/* XXX do nothing */
   4389 		return 0;
   4390 	} else if (ifd->ifd_cmd != 0) {
   4391 		return EINVAL;
   4392 	} else if (wg->wg_user != NULL) {
   4393 		return EBUSY;
   4394 	}
   4395 
   4396 	/* Assume \0 included */
   4397 	if (ifd->ifd_len > IFNAMSIZ) {
   4398 		return E2BIG;
   4399 	} else if (ifd->ifd_len < 1) {
   4400 		return EINVAL;
   4401 	}
   4402 
   4403 	char tun_name[IFNAMSIZ];
   4404 	error = copyinstr(ifd->ifd_data, tun_name, ifd->ifd_len, NULL);
   4405 	if (error != 0)
   4406 		return error;
   4407 
   4408 	if (strncmp(tun_name, "tun", 3) != 0)
   4409 		return EINVAL;
   4410 
   4411 	error = rumpuser_wg_create(tun_name, wg, &wg->wg_user);
   4412 
   4413 	return error;
   4414 }
   4415 
   4416 static int
   4417 wg_send_user(struct wg_peer *wgp, struct mbuf *m)
   4418 {
   4419 	int error;
   4420 	struct psref psref;
   4421 	struct wg_sockaddr *wgsa;
   4422 	struct wg_softc *wg = wgp->wgp_sc;
   4423 	struct iovec iov[1];
   4424 
   4425 	wgsa = wg_get_endpoint_sa(wgp, &psref);
   4426 
   4427 	iov[0].iov_base = mtod(m, void *);
   4428 	iov[0].iov_len = m->m_len;
   4429 
   4430 	/* Send messages to a peer via an ordinary socket. */
   4431 	error = rumpuser_wg_send_peer(wg->wg_user, wgsatosa(wgsa), iov, 1);
   4432 
   4433 	wg_put_sa(wgp, wgsa, &psref);
   4434 
   4435 	return error;
   4436 }
   4437 
   4438 static void
   4439 wg_input_user(struct ifnet *ifp, struct mbuf *m, const int af)
   4440 {
   4441 	struct wg_softc *wg = ifp->if_softc;
   4442 	struct iovec iov[2];
   4443 	struct sockaddr_storage ss;
   4444 
   4445 	KASSERT(af == AF_INET || af == AF_INET6);
   4446 
   4447 	WG_TRACE("");
   4448 
   4449 	if (af == AF_INET) {
   4450 		struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
   4451 		struct ip *ip;
   4452 		ip = mtod(m, struct ip *);
   4453 		sockaddr_in_init(sin, &ip->ip_dst, 0);
   4454 	} else {
   4455 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
   4456 		struct ip6_hdr *ip6;
   4457 		ip6 = mtod(m, struct ip6_hdr *);
   4458 		sockaddr_in6_init(sin6, &ip6->ip6_dst, 0, 0, 0);
   4459 	}
   4460 
   4461 	iov[0].iov_base = &ss;
   4462 	iov[0].iov_len = ss.ss_len;
   4463 	iov[1].iov_base = mtod(m, void *);
   4464 	iov[1].iov_len = m->m_len;
   4465 
   4466 	WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
   4467 
   4468 	/* Send decrypted packets to users via a tun. */
   4469 	rumpuser_wg_send_user(wg->wg_user, iov, 2);
   4470 }
   4471 
   4472 static int
   4473 wg_bind_port_user(struct wg_softc *wg, const uint16_t port)
   4474 {
   4475 	int error;
   4476 	uint16_t old_port = wg->wg_listen_port;
   4477 
   4478 	if (port != 0 && old_port == port)
   4479 		return 0;
   4480 
   4481 	error = rumpuser_wg_sock_bind(wg->wg_user, port);
   4482 	if (error == 0)
   4483 		wg->wg_listen_port = port;
   4484 	return error;
   4485 }
   4486 
   4487 /*
   4488  * Receive user packets.
   4489  */
   4490 void
   4491 rumpkern_wg_recv_user(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
   4492 {
   4493 	struct ifnet *ifp = &wg->wg_if;
   4494 	struct mbuf *m;
   4495 	const struct sockaddr *dst;
   4496 
   4497 	WG_TRACE("");
   4498 
   4499 	dst = iov[0].iov_base;
   4500 
   4501 	m = m_gethdr(M_NOWAIT, MT_DATA);
   4502 	if (m == NULL)
   4503 		return;
   4504 	m->m_len = m->m_pkthdr.len = 0;
   4505 	m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
   4506 
   4507 	WG_DLOG("iov_len=%lu\n", iov[1].iov_len);
   4508 	WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
   4509 
   4510 	(void)wg_output(ifp, m, dst, NULL);
   4511 }
   4512 
   4513 /*
   4514  * Receive packets from a peer.
   4515  */
   4516 void
   4517 rumpkern_wg_recv_peer(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
   4518 {
   4519 	struct mbuf *m;
   4520 	const struct sockaddr *src;
   4521 
   4522 	WG_TRACE("");
   4523 
   4524 	src = iov[0].iov_base;
   4525 
   4526 	m = m_gethdr(M_NOWAIT, MT_DATA);
   4527 	if (m == NULL)
   4528 		return;
   4529 	m->m_len = m->m_pkthdr.len = 0;
   4530 	m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
   4531 
   4532 	WG_DLOG("iov_len=%lu\n", iov[1].iov_len);
   4533 	WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
   4534 
   4535 	wg_handle_packet(wg, m, src);
   4536 }
   4537 #endif /* WG_RUMPKERNEL */
   4538 
   4539 /*
   4540  * Module infrastructure
   4541  */
   4542 #include "if_module.h"
   4543 
   4544 IF_MODULE(MODULE_CLASS_DRIVER, wg, "")
   4545