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