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