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