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