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