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