if_wg.c revision 1.143 1 /* $NetBSD: if_wg.c,v 1.143 2026/08/30 03:48:20 gutteridge 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.143 2026/08/30 03:48:20 gutteridge 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 mutex_enter(wgp->wgp_intr_lock);
2812 WG_DLOG("tasks=%d, task=%d\n", wgp->wgp_tasks, task);
2813 if (wgp->wgp_tasks == 0)
2814 /*
2815 * XXX If the current CPU is already loaded -- e.g., if
2816 * there's already a bunch of handshakes queued up --
2817 * consider tossing this over to another CPU to
2818 * distribute the load.
2819 */
2820 workqueue_enqueue(wg_wq, &wgp->wgp_work, NULL);
2821 wgp->wgp_tasks |= task;
2822 mutex_exit(wgp->wgp_intr_lock);
2823 }
2824
2825 static void
2826 wg_change_endpoint(struct wg_peer *wgp, const struct sockaddr *new)
2827 {
2828 struct wg_sockaddr *wgsa_prev;
2829
2830 WG_TRACE("Changing endpoint");
2831
2832 memcpy(wgp->wgp_endpoint0, new, new->sa_len);
2833 wgsa_prev = wgp->wgp_endpoint;
2834 atomic_store_release(&wgp->wgp_endpoint, wgp->wgp_endpoint0);
2835 wgp->wgp_endpoint0 = wgsa_prev;
2836 atomic_store_release(&wgp->wgp_endpoint_available, true);
2837
2838 wg_schedule_peer_task(wgp, WGP_TASK_ENDPOINT_CHANGED);
2839 }
2840
2841 static bool
2842 wg_validate_inner_packet(const char *packet, size_t decrypted_len, int *af)
2843 {
2844 uint16_t packet_len;
2845 const struct ip *ip;
2846
2847 if (__predict_false(decrypted_len < sizeof(*ip))) {
2848 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2849 sizeof(*ip));
2850 return false;
2851 }
2852
2853 ip = (const struct ip *)packet;
2854 if (ip->ip_v == 4)
2855 *af = AF_INET;
2856 else if (ip->ip_v == 6)
2857 *af = AF_INET6;
2858 else {
2859 WG_DLOG("ip_v=%d\n", ip->ip_v);
2860 return false;
2861 }
2862
2863 WG_DLOG("af=%d\n", *af);
2864
2865 switch (*af) {
2866 #ifdef INET
2867 case AF_INET:
2868 packet_len = ntohs(ip->ip_len);
2869 break;
2870 #endif
2871 #ifdef INET6
2872 case AF_INET6: {
2873 const struct ip6_hdr *ip6;
2874
2875 if (__predict_false(decrypted_len < sizeof(*ip6))) {
2876 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2877 sizeof(*ip6));
2878 return false;
2879 }
2880
2881 ip6 = (const struct ip6_hdr *)packet;
2882 packet_len = sizeof(*ip6) + ntohs(ip6->ip6_plen);
2883 break;
2884 }
2885 #endif
2886 default:
2887 return false;
2888 }
2889
2890 if (packet_len > decrypted_len) {
2891 WG_DLOG("packet_len %u > decrypted_len %zu\n", packet_len,
2892 decrypted_len);
2893 return false;
2894 }
2895
2896 return true;
2897 }
2898
2899 static bool
2900 wg_validate_route(struct wg_softc *wg, struct wg_peer *wgp_expected,
2901 int af, char *packet)
2902 {
2903 struct sockaddr_storage ss;
2904 struct sockaddr *sa;
2905 struct psref psref;
2906 struct wg_peer *wgp;
2907 bool ok;
2908
2909 /*
2910 * II CRYPTOKEY ROUTING
2911 * "it will only accept it if its source IP resolves in the
2912 * table to the public key used in the secure session for
2913 * decrypting it."
2914 */
2915
2916 switch (af) {
2917 #ifdef INET
2918 case AF_INET: {
2919 const struct ip *ip = (const struct ip *)packet;
2920 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
2921 sockaddr_in_init(sin, &ip->ip_src, 0);
2922 sa = sintosa(sin);
2923 break;
2924 }
2925 #endif
2926 #ifdef INET6
2927 case AF_INET6: {
2928 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)packet;
2929 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
2930 sockaddr_in6_init(sin6, &ip6->ip6_src, 0, 0, 0);
2931 sa = sin6tosa(sin6);
2932 break;
2933 }
2934 #endif
2935 default:
2936 __USE(ss);
2937 return false;
2938 }
2939
2940 wgp = wg_pick_peer_by_sa(wg, sa, &psref);
2941 ok = (wgp == wgp_expected);
2942 if (wgp != NULL)
2943 wg_put_peer(wgp, &psref);
2944
2945 return ok;
2946 }
2947
2948 static void
2949 wg_session_dtor_timer(void *arg)
2950 {
2951 struct wg_peer *wgp = arg;
2952
2953 WG_TRACE("enter");
2954
2955 wg_schedule_session_dtor_timer(wgp);
2956 wg_schedule_peer_task(wgp, WGP_TASK_DESTROY_PREV_SESSION);
2957 }
2958
2959 static void
2960 wg_schedule_session_dtor_timer(struct wg_peer *wgp)
2961 {
2962
2963 /*
2964 * If the periodic session destructor is already pending to
2965 * handle the previous session, that's fine -- leave it in
2966 * place; it will be scheduled again.
2967 */
2968 if (callout_pending(&wgp->wgp_session_dtor_timer)) {
2969 WG_DLOG("session dtor already pending\n");
2970 return;
2971 }
2972
2973 WG_DLOG("scheduling session dtor in %u secs\n", wg_reject_after_time);
2974 callout_schedule(&wgp->wgp_session_dtor_timer,
2975 wg_reject_after_time*hz);
2976 }
2977
2978 static bool
2979 sockaddr_port_match(const struct sockaddr *sa1, const struct sockaddr *sa2)
2980 {
2981 if (sa1->sa_family != sa2->sa_family)
2982 return false;
2983
2984 switch (sa1->sa_family) {
2985 #ifdef INET
2986 case AF_INET:
2987 return satocsin(sa1)->sin_port == satocsin(sa2)->sin_port;
2988 #endif
2989 #ifdef INET6
2990 case AF_INET6:
2991 return satocsin6(sa1)->sin6_port == satocsin6(sa2)->sin6_port;
2992 #endif
2993 default:
2994 return false;
2995 }
2996 }
2997
2998 static void
2999 wg_update_endpoint_if_necessary(struct wg_peer *wgp,
3000 const struct sockaddr *src)
3001 {
3002 struct wg_sockaddr *wgsa;
3003 struct psref psref;
3004
3005 wgsa = wg_get_endpoint_sa(wgp, &psref);
3006
3007 #ifdef WG_DEBUG_LOG
3008 char oldaddr[128], newaddr[128];
3009 sockaddr_format(wgsatosa(wgsa), oldaddr, sizeof(oldaddr));
3010 sockaddr_format(src, newaddr, sizeof(newaddr));
3011 WG_DLOG("old=%s, new=%s\n", oldaddr, newaddr);
3012 #endif
3013
3014 /*
3015 * III: "Since the packet has authenticated correctly, the source IP of
3016 * the outer UDP/IP packet is used to update the endpoint for peer..."
3017 */
3018 if (__predict_false(sockaddr_cmp(src, wgsatosa(wgsa)) != 0 ||
3019 !sockaddr_port_match(src, wgsatosa(wgsa)))) {
3020 /* XXX We can't change the endpoint twice in a short period */
3021 if (atomic_swap_uint(&wgp->wgp_endpoint_changing, 1) == 0) {
3022 wg_change_endpoint(wgp, src);
3023 }
3024 }
3025
3026 wg_put_sa(wgp, wgsa, &psref);
3027 }
3028
3029 static void __noinline
3030 wg_handle_msg_data(struct wg_softc *wg, struct mbuf *m,
3031 const struct sockaddr *src)
3032 {
3033 struct wg_msg_data *wgmd;
3034 char *encrypted_buf = NULL, *decrypted_buf;
3035 size_t encrypted_len, decrypted_len;
3036 struct wg_session *wgs;
3037 struct wg_peer *wgp;
3038 int state;
3039 uint32_t age;
3040 size_t mlen;
3041 struct psref psref;
3042 int error, af;
3043 bool success, free_encrypted_buf = false, ok;
3044 struct mbuf *n;
3045
3046 KASSERT(m->m_len >= sizeof(struct wg_msg_data));
3047 wgmd = mtod(m, struct wg_msg_data *);
3048
3049 KASSERT(wgmd->wgmd_type == htole32(WG_MSG_TYPE_DATA));
3050 WG_TRACE("data");
3051
3052 /* Find the putative session, or drop. */
3053 wgs = wg_lookup_session_by_index(wg, wgmd->wgmd_receiver, &psref);
3054 if (wgs == NULL) {
3055 WG_TRACE("No session found");
3056 m_freem(m);
3057 return;
3058 }
3059
3060 /*
3061 * We are only ready to handle data when in INIT_PASSIVE,
3062 * ESTABLISHED, or DESTROYING. All transitions out of that
3063 * state dissociate the session index and drain psrefs.
3064 *
3065 * atomic_load_acquire matches atomic_store_release in either
3066 * wg_handle_msg_init or wg_handle_msg_resp. (The transition
3067 * INIT_PASSIVE to ESTABLISHED in wg_task_establish_session
3068 * doesn't make a difference for this rx path.)
3069 */
3070 state = atomic_load_acquire(&wgs->wgs_state);
3071 switch (state) {
3072 case WGS_STATE_UNKNOWN:
3073 case WGS_STATE_INIT_ACTIVE:
3074 WG_TRACE("not yet ready for data");
3075 goto out;
3076 case WGS_STATE_INIT_PASSIVE:
3077 case WGS_STATE_ESTABLISHED:
3078 case WGS_STATE_DESTROYING:
3079 break;
3080 }
3081
3082 /*
3083 * Reject if the session is too old.
3084 */
3085 age = time_uptime32 - wgs->wgs_time_established;
3086 if (__predict_false(age >= wg_reject_after_time)) {
3087 WG_DLOG("session %"PRIx32" too old, %"PRIu32" sec\n",
3088 wgmd->wgmd_receiver, age);
3089 goto out;
3090 }
3091
3092 /*
3093 * Get the peer, for rate-limited logs (XXX MPSAFE, dtrace) and
3094 * to update the endpoint if authentication succeeds.
3095 */
3096 wgp = wgs->wgs_peer;
3097
3098 /*
3099 * Reject outrageously wrong sequence numbers before doing any
3100 * crypto work or taking any locks.
3101 */
3102 error = sliwin_check_fast(&wgs->wgs_recvwin->window,
3103 le64toh(wgmd->wgmd_counter));
3104 if (error) {
3105 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3106 "%s: peer %s: out-of-window packet: %"PRIu64"\n",
3107 if_name(&wg->wg_if), wgp->wgp_name,
3108 le64toh(wgmd->wgmd_counter));
3109 goto out;
3110 }
3111
3112 /* Ensure the payload and authenticator are contiguous. */
3113 mlen = m_length(m);
3114 encrypted_len = mlen - sizeof(*wgmd);
3115 if (encrypted_len < WG_AUTHTAG_LEN) {
3116 WG_DLOG("Short encrypted_len: %zu\n", encrypted_len);
3117 goto out;
3118 }
3119 success = m_ensure_contig(&m, sizeof(*wgmd) + encrypted_len);
3120 if (success) {
3121 encrypted_buf = mtod(m, char *) + sizeof(*wgmd);
3122 } else {
3123 encrypted_buf = kmem_intr_alloc(encrypted_len, KM_NOSLEEP);
3124 if (encrypted_buf == NULL) {
3125 WG_DLOG("failed to allocate encrypted_buf\n");
3126 goto out;
3127 }
3128 m_copydata(m, sizeof(*wgmd), encrypted_len, encrypted_buf);
3129 free_encrypted_buf = true;
3130 }
3131 /* m_ensure_contig may change m regardless of its result */
3132 KASSERT(m->m_len >= sizeof(*wgmd));
3133 wgmd = mtod(m, struct wg_msg_data *);
3134
3135 /*
3136 * Get a buffer for the plaintext. Add WG_AUTHTAG_LEN to avoid
3137 * a zero-length buffer (XXX). Drop if plaintext is longer
3138 * than MCLBYTES (XXX).
3139 */
3140 decrypted_len = encrypted_len - WG_AUTHTAG_LEN;
3141 if (decrypted_len > MCLBYTES) {
3142 /* FIXME handle larger data than MCLBYTES */
3143 WG_DLOG("couldn't handle larger data than MCLBYTES\n");
3144 goto out;
3145 }
3146 n = wg_get_mbuf(0, decrypted_len + WG_AUTHTAG_LEN);
3147 if (n == NULL) {
3148 WG_DLOG("wg_get_mbuf failed\n");
3149 goto out;
3150 }
3151 decrypted_buf = mtod(n, char *);
3152
3153 /* Decrypt and verify the packet. */
3154 WG_DLOG("mlen=%zu, encrypted_len=%zu\n", mlen, encrypted_len);
3155 error = wg_algo_aead_dec(decrypted_buf,
3156 encrypted_len - WG_AUTHTAG_LEN /* can be 0 */,
3157 wgs->wgs_tkey_recv, le64toh(wgmd->wgmd_counter), encrypted_buf,
3158 encrypted_len, NULL, 0);
3159 if (error != 0) {
3160 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3161 "%s: peer %s: failed to wg_algo_aead_dec\n",
3162 if_name(&wg->wg_if), wgp->wgp_name);
3163 m_freem(n);
3164 goto out;
3165 }
3166 WG_DLOG("outsize=%u\n", (u_int)decrypted_len);
3167
3168 /* Packet is genuine. Reject it if a replay or just too old. */
3169 mutex_enter(&wgs->wgs_recvwin->lock);
3170 error = sliwin_update(&wgs->wgs_recvwin->window,
3171 le64toh(wgmd->wgmd_counter));
3172 mutex_exit(&wgs->wgs_recvwin->lock);
3173 if (error) {
3174 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3175 "%s: peer %s: replay or out-of-window packet: %"PRIu64"\n",
3176 if_name(&wg->wg_if), wgp->wgp_name,
3177 le64toh(wgmd->wgmd_counter));
3178 m_freem(n);
3179 goto out;
3180 }
3181
3182 /* We're done with m now; free it and chuck the pointers. */
3183 m_freem(m);
3184 m = NULL;
3185 wgmd = NULL;
3186
3187 /*
3188 * The packet is genuine. Update the peer's endpoint if the
3189 * source address changed.
3190 *
3191 * XXX How to prevent DoS by replaying genuine packets from the
3192 * wrong source address?
3193 */
3194 wg_update_endpoint_if_necessary(wgp, src);
3195
3196 /*
3197 * Validate the encapsulated packet header and get the address
3198 * family, or drop.
3199 */
3200 ok = wg_validate_inner_packet(decrypted_buf, decrypted_len, &af);
3201 if (!ok) {
3202 m_freem(n);
3203 goto update_state;
3204 }
3205
3206 /* Submit it into our network stack if routable. */
3207 ok = wg_validate_route(wg, wgp, af, decrypted_buf);
3208 if (ok) {
3209 wg->wg_ops->input(&wg->wg_if, n, af);
3210 } else {
3211 char addrstr[INET6_ADDRSTRLEN];
3212 memset(addrstr, 0, sizeof(addrstr));
3213 switch (af) {
3214 #ifdef INET
3215 case AF_INET: {
3216 const struct ip *ip = (const struct ip *)decrypted_buf;
3217 IN_PRINT(addrstr, &ip->ip_src);
3218 break;
3219 }
3220 #endif
3221 #ifdef INET6
3222 case AF_INET6: {
3223 const struct ip6_hdr *ip6 =
3224 (const struct ip6_hdr *)decrypted_buf;
3225 IN6_PRINT(addrstr, &ip6->ip6_src);
3226 break;
3227 }
3228 #endif
3229 default:
3230 panic("invalid af=%d", af);
3231 }
3232 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3233 "%s: peer %s: invalid source address (%s)\n",
3234 if_name(&wg->wg_if), wgp->wgp_name, addrstr);
3235 m_freem(n);
3236 /*
3237 * The inner address is invalid however the session is valid
3238 * so continue the session processing below.
3239 */
3240 }
3241 n = NULL;
3242
3243 update_state:
3244 /* Update the state machine if necessary. */
3245 if (__predict_false(state == WGS_STATE_INIT_PASSIVE)) {
3246 /*
3247 * We were waiting for the initiator to send their
3248 * first data transport message, and that has happened.
3249 * Schedule a task to establish this session.
3250 */
3251 wg_schedule_peer_task(wgp, WGP_TASK_ESTABLISH_SESSION);
3252 } else {
3253 if (__predict_false(wg_need_to_send_init_message(wgs))) {
3254 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3255 }
3256 /*
3257 * [W] 6.5 Passive Keepalive
3258 * "If a peer has received a validly-authenticated transport
3259 * data message (section 5.4.6), but does not have any packets
3260 * itself to send back for KEEPALIVE-TIMEOUT seconds, it sends
3261 * a keepalive message."
3262 */
3263 const uint32_t now = time_uptime32;
3264 const uint32_t time_last_data_sent =
3265 atomic_load_relaxed(&wgs->wgs_time_last_data_sent);
3266 WG_DLOG("time_uptime32=%"PRIu32
3267 " wgs_time_last_data_sent=%"PRIu32"\n",
3268 now, time_last_data_sent);
3269 if ((now - time_last_data_sent) >= wg_keepalive_timeout) {
3270 WG_TRACE("Schedule sending keepalive message");
3271 /*
3272 * We can't send a keepalive message here to avoid
3273 * a deadlock; we already hold the solock of a socket
3274 * that is used to send the message.
3275 */
3276 wg_schedule_peer_task(wgp,
3277 WGP_TASK_SEND_KEEPALIVE_MESSAGE);
3278 }
3279 }
3280 out:
3281 wg_put_session(wgs, &psref);
3282 m_freem(m);
3283 if (free_encrypted_buf)
3284 kmem_intr_free(encrypted_buf, encrypted_len);
3285 }
3286
3287 static void __noinline
3288 wg_handle_msg_cookie(struct wg_softc *wg, const struct wg_msg_cookie *wgmc)
3289 {
3290 struct wg_session *wgs;
3291 struct wg_peer *wgp;
3292 struct psref psref;
3293 int error;
3294 uint8_t key[WG_HASH_LEN];
3295 uint8_t cookie[WG_COOKIE_LEN];
3296
3297 WG_TRACE("cookie msg received");
3298
3299 /* Find the putative session. */
3300 wgs = wg_lookup_session_by_index(wg, wgmc->wgmc_receiver, &psref);
3301 if (wgs == NULL) {
3302 WG_TRACE("No session found");
3303 return;
3304 }
3305
3306 /* Lock the peer so we can update the cookie state. */
3307 wgp = wgs->wgs_peer;
3308 mutex_enter(wgp->wgp_lock);
3309
3310 if (!wgp->wgp_last_sent_mac1_valid) {
3311 WG_TRACE("No valid mac1 sent (or expired)");
3312 goto out;
3313 }
3314
3315 /*
3316 * wgp_last_sent_mac1_valid is only set to true when we are
3317 * transitioning to INIT_ACTIVE or INIT_PASSIVE, and always
3318 * cleared on transition out of them.
3319 */
3320 KASSERTMSG((wgs->wgs_state == WGS_STATE_INIT_ACTIVE ||
3321 wgs->wgs_state == WGS_STATE_INIT_PASSIVE),
3322 "state=%d", wgs->wgs_state);
3323
3324 /* Decrypt the cookie and store it for later handshake retry. */
3325 wg_algo_mac_cookie(key, sizeof(key), wgp->wgp_pubkey,
3326 sizeof(wgp->wgp_pubkey));
3327 error = wg_algo_xaead_dec(cookie, sizeof(cookie), key,
3328 wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie),
3329 wgp->wgp_last_sent_mac1, sizeof(wgp->wgp_last_sent_mac1),
3330 wgmc->wgmc_salt);
3331 if (error != 0) {
3332 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3333 "%s: peer %s: wg_algo_aead_dec for cookie failed: "
3334 "error=%d\n", if_name(&wg->wg_if), wgp->wgp_name, error);
3335 goto out;
3336 }
3337 /*
3338 * [W] 6.6: Interaction with Cookie Reply System
3339 * "it should simply store the decrypted cookie value from the cookie
3340 * reply message, and wait for the expiration of the REKEY-TIMEOUT
3341 * timer for retrying a handshake initiation message."
3342 */
3343 wgp->wgp_latest_cookie_time = time_uptime;
3344 memcpy(wgp->wgp_latest_cookie, cookie, sizeof(wgp->wgp_latest_cookie));
3345 out:
3346 mutex_exit(wgp->wgp_lock);
3347 wg_put_session(wgs, &psref);
3348 }
3349
3350 static struct mbuf *
3351 wg_validate_msg_header(struct wg_softc *wg, struct mbuf *m)
3352 {
3353 struct wg_msg wgm;
3354 size_t mbuflen;
3355 size_t msglen;
3356
3357 /*
3358 * Get the mbuf chain length. It is already guaranteed, by
3359 * wg_overudp_cb, to be large enough for a struct wg_msg.
3360 */
3361 mbuflen = m_length(m);
3362 KASSERT(mbuflen >= sizeof(struct wg_msg));
3363
3364 /*
3365 * Copy the message header (32-bit message type) out -- we'll
3366 * worry about contiguity and alignment later.
3367 */
3368 m_copydata(m, 0, sizeof(wgm), &wgm);
3369 switch (le32toh(wgm.wgm_type)) {
3370 case WG_MSG_TYPE_INIT:
3371 msglen = sizeof(struct wg_msg_init);
3372 break;
3373 case WG_MSG_TYPE_RESP:
3374 msglen = sizeof(struct wg_msg_resp);
3375 break;
3376 case WG_MSG_TYPE_COOKIE:
3377 msglen = sizeof(struct wg_msg_cookie);
3378 break;
3379 case WG_MSG_TYPE_DATA:
3380 msglen = sizeof(struct wg_msg_data);
3381 break;
3382 default:
3383 WG_LOG_RATECHECK(&wg->wg_ppsratecheck, LOG_DEBUG,
3384 "%s: Unexpected msg type: %u\n", if_name(&wg->wg_if),
3385 le32toh(wgm.wgm_type));
3386 goto error;
3387 }
3388
3389 /* Verify the mbuf chain is long enough for this type of message. */
3390 if (__predict_false(mbuflen < msglen)) {
3391 WG_DLOG("Invalid msg size: mbuflen=%zu type=%u\n", mbuflen,
3392 le32toh(wgm.wgm_type));
3393 goto error;
3394 }
3395
3396 /* Make the message header contiguous if necessary. */
3397 if (__predict_false(m->m_len < msglen)) {
3398 m = m_pullup(m, msglen);
3399 if (m == NULL)
3400 return NULL;
3401 }
3402
3403 return m;
3404
3405 error:
3406 m_freem(m);
3407 return NULL;
3408 }
3409
3410 static void
3411 wg_handle_packet(struct wg_softc *wg, struct mbuf *m,
3412 const struct sockaddr *src)
3413 {
3414 struct wg_msg *wgm;
3415
3416 KASSERT(curlwp->l_pflag & LP_BOUND);
3417
3418 m = wg_validate_msg_header(wg, m);
3419 if (__predict_false(m == NULL))
3420 return;
3421
3422 KASSERT(m->m_len >= sizeof(struct wg_msg));
3423 wgm = mtod(m, struct wg_msg *);
3424 switch (le32toh(wgm->wgm_type)) {
3425 case WG_MSG_TYPE_INIT:
3426 wg_handle_msg_init(wg, (struct wg_msg_init *)wgm, src);
3427 break;
3428 case WG_MSG_TYPE_RESP:
3429 wg_handle_msg_resp(wg, (struct wg_msg_resp *)wgm, src);
3430 break;
3431 case WG_MSG_TYPE_COOKIE:
3432 wg_handle_msg_cookie(wg, (struct wg_msg_cookie *)wgm);
3433 break;
3434 case WG_MSG_TYPE_DATA:
3435 wg_handle_msg_data(wg, m, src);
3436 /* wg_handle_msg_data frees m for us */
3437 return;
3438 default:
3439 panic("invalid message type: %d", le32toh(wgm->wgm_type));
3440 }
3441
3442 m_freem(m);
3443 }
3444
3445 static void
3446 wg_receive_packets(struct wg_softc *wg, const int af)
3447 {
3448
3449 for (;;) {
3450 int error, flags;
3451 struct socket *so;
3452 struct mbuf *m = NULL;
3453 struct uio dummy_uio;
3454 struct mbuf *paddr = NULL;
3455 struct sockaddr *src;
3456
3457 so = wg_get_so_by_af(wg, af);
3458 flags = MSG_DONTWAIT;
3459 dummy_uio.uio_resid = 1000000000;
3460
3461 error = so->so_receive(so, &paddr, &dummy_uio, &m, NULL,
3462 &flags);
3463 if (error || m == NULL) {
3464 //if (error == EWOULDBLOCK)
3465 return;
3466 }
3467
3468 /*
3469 * wg_overudp_cb should guarantee that only packets
3470 * long enough to possibly be wg messages make it
3471 * through to us, but let's double-check out of
3472 * paranoia.
3473 */
3474 KASSERT(m_length(m) >= sizeof(struct wg_msg));
3475 if (__predict_false(m_length(m) < sizeof(struct wg_msg))) {
3476 m_freem(m);
3477 continue;
3478 }
3479
3480 KASSERT(paddr != NULL);
3481 KASSERT(paddr->m_len >= sizeof(struct sockaddr));
3482 src = mtod(paddr, struct sockaddr *);
3483
3484 wg_handle_packet(wg, m, src);
3485 }
3486 }
3487
3488 static void
3489 wg_get_peer(struct wg_peer *wgp, struct psref *psref)
3490 {
3491
3492 psref_acquire(psref, &wgp->wgp_psref, wg_psref_class);
3493 }
3494
3495 static void
3496 wg_put_peer(struct wg_peer *wgp, struct psref *psref)
3497 {
3498
3499 psref_release(psref, &wgp->wgp_psref, wg_psref_class);
3500 }
3501
3502 static void
3503 wg_task_send_init_message(struct wg_softc *wg, struct wg_peer *wgp)
3504 {
3505 struct wg_session *wgs;
3506
3507 WG_TRACE("WGP_TASK_SEND_INIT_MESSAGE");
3508
3509 KASSERT(mutex_owned(wgp->wgp_lock));
3510
3511 if (!atomic_load_acquire(&wgp->wgp_endpoint_available)) {
3512 WGLOG(LOG_DEBUG, "%s: No endpoint available\n",
3513 if_name(&wg->wg_if));
3514 /* XXX should do something? */
3515 return;
3516 }
3517
3518 /*
3519 * If we already have an established session, there's no need
3520 * to initiate a new one -- unless the rekey-after-time or
3521 * rekey-after-messages limits have passed.
3522 */
3523 wgs = wgp->wgp_session_stable;
3524 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3525 !atomic_load_relaxed(&wgs->wgs_force_rekey))
3526 return;
3527
3528 /*
3529 * Ensure we're initiating a new session. If the unstable
3530 * session is already INIT_ACTIVE or INIT_PASSIVE, this does
3531 * nothing.
3532 */
3533 wg_send_handshake_msg_init(wg, wgp);
3534 }
3535
3536 static void
3537 wg_task_retry_handshake(struct wg_softc *wg, struct wg_peer *wgp)
3538 {
3539 struct wg_session *wgs;
3540
3541 WG_TRACE("WGP_TASK_RETRY_HANDSHAKE");
3542
3543 KASSERT(mutex_owned(wgp->wgp_lock));
3544
3545 wgs = wgp->wgp_session_unstable;
3546 if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE)
3547 return;
3548
3549 KASSERT(wgp->wgp_handshake_start_time != 0);
3550
3551 /*
3552 * XXX no real need to assign a new index here, but we do need
3553 * to transition to UNKNOWN temporarily
3554 */
3555 wg_put_session_index(wg, wgs);
3556
3557 /* [W] 6.4 Handshake Initiation Retransmission */
3558 if ((time_uptime - wgp->wgp_handshake_start_time) >
3559 wg_rekey_attempt_time) {
3560 /* Give up handshaking */
3561 wgp->wgp_handshake_start_time = 0;
3562 WG_TRACE("give up");
3563
3564 /*
3565 * If a new data packet comes, handshaking will be retried
3566 * and a new session would be established at that time,
3567 * however we don't want to send pending packets then.
3568 */
3569 wg_purge_pending_packets(wgp);
3570 return;
3571 }
3572
3573 wg_task_send_init_message(wg, wgp);
3574 }
3575
3576 static void
3577 wg_task_establish_session(struct wg_softc *wg, struct wg_peer *wgp)
3578 {
3579 struct wg_session *wgs;
3580
3581 KASSERT(mutex_owned(wgp->wgp_lock));
3582
3583 wgs = wgp->wgp_session_unstable;
3584 if (wgs->wgs_state != WGS_STATE_INIT_PASSIVE)
3585 /* XXX Can this happen? */
3586 return;
3587
3588 wgs->wgs_time_last_data_sent = 0;
3589 wgs->wgs_is_initiator = false;
3590
3591 /*
3592 * Session was already ready to receive data. Transition from
3593 * INIT_PASSIVE to ESTABLISHED just so we can swap the
3594 * sessions.
3595 *
3596 * atomic_store_relaxed because this doesn't affect the data rx
3597 * path, wg_handle_msg_data -- changing from INIT_PASSIVE to
3598 * ESTABLISHED makes no difference to the data rx path, and the
3599 * transition to INIT_PASSIVE with store-release already
3600 * published the state needed by the data rx path.
3601 */
3602 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_ESTABLISHED\n",
3603 wgs->wgs_local_index, wgs->wgs_remote_index);
3604 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
3605 WG_TRACE("WGS_STATE_ESTABLISHED");
3606
3607 /*
3608 * Session is ready to send data too now that we have received
3609 * the peer initiator's first data packet.
3610 *
3611 * Swap the sessions to publish the new one as the stable
3612 * session for the data tx path, wg_output.
3613 */
3614 wg_swap_sessions(wg, wgp);
3615 KASSERT(wgs == wgp->wgp_session_stable);
3616 }
3617
3618 static void
3619 wg_task_endpoint_changed(struct wg_softc *wg, struct wg_peer *wgp)
3620 {
3621
3622 WG_TRACE("WGP_TASK_ENDPOINT_CHANGED");
3623
3624 KASSERT(mutex_owned(wgp->wgp_lock));
3625
3626 if (atomic_load_relaxed(&wgp->wgp_endpoint_changing)) {
3627 pserialize_perform(wgp->wgp_psz);
3628 mutex_exit(wgp->wgp_lock);
3629 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref,
3630 wg_psref_class);
3631 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref,
3632 wg_psref_class);
3633 mutex_enter(wgp->wgp_lock);
3634 atomic_store_release(&wgp->wgp_endpoint_changing, 0);
3635 }
3636 }
3637
3638 static void
3639 wg_task_send_keepalive_message(struct wg_softc *wg, struct wg_peer *wgp)
3640 {
3641 struct wg_session *wgs;
3642
3643 WG_TRACE("WGP_TASK_SEND_KEEPALIVE_MESSAGE");
3644
3645 KASSERT(mutex_owned(wgp->wgp_lock));
3646
3647 wgs = wgp->wgp_session_stable;
3648 if (wgs->wgs_state != WGS_STATE_ESTABLISHED)
3649 return;
3650
3651 wg_send_keepalive_msg(wgp, wgs);
3652 }
3653
3654 static void
3655 wg_task_destroy_prev_session(struct wg_softc *wg, struct wg_peer *wgp)
3656 {
3657 struct wg_session *wgs;
3658 uint32_t age;
3659
3660 WG_TRACE("WGP_TASK_DESTROY_PREV_SESSION");
3661
3662 KASSERT(mutex_owned(wgp->wgp_lock));
3663
3664 /*
3665 * If theres's any previous unstable session, i.e., one that
3666 * was ESTABLISHED and is now DESTROYING, older than
3667 * reject-after-time, destroy it. Upcoming sessions are still
3668 * in INIT_ACTIVE or INIT_PASSIVE -- we don't touch those here.
3669 */
3670 wgs = wgp->wgp_session_unstable;
3671 KASSERT(wgs->wgs_state != WGS_STATE_ESTABLISHED);
3672 if (wgs->wgs_state == WGS_STATE_DESTROYING &&
3673 ((age = (time_uptime32 - wgs->wgs_time_established)) >=
3674 wg_reject_after_time)) {
3675 WG_DLOG("destroying past session %"PRIu32" sec old\n", age);
3676 wg_put_session_index(wg, wgs);
3677 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
3678 wgs->wgs_state);
3679 }
3680
3681 /*
3682 * If theres's any ESTABLISHED stable session older than
3683 * reject-after-time, destroy it. (The stable session can also
3684 * be in UNKNOWN state -- nothing to do in that case)
3685 */
3686 wgs = wgp->wgp_session_stable;
3687 KASSERT(wgs->wgs_state != WGS_STATE_INIT_ACTIVE);
3688 KASSERT(wgs->wgs_state != WGS_STATE_INIT_PASSIVE);
3689 KASSERT(wgs->wgs_state != WGS_STATE_DESTROYING);
3690 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3691 ((age = (time_uptime32 - wgs->wgs_time_established)) >=
3692 wg_reject_after_time)) {
3693 WG_DLOG("destroying current session %"PRIu32" sec old\n", age);
3694 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_DESTROYING);
3695 wg_put_session_index(wg, wgs);
3696 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
3697 wgs->wgs_state);
3698 }
3699
3700 /*
3701 * If there's no sessions left, no need to have the timer run
3702 * until the next time around -- halt it.
3703 *
3704 * It is only ever scheduled with wgp_lock held or in the
3705 * callout itself, and callout_halt prevents rescheudling
3706 * itself, so this never races with rescheduling.
3707 */
3708 if (wgp->wgp_session_unstable->wgs_state == WGS_STATE_UNKNOWN &&
3709 wgp->wgp_session_stable->wgs_state == WGS_STATE_UNKNOWN)
3710 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
3711 }
3712
3713 static void
3714 wg_peer_work(struct work *wk, void *cookie)
3715 {
3716 struct wg_peer *wgp = container_of(wk, struct wg_peer, wgp_work);
3717 struct wg_softc *wg = wgp->wgp_sc;
3718 unsigned int tasks;
3719
3720 mutex_enter(wgp->wgp_intr_lock);
3721 while ((tasks = wgp->wgp_tasks) != 0) {
3722 wgp->wgp_tasks = 0;
3723 mutex_exit(wgp->wgp_intr_lock);
3724
3725 mutex_enter(wgp->wgp_lock);
3726 if (ISSET(tasks, WGP_TASK_SEND_INIT_MESSAGE))
3727 wg_task_send_init_message(wg, wgp);
3728 if (ISSET(tasks, WGP_TASK_RETRY_HANDSHAKE))
3729 wg_task_retry_handshake(wg, wgp);
3730 if (ISSET(tasks, WGP_TASK_ESTABLISH_SESSION))
3731 wg_task_establish_session(wg, wgp);
3732 if (ISSET(tasks, WGP_TASK_ENDPOINT_CHANGED))
3733 wg_task_endpoint_changed(wg, wgp);
3734 if (ISSET(tasks, WGP_TASK_SEND_KEEPALIVE_MESSAGE))
3735 wg_task_send_keepalive_message(wg, wgp);
3736 if (ISSET(tasks, WGP_TASK_DESTROY_PREV_SESSION))
3737 wg_task_destroy_prev_session(wg, wgp);
3738 mutex_exit(wgp->wgp_lock);
3739
3740 mutex_enter(wgp->wgp_intr_lock);
3741 }
3742 mutex_exit(wgp->wgp_intr_lock);
3743 }
3744
3745 static void
3746 wg_job(struct threadpool_job *job)
3747 {
3748 struct wg_softc *wg = container_of(job, struct wg_softc, wg_job);
3749 int bound, upcalls;
3750
3751 mutex_enter(wg->wg_intr_lock);
3752 while ((upcalls = wg->wg_upcalls) != 0) {
3753 wg->wg_upcalls = 0;
3754 mutex_exit(wg->wg_intr_lock);
3755 bound = curlwp_bind();
3756 if (ISSET(upcalls, WG_UPCALL_INET))
3757 wg_receive_packets(wg, AF_INET);
3758 if (ISSET(upcalls, WG_UPCALL_INET6))
3759 wg_receive_packets(wg, AF_INET6);
3760 curlwp_bindx(bound);
3761 mutex_enter(wg->wg_intr_lock);
3762 }
3763 threadpool_job_done(job);
3764 mutex_exit(wg->wg_intr_lock);
3765 }
3766
3767 static int
3768 wg_bind_port(struct wg_softc *wg, const uint16_t port)
3769 {
3770 int error = 0;
3771 uint16_t old_port = wg->wg_listen_port;
3772
3773 if (port != 0 && old_port == port)
3774 return 0;
3775
3776 #ifdef INET
3777 struct sockaddr_in _sin, *sin = &_sin;
3778 sin->sin_len = sizeof(*sin);
3779 sin->sin_family = AF_INET;
3780 sin->sin_addr.s_addr = INADDR_ANY;
3781 sin->sin_port = htons(port);
3782
3783 error = sobind(wg->wg_so4, sintosa(sin), curlwp);
3784 if (error)
3785 return error;
3786 #endif
3787
3788 #ifdef INET6
3789 struct sockaddr_in6 _sin6, *sin6 = &_sin6;
3790 sin6->sin6_len = sizeof(*sin6);
3791 sin6->sin6_family = AF_INET6;
3792 sin6->sin6_addr = in6addr_any;
3793 sin6->sin6_port = htons(port);
3794
3795 error = sobind(wg->wg_so6, sin6tosa(sin6), curlwp);
3796 if (error)
3797 return error;
3798 #endif
3799
3800 wg->wg_listen_port = port;
3801
3802 return error;
3803 }
3804
3805 static void
3806 wg_so_upcall(struct socket *so, void *cookie, int events, int waitflag)
3807 {
3808 struct wg_softc *wg = cookie;
3809 int reason;
3810
3811 reason = (so->so_proto->pr_domain->dom_family == AF_INET) ?
3812 WG_UPCALL_INET :
3813 WG_UPCALL_INET6;
3814
3815 mutex_enter(wg->wg_intr_lock);
3816 wg->wg_upcalls |= reason;
3817 threadpool_schedule_job(wg->wg_threadpool, &wg->wg_job);
3818 mutex_exit(wg->wg_intr_lock);
3819 }
3820
3821 /*
3822 * wg_overudp_cb(&m, offset, so, src, arg)
3823 *
3824 * Callback for incoming UDP packets in high-priority
3825 * packet-processing path.
3826 *
3827 * Three cases:
3828 *
3829 * - Data packet. Consumed here for high-priority handling.
3830 * => Returns 1 and takes ownership of m.
3831 *
3832 * - Handshake packet. Defer to thread context via so_receive in
3833 * wg_receive_packets.
3834 * => Returns 0 and leaves caller with ownership of m.
3835 *
3836 * - Invalid. Dropped on the floor and freed.
3837 * => Returns -1 and takes ownership of m (frees m).
3838 */
3839 static int
3840 wg_overudp_cb(struct mbuf **mp, int offset, struct socket *so,
3841 struct sockaddr *src, void *arg)
3842 {
3843 struct wg_softc *wg = arg;
3844 struct wg_msg wgm;
3845 struct mbuf *m = *mp;
3846
3847 WG_TRACE("enter");
3848
3849 /*
3850 * Verify the mbuf chain is long enough to have a wg msg header.
3851 * wg_receive_packets relies on this.
3852 */
3853 KASSERT(offset <= m_length(m));
3854 if (__predict_false(m_length(m) - offset < sizeof(struct wg_msg))) {
3855 /* drop on the floor */
3856 m_freem(m);
3857 *mp = NULL;
3858 return -1; /* dropped */
3859 }
3860
3861 /*
3862 * Copy the message header (32-bit message type) out -- we'll
3863 * worry about contiguity and alignment later.
3864 */
3865 m_copydata(m, offset, sizeof(struct wg_msg), &wgm);
3866 WG_DLOG("type=%d\n", le32toh(wgm.wgm_type));
3867
3868 /*
3869 * Handle DATA packets promptly as they arrive, if they are in
3870 * an active session. Other packets may require expensive
3871 * public-key crypto and are not as sensitive to latency, so
3872 * defer them to the worker thread.
3873 */
3874 switch (le32toh(wgm.wgm_type)) {
3875 case WG_MSG_TYPE_DATA:
3876 /* handle immediately */
3877 m_adj(m, offset);
3878 if (__predict_false(m->m_len < sizeof(struct wg_msg_data))) {
3879 m = m_pullup(m, sizeof(struct wg_msg_data));
3880 if (m == NULL) {
3881 *mp = NULL;
3882 return -1; /* dropped */
3883 }
3884 }
3885 wg_handle_msg_data(wg, m, src);
3886 *mp = NULL;
3887 return 1; /* consumed */
3888 case WG_MSG_TYPE_INIT:
3889 case WG_MSG_TYPE_RESP:
3890 case WG_MSG_TYPE_COOKIE:
3891 /* pass through to so_receive in wg_receive_packets */
3892 return 0; /* passthrough */
3893 default:
3894 /* drop on the floor */
3895 m_freem(m);
3896 *mp = NULL;
3897 return -1; /* dropped */
3898 }
3899 }
3900
3901 static int
3902 wg_socreate(struct wg_softc *wg, int af, struct socket **sop)
3903 {
3904 int error;
3905 struct socket *so;
3906
3907 error = socreate(af, &so, SOCK_DGRAM, 0, curlwp, NULL);
3908 if (error != 0)
3909 return error;
3910
3911 solock(so);
3912 so->so_upcallarg = wg;
3913 so->so_upcall = wg_so_upcall;
3914 so->so_rcv.sb_flags |= SB_UPCALL;
3915 inpcb_register_overudp_cb(sotoinpcb(so), wg_overudp_cb, wg);
3916 sounlock(so);
3917
3918 *sop = so;
3919
3920 return 0;
3921 }
3922
3923 static bool
3924 wg_session_hit_limits(struct wg_session *wgs)
3925 {
3926
3927 /*
3928 * [W] 6.2: Transport Message Limits
3929 * "After REJECT-AFTER-MESSAGES transport data messages or after the
3930 * current secure session is REJECT-AFTER-TIME seconds old, whichever
3931 * comes first, WireGuard will refuse to send or receive any more
3932 * transport data messages using the current secure session, ..."
3933 */
3934 KASSERT(wgs->wgs_time_established != 0 || time_uptime > UINT32_MAX);
3935 if (time_uptime32 - wgs->wgs_time_established > wg_reject_after_time) {
3936 WG_DLOG("The session hits REJECT_AFTER_TIME\n");
3937 return true;
3938 } else if (wg_session_get_send_counter(wgs) >
3939 wg_reject_after_messages) {
3940 WG_DLOG("The session hits REJECT_AFTER_MESSAGES\n");
3941 return true;
3942 }
3943
3944 return false;
3945 }
3946
3947 static void
3948 wgintr(void *cookie)
3949 {
3950 struct wg_peer *wgp;
3951 struct wg_session *wgs;
3952 struct mbuf *m;
3953 struct psref psref;
3954
3955 while ((m = pktq_dequeue(wg_pktq)) != NULL) {
3956 wgp = M_GETCTX(m, struct wg_peer *);
3957 if ((wgs = wg_get_stable_session(wgp, &psref)) == NULL) {
3958 /*
3959 * No established session. If we're the first
3960 * to try sending data, schedule a handshake
3961 * and queue the packet for when the handshake
3962 * is done; otherwise just drop the packet and
3963 * let the ongoing handshake attempt continue.
3964 * We could queue more data packets but it's
3965 * not clear that's worthwhile.
3966 */
3967 WG_TRACE("no stable session");
3968 membar_release();
3969 if ((m = atomic_swap_ptr(&wgp->wgp_pending, m)) ==
3970 NULL) {
3971 WG_TRACE("queued first packet;"
3972 " init handshake");
3973 wg_schedule_peer_task(wgp,
3974 WGP_TASK_SEND_INIT_MESSAGE);
3975 } else {
3976 membar_acquire();
3977 WG_TRACE("first packet already queued,"
3978 " dropping");
3979 }
3980 goto next0;
3981 }
3982 if (__predict_false(wg_session_hit_limits(wgs))) {
3983 WG_TRACE("stable session hit limits");
3984 membar_release();
3985 if ((m = atomic_swap_ptr(&wgp->wgp_pending, m)) ==
3986 NULL) {
3987 WG_TRACE("queued first packet in a while;"
3988 " reinit handshake");
3989 atomic_store_relaxed(&wgs->wgs_force_rekey,
3990 true);
3991 wg_schedule_peer_task(wgp,
3992 WGP_TASK_SEND_INIT_MESSAGE);
3993 } else {
3994 membar_acquire();
3995 WG_TRACE("first packet in already queued,"
3996 " dropping");
3997 }
3998 goto next1;
3999 }
4000 wg_send_data_msg(wgp, wgs, m);
4001 m = NULL; /* consumed */
4002 next1: wg_put_session(wgs, &psref);
4003 next0: m_freem(m);
4004 /* XXX Yield to avoid userland starvation? */
4005 }
4006 }
4007
4008 static void
4009 wg_purge_pending_packets(struct wg_peer *wgp)
4010 {
4011 struct mbuf *m;
4012
4013 m = atomic_swap_ptr(&wgp->wgp_pending, NULL);
4014 membar_acquire(); /* matches membar_release in wgintr */
4015 m_freem(m);
4016 #ifdef ALTQ
4017 wg_start(&wgp->wgp_sc->wg_if);
4018 #endif
4019 pktq_barrier(wg_pktq);
4020 }
4021
4022 static void
4023 wg_handshake_timeout_timer(void *arg)
4024 {
4025 struct wg_peer *wgp = arg;
4026
4027 WG_TRACE("enter");
4028
4029 wg_schedule_peer_task(wgp, WGP_TASK_RETRY_HANDSHAKE);
4030 }
4031
4032 static struct wg_peer *
4033 wg_alloc_peer(struct wg_softc *wg)
4034 {
4035 struct wg_peer *wgp;
4036
4037 wgp = kmem_zalloc(sizeof(*wgp), KM_SLEEP);
4038
4039 wgp->wgp_sc = wg;
4040 callout_init(&wgp->wgp_handshake_timeout_timer, CALLOUT_MPSAFE);
4041 callout_setfunc(&wgp->wgp_handshake_timeout_timer,
4042 wg_handshake_timeout_timer, wgp);
4043 callout_init(&wgp->wgp_session_dtor_timer, CALLOUT_MPSAFE);
4044 callout_setfunc(&wgp->wgp_session_dtor_timer,
4045 wg_session_dtor_timer, wgp);
4046 PSLIST_ENTRY_INIT(wgp, wgp_peerlist_entry);
4047 wgp->wgp_endpoint_changing = false;
4048 wgp->wgp_endpoint_available = false;
4049 wgp->wgp_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
4050 wgp->wgp_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
4051 wgp->wgp_psz = pserialize_create();
4052 psref_target_init(&wgp->wgp_psref, wg_psref_class);
4053
4054 wgp->wgp_endpoint = kmem_zalloc(sizeof(*wgp->wgp_endpoint), KM_SLEEP);
4055 wgp->wgp_endpoint0 = kmem_zalloc(sizeof(*wgp->wgp_endpoint0), KM_SLEEP);
4056 psref_target_init(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
4057 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
4058
4059 struct wg_session *wgs;
4060 wgp->wgp_session_stable =
4061 kmem_zalloc(sizeof(*wgp->wgp_session_stable), KM_SLEEP);
4062 wgp->wgp_session_unstable =
4063 kmem_zalloc(sizeof(*wgp->wgp_session_unstable), KM_SLEEP);
4064 wgs = wgp->wgp_session_stable;
4065 wgs->wgs_peer = wgp;
4066 wgs->wgs_state = WGS_STATE_UNKNOWN;
4067 psref_target_init(&wgs->wgs_psref, wg_psref_class);
4068 #ifndef __HAVE_ATOMIC64_LOADSTORE
4069 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
4070 #endif
4071 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
4072 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
4073
4074 wgs = wgp->wgp_session_unstable;
4075 wgs->wgs_peer = wgp;
4076 wgs->wgs_state = WGS_STATE_UNKNOWN;
4077 psref_target_init(&wgs->wgs_psref, wg_psref_class);
4078 #ifndef __HAVE_ATOMIC64_LOADSTORE
4079 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
4080 #endif
4081 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
4082 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
4083
4084 return wgp;
4085 }
4086
4087 static void
4088 wg_destroy_peer(struct wg_peer *wgp)
4089 {
4090 struct wg_session *wgs;
4091 struct wg_softc *wg = wgp->wgp_sc;
4092
4093 /* Prevent new packets from this peer on any source address. */
4094 rw_enter(wg->wg_rwlock, RW_WRITER);
4095 KASSERT(wgp->wgp_n_allowedips <= WG_ALLOWEDIPS);
4096 for (int i = 0; i < wgp->wgp_n_allowedips; i++) {
4097 struct wg_allowedip *wga = &wgp->wgp_allowedips[i];
4098 struct radix_node_head *rnh = wg_rnh(wg, wga->wga_family);
4099 struct radix_node *rn;
4100
4101 KASSERT(rnh != NULL);
4102 rn = rnh->rnh_deladdr(&wga->wga_sa_addr,
4103 &wga->wga_sa_mask, rnh);
4104 if (rn == NULL) {
4105 char addrstr[128];
4106 sockaddr_format(&wga->wga_sa_addr, addrstr,
4107 sizeof(addrstr));
4108 WGLOG(LOG_WARNING, "%s: Couldn't delete %s",
4109 if_name(&wg->wg_if), addrstr);
4110 }
4111 }
4112 rw_exit(wg->wg_rwlock);
4113
4114 /* Purge pending packets. */
4115 wg_purge_pending_packets(wgp);
4116
4117 /* Halt all packet processing and timeouts. */
4118 callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
4119 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
4120
4121 /* Wait for any queued work to complete. */
4122 workqueue_wait(wg_wq, &wgp->wgp_work);
4123
4124 wgs = wgp->wgp_session_unstable;
4125 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
4126 mutex_enter(wgp->wgp_lock);
4127 wg_destroy_session(wg, wgs);
4128 mutex_exit(wgp->wgp_lock);
4129 }
4130 mutex_destroy(&wgs->wgs_recvwin->lock);
4131 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
4132 #ifndef __HAVE_ATOMIC64_LOADSTORE
4133 mutex_destroy(&wgs->wgs_send_counter_lock);
4134 #endif
4135 kmem_free(wgs, sizeof(*wgs));
4136
4137 wgs = wgp->wgp_session_stable;
4138 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
4139 mutex_enter(wgp->wgp_lock);
4140 wg_destroy_session(wg, wgs);
4141 mutex_exit(wgp->wgp_lock);
4142 }
4143 mutex_destroy(&wgs->wgs_recvwin->lock);
4144 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
4145 #ifndef __HAVE_ATOMIC64_LOADSTORE
4146 mutex_destroy(&wgs->wgs_send_counter_lock);
4147 #endif
4148 kmem_free(wgs, sizeof(*wgs));
4149
4150 psref_target_destroy(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
4151 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
4152 kmem_free(wgp->wgp_endpoint, sizeof(*wgp->wgp_endpoint));
4153 kmem_free(wgp->wgp_endpoint0, sizeof(*wgp->wgp_endpoint0));
4154
4155 pserialize_destroy(wgp->wgp_psz);
4156 mutex_obj_free(wgp->wgp_intr_lock);
4157 mutex_obj_free(wgp->wgp_lock);
4158
4159 kmem_free(wgp, sizeof(*wgp));
4160 }
4161
4162 static void
4163 wg_destroy_all_peers(struct wg_softc *wg)
4164 {
4165 struct wg_peer *wgp, *wgp0 __diagused;
4166 void *garbage_byname, *garbage_bypubkey;
4167
4168 restart:
4169 garbage_byname = garbage_bypubkey = NULL;
4170 mutex_enter(wg->wg_lock);
4171 WG_PEER_WRITER_FOREACH(wgp, wg) {
4172 if (wgp->wgp_name[0]) {
4173 wgp0 = thmap_del(wg->wg_peers_byname, wgp->wgp_name,
4174 strlen(wgp->wgp_name));
4175 KASSERT(wgp0 == wgp);
4176 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
4177 }
4178 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4179 sizeof(wgp->wgp_pubkey));
4180 KASSERT(wgp0 == wgp);
4181 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
4182 WG_PEER_WRITER_REMOVE(wgp);
4183 wg->wg_npeers--;
4184 mutex_enter(wgp->wgp_lock);
4185 pserialize_perform(wgp->wgp_psz);
4186 mutex_exit(wgp->wgp_lock);
4187 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
4188 break;
4189 }
4190 mutex_exit(wg->wg_lock);
4191
4192 if (wgp == NULL)
4193 return;
4194
4195 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
4196
4197 wg_destroy_peer(wgp);
4198 thmap_gc(wg->wg_peers_byname, garbage_byname);
4199 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
4200
4201 goto restart;
4202 }
4203
4204 static int
4205 wg_destroy_peer_name(struct wg_softc *wg, const char *name)
4206 {
4207 struct wg_peer *wgp, *wgp0 __diagused;
4208 void *garbage_byname, *garbage_bypubkey;
4209
4210 mutex_enter(wg->wg_lock);
4211 wgp = thmap_del(wg->wg_peers_byname, name, strlen(name));
4212 if (wgp != NULL) {
4213 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4214 sizeof(wgp->wgp_pubkey));
4215 KASSERT(wgp0 == wgp);
4216 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
4217 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
4218 WG_PEER_WRITER_REMOVE(wgp);
4219 wg->wg_npeers--;
4220 if (wg->wg_npeers == 0)
4221 if_link_state_change(&wg->wg_if, LINK_STATE_DOWN);
4222 mutex_enter(wgp->wgp_lock);
4223 pserialize_perform(wgp->wgp_psz);
4224 mutex_exit(wgp->wgp_lock);
4225 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
4226 }
4227 mutex_exit(wg->wg_lock);
4228
4229 if (wgp == NULL)
4230 return ENOENT;
4231
4232 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
4233
4234 wg_destroy_peer(wgp);
4235 thmap_gc(wg->wg_peers_byname, garbage_byname);
4236 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
4237
4238 return 0;
4239 }
4240
4241 static int
4242 wg_if_attach(struct wg_softc *wg)
4243 {
4244
4245 wg->wg_if.if_addrlen = 0;
4246 wg->wg_if.if_mtu = WG_MTU;
4247 wg->wg_if.if_flags = IFF_MULTICAST;
4248 wg->wg_if.if_extflags = IFEF_MPSAFE;
4249 wg->wg_if.if_ioctl = wg_ioctl;
4250 wg->wg_if.if_output = wg_output;
4251 wg->wg_if.if_init = wg_init;
4252 #ifdef ALTQ
4253 wg->wg_if.if_start = wg_start;
4254 #endif
4255 wg->wg_if.if_stop = wg_stop;
4256 wg->wg_if.if_type = IFT_OTHER;
4257 wg->wg_if.if_dlt = DLT_NULL;
4258 wg->wg_if.if_softc = wg;
4259 #ifdef ALTQ
4260 IFQ_SET_READY(&wg->wg_if.if_snd);
4261 #endif
4262 if_initialize(&wg->wg_if);
4263
4264 wg->wg_if.if_link_state = LINK_STATE_DOWN;
4265 if_alloc_sadl(&wg->wg_if);
4266 if_register(&wg->wg_if);
4267
4268 bpf_attach(&wg->wg_if, DLT_NULL, sizeof(uint32_t));
4269
4270 return 0;
4271 }
4272
4273 static void
4274 wg_if_detach(struct wg_softc *wg)
4275 {
4276 struct ifnet *ifp = &wg->wg_if;
4277
4278 bpf_detach(ifp);
4279 if_detach(ifp);
4280 }
4281
4282 static int
4283 wg_clone_create(struct if_clone *ifc, int unit)
4284 {
4285 struct wg_softc *wg;
4286 int error;
4287
4288 wg_guarantee_initialized();
4289
4290 error = wg_count_inc();
4291 if (error)
4292 return error;
4293
4294 wg = kmem_zalloc(sizeof(*wg), KM_SLEEP);
4295
4296 if_initname(&wg->wg_if, ifc->ifc_name, unit);
4297
4298 PSLIST_INIT(&wg->wg_peers);
4299 wg->wg_peers_bypubkey = thmap_create(0, NULL, THMAP_NOCOPY);
4300 wg->wg_peers_byname = thmap_create(0, NULL, THMAP_NOCOPY);
4301 wg->wg_sessions_byindex = thmap_create(0, NULL, THMAP_NOCOPY);
4302 wg->wg_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
4303 wg->wg_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
4304 wg->wg_rwlock = rw_obj_alloc();
4305 threadpool_job_init(&wg->wg_job, wg_job, wg->wg_intr_lock,
4306 "%s", if_name(&wg->wg_if));
4307 wg->wg_ops = &wg_ops_rumpkernel;
4308
4309 cprng_strong(kern_cprng,
4310 wg->wg_cookiesecret, sizeof(wg->wg_cookiesecret),
4311 0);
4312
4313 error = threadpool_get(&wg->wg_threadpool, PRI_NONE);
4314 if (error)
4315 goto fail0;
4316
4317 #ifdef INET
4318 error = wg_socreate(wg, AF_INET, &wg->wg_so4);
4319 if (error)
4320 goto fail1;
4321 rn_inithead((void **)&wg->wg_rtable_ipv4,
4322 offsetof(struct sockaddr_in, sin_addr) * NBBY);
4323 #endif
4324 #ifdef INET6
4325 error = wg_socreate(wg, AF_INET6, &wg->wg_so6);
4326 if (error)
4327 goto fail2;
4328 rn_inithead((void **)&wg->wg_rtable_ipv6,
4329 offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
4330 #endif
4331
4332 error = wg_if_attach(wg);
4333 if (error)
4334 goto fail3;
4335
4336 return 0;
4337
4338 fail4: __unused
4339 wg_destroy_all_peers(wg);
4340 wg_if_detach(wg);
4341 fail3:
4342 #ifdef INET6
4343 solock(wg->wg_so6);
4344 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
4345 sounlock(wg->wg_so6);
4346 #endif
4347 #ifdef INET
4348 solock(wg->wg_so4);
4349 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
4350 sounlock(wg->wg_so4);
4351 #endif
4352 mutex_enter(wg->wg_intr_lock);
4353 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
4354 mutex_exit(wg->wg_intr_lock);
4355 #ifdef INET6
4356 if (wg->wg_rtable_ipv6 != NULL)
4357 free(wg->wg_rtable_ipv6, M_RTABLE);
4358 soclose(wg->wg_so6);
4359 fail2:
4360 #endif
4361 #ifdef INET
4362 if (wg->wg_rtable_ipv4 != NULL)
4363 free(wg->wg_rtable_ipv4, M_RTABLE);
4364 soclose(wg->wg_so4);
4365 fail1:
4366 #endif
4367 threadpool_put(wg->wg_threadpool, PRI_NONE);
4368 fail0: threadpool_job_destroy(&wg->wg_job);
4369 rw_obj_free(wg->wg_rwlock);
4370 mutex_obj_free(wg->wg_intr_lock);
4371 mutex_obj_free(wg->wg_lock);
4372 thmap_destroy(wg->wg_sessions_byindex);
4373 thmap_destroy(wg->wg_peers_byname);
4374 thmap_destroy(wg->wg_peers_bypubkey);
4375 PSLIST_DESTROY(&wg->wg_peers);
4376 kmem_free(wg, sizeof(*wg));
4377 wg_count_dec();
4378 return error;
4379 }
4380
4381 static int
4382 wg_clone_destroy(struct ifnet *ifp)
4383 {
4384 struct wg_softc *wg = container_of(ifp, struct wg_softc, wg_if);
4385
4386 #ifdef WG_RUMPKERNEL
4387 if (wg_user_mode(wg)) {
4388 rumpuser_wg_destroy(wg->wg_user);
4389 wg->wg_user = NULL;
4390 }
4391 #endif
4392
4393 wg_destroy_all_peers(wg);
4394 wg_if_detach(wg);
4395 #ifdef INET6
4396 solock(wg->wg_so6);
4397 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
4398 sounlock(wg->wg_so6);
4399 #endif
4400 #ifdef INET
4401 solock(wg->wg_so4);
4402 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
4403 sounlock(wg->wg_so4);
4404 #endif
4405 mutex_enter(wg->wg_intr_lock);
4406 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
4407 mutex_exit(wg->wg_intr_lock);
4408 #ifdef INET6
4409 if (wg->wg_rtable_ipv6 != NULL)
4410 free(wg->wg_rtable_ipv6, M_RTABLE);
4411 soclose(wg->wg_so6);
4412 #endif
4413 #ifdef INET
4414 if (wg->wg_rtable_ipv4 != NULL)
4415 free(wg->wg_rtable_ipv4, M_RTABLE);
4416 soclose(wg->wg_so4);
4417 #endif
4418 threadpool_put(wg->wg_threadpool, PRI_NONE);
4419 threadpool_job_destroy(&wg->wg_job);
4420 rw_obj_free(wg->wg_rwlock);
4421 mutex_obj_free(wg->wg_intr_lock);
4422 mutex_obj_free(wg->wg_lock);
4423 thmap_destroy(wg->wg_sessions_byindex);
4424 thmap_destroy(wg->wg_peers_byname);
4425 thmap_destroy(wg->wg_peers_bypubkey);
4426 PSLIST_DESTROY(&wg->wg_peers);
4427 kmem_free(wg, sizeof(*wg));
4428 wg_count_dec();
4429
4430 return 0;
4431 }
4432
4433 static struct wg_peer *
4434 wg_pick_peer_by_sa(struct wg_softc *wg, const struct sockaddr *sa,
4435 struct psref *psref)
4436 {
4437 struct radix_node_head *rnh;
4438 struct radix_node *rn;
4439 struct wg_peer *wgp = NULL;
4440 struct wg_allowedip *wga;
4441
4442 #ifdef WG_DEBUG_LOG
4443 char addrstr[128];
4444 sockaddr_format(sa, addrstr, sizeof(addrstr));
4445 WG_DLOG("sa=%s\n", addrstr);
4446 #endif
4447
4448 rw_enter(wg->wg_rwlock, RW_READER);
4449
4450 rnh = wg_rnh(wg, sa->sa_family);
4451 if (rnh == NULL)
4452 goto out;
4453
4454 rn = rnh->rnh_matchaddr(sa, rnh);
4455 if (rn == NULL || (rn->rn_flags & RNF_ROOT) != 0)
4456 goto out;
4457
4458 WG_TRACE("success");
4459
4460 wga = container_of(rn, struct wg_allowedip, wga_nodes[0]);
4461 wgp = wga->wga_peer;
4462 wg_get_peer(wgp, psref);
4463
4464 out:
4465 rw_exit(wg->wg_rwlock);
4466 return wgp;
4467 }
4468
4469 static void
4470 wg_fill_msg_data(struct wg_softc *wg, struct wg_peer *wgp,
4471 struct wg_session *wgs, struct wg_msg_data *wgmd)
4472 {
4473
4474 memset(wgmd, 0, sizeof(*wgmd));
4475 wgmd->wgmd_type = htole32(WG_MSG_TYPE_DATA);
4476 wgmd->wgmd_receiver = wgs->wgs_remote_index;
4477 /* [W] 5.4.6: msg.counter := Nm^send */
4478 /* [W] 5.4.6: Nm^send := Nm^send + 1 */
4479 wgmd->wgmd_counter = htole64(wg_session_inc_send_counter(wgs));
4480 WG_DLOG("counter=%"PRIu64"\n", le64toh(wgmd->wgmd_counter));
4481 }
4482
4483 static int
4484 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
4485 const struct rtentry *rt)
4486 {
4487 struct wg_softc *wg = ifp->if_softc;
4488 struct wg_peer *wgp = NULL;
4489 struct psref wgp_psref;
4490 int bound;
4491 int error;
4492
4493 bound = curlwp_bind();
4494
4495 /* TODO make the nest limit configurable via sysctl */
4496 error = if_tunnel_check_nesting(ifp, m, 1);
4497 if (error) {
4498 WGLOG(LOG_ERR,
4499 "%s: tunneling loop detected and packet dropped\n",
4500 if_name(&wg->wg_if));
4501 goto out0;
4502 }
4503
4504 #ifdef ALTQ
4505 bool altq = atomic_load_relaxed(&ifp->if_snd.altq_flags)
4506 & ALTQF_ENABLED;
4507 if (altq)
4508 IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
4509 #endif
4510
4511 bpf_mtap_af(ifp, dst->sa_family, m, BPF_D_OUT);
4512
4513 m->m_flags &= ~(M_BCAST|M_MCAST);
4514
4515 wgp = wg_pick_peer_by_sa(wg, dst, &wgp_psref);
4516 if (wgp == NULL) {
4517 WG_TRACE("peer not found");
4518 error = EHOSTUNREACH;
4519 goto out0;
4520 }
4521
4522 /* Clear checksum-offload flags. */
4523 m->m_pkthdr.csum_flags = 0;
4524 m->m_pkthdr.csum_data = 0;
4525
4526 /* Toss it in the queue. */
4527 #ifdef ALTQ
4528 if (altq) {
4529 mutex_enter(ifp->if_snd.ifq_lock);
4530 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
4531 M_SETCTX(m, wgp);
4532 ALTQ_ENQUEUE(&ifp->if_snd, m, error);
4533 m = NULL; /* consume */
4534 }
4535 mutex_exit(ifp->if_snd.ifq_lock);
4536 if (m == NULL) {
4537 wg_start(ifp);
4538 goto out1;
4539 }
4540 }
4541 #endif
4542 kpreempt_disable();
4543 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
4544 M_SETCTX(m, wgp);
4545 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
4546 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
4547 if_name(&wg->wg_if));
4548 error = ENOBUFS;
4549 goto out2;
4550 }
4551 m = NULL; /* consumed */
4552 error = 0;
4553 out2: kpreempt_enable();
4554
4555 #ifdef ALTQ
4556 out1:
4557 #endif
4558 wg_put_peer(wgp, &wgp_psref);
4559 out0: m_freem(m);
4560 curlwp_bindx(bound);
4561 return error;
4562 }
4563
4564 static int
4565 wg_send_data(struct wg_peer *wgp, struct mbuf *m)
4566 {
4567 struct psref psref;
4568 struct wg_sockaddr *wgsa;
4569 int error;
4570 struct socket *so;
4571
4572 wgsa = wg_get_endpoint_sa(wgp, &psref);
4573 so = wg_get_so_by_peer(wgp, wgsa);
4574 solock(so);
4575 switch (wgsatosa(wgsa)->sa_family) {
4576 #ifdef INET
4577 case AF_INET:
4578 error = udp_send(so, m, wgsatosa(wgsa), NULL, curlwp);
4579 break;
4580 #endif
4581 #ifdef INET6
4582 case AF_INET6:
4583 error = udp6_output(sotoinpcb(so), m, wgsatosin6(wgsa),
4584 NULL, curlwp);
4585 break;
4586 #endif
4587 default:
4588 m_freem(m);
4589 error = EPFNOSUPPORT;
4590 }
4591 sounlock(so);
4592 wg_put_sa(wgp, wgsa, &psref);
4593
4594 return error;
4595 }
4596
4597 /* Inspired by pppoe_get_mbuf */
4598 static struct mbuf *
4599 wg_get_mbuf(size_t leading_len, size_t len)
4600 {
4601 struct mbuf *m;
4602
4603 KASSERT(leading_len <= MCLBYTES);
4604 KASSERT(len <= MCLBYTES - leading_len);
4605
4606 m = m_gethdr(M_DONTWAIT, MT_DATA);
4607 if (m == NULL)
4608 return NULL;
4609 if (len + leading_len > MHLEN) {
4610 m_clget(m, M_DONTWAIT);
4611 if ((m->m_flags & M_EXT) == 0) {
4612 m_free(m);
4613 return NULL;
4614 }
4615 }
4616 m->m_data += leading_len;
4617 m->m_pkthdr.len = m->m_len = len;
4618
4619 return m;
4620 }
4621
4622 static void
4623 wg_send_data_msg(struct wg_peer *wgp, struct wg_session *wgs, struct mbuf *m)
4624 {
4625 struct wg_softc *wg = wgp->wgp_sc;
4626 int error;
4627 size_t inner_len, padded_len, encrypted_len;
4628 char *padded_buf = NULL;
4629 size_t mlen;
4630 struct wg_msg_data *wgmd;
4631 bool free_padded_buf = false;
4632 struct mbuf *n;
4633 size_t leading_len = max_hdr + sizeof(struct udphdr);
4634
4635 mlen = m_length(m);
4636 inner_len = mlen;
4637 padded_len = roundup(mlen, 16);
4638 encrypted_len = padded_len + WG_AUTHTAG_LEN;
4639 WG_DLOG("inner=%zu, padded=%zu, encrypted_len=%zu\n",
4640 inner_len, padded_len, encrypted_len);
4641 if (mlen != 0) {
4642 bool success;
4643 success = m_ensure_contig(&m, padded_len);
4644 if (success) {
4645 padded_buf = mtod(m, char *);
4646 } else {
4647 padded_buf = kmem_intr_alloc(padded_len, KM_NOSLEEP);
4648 if (padded_buf == NULL) {
4649 error = ENOBUFS;
4650 goto out;
4651 }
4652 free_padded_buf = true;
4653 m_copydata(m, 0, mlen, padded_buf);
4654 }
4655 memset(padded_buf + mlen, 0, padded_len - inner_len);
4656 }
4657
4658 n = wg_get_mbuf(leading_len, sizeof(*wgmd) + encrypted_len);
4659 if (n == NULL) {
4660 error = ENOBUFS;
4661 goto out;
4662 }
4663 KASSERT(n->m_len >= sizeof(*wgmd));
4664 wgmd = mtod(n, struct wg_msg_data *);
4665 wg_fill_msg_data(wg, wgp, wgs, wgmd);
4666
4667 /* [W] 5.4.6: AEAD(Tm^send, Nm^send, P, e) */
4668 wg_algo_aead_enc((char *)wgmd + sizeof(*wgmd), encrypted_len,
4669 wgs->wgs_tkey_send, le64toh(wgmd->wgmd_counter),
4670 padded_buf, padded_len,
4671 NULL, 0);
4672
4673 error = wg->wg_ops->send_data_msg(wgp, n); /* consumes n */
4674 if (error) {
4675 WG_DLOG("send_data_msg failed, error=%d\n", error);
4676 goto out;
4677 }
4678
4679 /*
4680 * Packet was sent out -- count it in the interface statistics.
4681 */
4682 if_statadd(&wg->wg_if, if_obytes, mlen);
4683 if_statinc(&wg->wg_if, if_opackets);
4684
4685 /*
4686 * Record when we last sent data, for determining when we need
4687 * to send a passive keepalive.
4688 *
4689 * Other logic assumes that wgs_time_last_data_sent is zero iff
4690 * we have never sent data on this session. Early at boot, if
4691 * wg(4) starts operating within <1sec, or after 136 years of
4692 * uptime, we may observe time_uptime32 = 0. In that case,
4693 * pretend we observed 1 instead. That way, we correctly
4694 * indicate we have sent data on this session; the only logic
4695 * this might adversely affect is the keepalive timeout
4696 * detection, which might spuriously send a keepalive during
4697 * one second every 136 years. All of this is very silly, of
4698 * course, but the cost to guaranteeing wgs_time_last_data_sent
4699 * is nonzero is negligible here.
4700 */
4701 const uint32_t now = time_uptime32;
4702 atomic_store_relaxed(&wgs->wgs_time_last_data_sent, MAX(now, 1));
4703
4704 /*
4705 * Check rekey-after-time.
4706 */
4707 if (wgs->wgs_is_initiator &&
4708 now - wgs->wgs_time_established >= wg_rekey_after_time) {
4709 /*
4710 * [W] 6.2 Transport Message Limits
4711 * "if a peer is the initiator of a current secure
4712 * session, WireGuard will send a handshake initiation
4713 * message to begin a new secure session if, after
4714 * transmitting a transport data message, the current
4715 * secure session is REKEY-AFTER-TIME seconds old,"
4716 */
4717 WG_TRACE("rekey after time");
4718 atomic_store_relaxed(&wgs->wgs_force_rekey, true);
4719 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4720 }
4721
4722 /*
4723 * Check rekey-after-messages.
4724 */
4725 if (wg_session_get_send_counter(wgs) >= wg_rekey_after_messages) {
4726 /*
4727 * [W] 6.2 Transport Message Limits
4728 * "WireGuard will try to create a new session, by
4729 * sending a handshake initiation message (section
4730 * 5.4.2), after it has sent REKEY-AFTER-MESSAGES
4731 * transport data messages..."
4732 */
4733 WG_TRACE("rekey after messages");
4734 atomic_store_relaxed(&wgs->wgs_force_rekey, true);
4735 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4736 }
4737
4738 out: m_freem(m);
4739 if (free_padded_buf)
4740 kmem_intr_free(padded_buf, padded_len);
4741 }
4742
4743 static void
4744 wg_input(struct ifnet *ifp, struct mbuf *m, const int af)
4745 {
4746 pktqueue_t *pktq;
4747 size_t pktlen;
4748
4749 KASSERT(af == AF_INET || af == AF_INET6);
4750
4751 WG_TRACE("");
4752
4753 m_set_rcvif(m, ifp);
4754 pktlen = m->m_pkthdr.len;
4755
4756 bpf_mtap_af(ifp, af, m, BPF_D_IN);
4757
4758 switch (af) {
4759 #ifdef INET
4760 case AF_INET:
4761 pktq = ip_pktq;
4762 break;
4763 #endif
4764 #ifdef INET6
4765 case AF_INET6:
4766 pktq = ip6_pktq;
4767 break;
4768 #endif
4769 default:
4770 panic("invalid af=%d", af);
4771 }
4772
4773 kpreempt_disable();
4774 const u_int h = curcpu()->ci_index;
4775 if (__predict_true(pktq_enqueue(pktq, m, h))) {
4776 if_statadd(ifp, if_ibytes, pktlen);
4777 if_statinc(ifp, if_ipackets);
4778 } else {
4779 m_freem(m);
4780 }
4781 kpreempt_enable();
4782 }
4783
4784 static void
4785 wg_calc_pubkey(uint8_t pubkey[static WG_STATIC_KEY_LEN],
4786 const uint8_t privkey[static WG_STATIC_KEY_LEN])
4787 {
4788
4789 crypto_scalarmult_base(pubkey, privkey);
4790 }
4791
4792 static int
4793 wg_rtable_add_route(struct wg_softc *wg, struct wg_allowedip *wga)
4794 {
4795 struct radix_node_head *rnh;
4796 struct radix_node *rn;
4797 int error = 0;
4798
4799 rw_enter(wg->wg_rwlock, RW_WRITER);
4800 rnh = wg_rnh(wg, wga->wga_family);
4801 KASSERT(rnh != NULL);
4802 rn = rnh->rnh_addaddr(&wga->wga_sa_addr, &wga->wga_sa_mask, rnh,
4803 wga->wga_nodes);
4804 rw_exit(wg->wg_rwlock);
4805
4806 if (rn == NULL)
4807 error = EEXIST;
4808
4809 return error;
4810 }
4811
4812 static int
4813 wg_handle_prop_peer(struct wg_softc *wg, prop_dictionary_t peer,
4814 struct wg_peer **wgpp)
4815 {
4816 int error = 0;
4817 const void *pubkey;
4818 size_t pubkey_len;
4819 const void *psk;
4820 size_t psk_len;
4821 const char *name = NULL;
4822 struct wg_peer *wgp = NULL;
4823
4824 if (prop_dictionary_get_string(peer, "name", &name)) {
4825 if (strlen(name) > WG_PEER_NAME_MAXLEN) {
4826 error = EINVAL;
4827 goto out;
4828 }
4829 }
4830
4831 if (!prop_dictionary_get_data(peer, "public_key",
4832 &pubkey, &pubkey_len)) {
4833 error = EINVAL;
4834 goto out;
4835 }
4836 #ifdef WG_DEBUG_DUMP
4837 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4838 char *hex = gethexdump(pubkey, pubkey_len);
4839 log(LOG_DEBUG, "pubkey=%p, pubkey_len=%zu\n%s\n",
4840 pubkey, pubkey_len, hex);
4841 puthexdump(hex, pubkey, pubkey_len);
4842 }
4843 #endif
4844
4845 wgp = wg_alloc_peer(wg);
4846 memcpy(wgp->wgp_pubkey, pubkey, sizeof(wgp->wgp_pubkey));
4847 if (name != NULL)
4848 strncpy(wgp->wgp_name, name, sizeof(wgp->wgp_name));
4849
4850 if (prop_dictionary_get_data(peer, "preshared_key", &psk, &psk_len)) {
4851 if (psk_len != sizeof(wgp->wgp_psk)) {
4852 error = EINVAL;
4853 goto out;
4854 }
4855 memcpy(wgp->wgp_psk, psk, sizeof(wgp->wgp_psk));
4856 }
4857
4858 const void *addr;
4859 size_t addr_len;
4860 struct wg_sockaddr *wgsa = wgp->wgp_endpoint;
4861
4862 if (!prop_dictionary_get_data(peer, "endpoint", &addr, &addr_len))
4863 goto skip_endpoint;
4864 if (addr_len < sizeof(*wgsatosa(wgsa)) ||
4865 addr_len > sizeof(*wgsatoss(wgsa))) {
4866 error = EINVAL;
4867 goto out;
4868 }
4869 memcpy(wgsatoss(wgsa), addr, addr_len);
4870 switch (wgsa_family(wgsa)) {
4871 #ifdef INET
4872 case AF_INET:
4873 break;
4874 #endif
4875 #ifdef INET6
4876 case AF_INET6:
4877 break;
4878 #endif
4879 default:
4880 error = EPFNOSUPPORT;
4881 goto out;
4882 }
4883 if (addr_len != sockaddr_getsize_by_family(wgsa_family(wgsa))) {
4884 error = EINVAL;
4885 goto out;
4886 }
4887 {
4888 char addrstr[128];
4889 sockaddr_format(wgsatosa(wgsa), addrstr, sizeof(addrstr));
4890 WG_DLOG("addr=%s\n", addrstr);
4891 }
4892 wgp->wgp_endpoint_available = true;
4893
4894 prop_array_t allowedips;
4895 skip_endpoint:
4896 allowedips = prop_dictionary_get(peer, "allowedips");
4897 if (allowedips == NULL)
4898 goto skip;
4899
4900 prop_object_iterator_t _it = prop_array_iterator(allowedips);
4901 prop_dictionary_t prop_allowedip;
4902 while ((prop_allowedip = prop_object_iterator_next(_it)) != NULL) {
4903 if (wgp->wgp_n_allowedips >= WG_ALLOWEDIPS) {
4904 error = E2BIG;
4905 goto out;
4906 }
4907
4908 struct wg_allowedip *const wga =
4909 &wgp->wgp_allowedips[wgp->wgp_n_allowedips++];
4910
4911 if (!prop_dictionary_get_int(prop_allowedip, "family",
4912 &wga->wga_family))
4913 continue;
4914 if (!prop_dictionary_get_data(prop_allowedip, "ip",
4915 &addr, &addr_len))
4916 continue;
4917 if (!prop_dictionary_get_uint8(prop_allowedip, "cidr",
4918 &wga->wga_cidr))
4919 continue;
4920
4921 switch (wga->wga_family) {
4922 #ifdef INET
4923 case AF_INET: {
4924 struct sockaddr_in sin;
4925 char addrstr[128];
4926 struct in_addr mask;
4927 struct sockaddr_in sin_mask;
4928
4929 if (addr_len != sizeof(struct in_addr)) {
4930 error = EINVAL;
4931 goto out;
4932 }
4933 memcpy(&wga->wga_addr4, addr, addr_len);
4934
4935 sockaddr_in_init(&sin, (const struct in_addr *)addr,
4936 0);
4937 sockaddr_copy(&wga->wga_sa_addr,
4938 sizeof(sin), sintosa(&sin));
4939
4940 sockaddr_format(sintosa(&sin),
4941 addrstr, sizeof(addrstr));
4942 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4943
4944 in_len2mask(&mask, wga->wga_cidr);
4945 sockaddr_in_init(&sin_mask, &mask, 0);
4946 sockaddr_copy(&wga->wga_sa_mask,
4947 sizeof(sin_mask), sintosa(&sin_mask));
4948
4949 break;
4950 }
4951 #endif
4952 #ifdef INET6
4953 case AF_INET6: {
4954 struct sockaddr_in6 sin6;
4955 char addrstr[128];
4956 struct in6_addr mask;
4957 struct sockaddr_in6 sin6_mask;
4958
4959 if (addr_len != sizeof(struct in6_addr)) {
4960 error = EINVAL;
4961 goto out;
4962 }
4963 memcpy(&wga->wga_addr6, addr, addr_len);
4964
4965 sockaddr_in6_init(&sin6, (const struct in6_addr *)addr,
4966 0, 0, 0);
4967 sockaddr_copy(&wga->wga_sa_addr,
4968 sizeof(sin6), sin6tosa(&sin6));
4969
4970 sockaddr_format(sin6tosa(&sin6),
4971 addrstr, sizeof(addrstr));
4972 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4973
4974 in6_prefixlen2mask(&mask, wga->wga_cidr);
4975 sockaddr_in6_init(&sin6_mask, &mask, 0, 0, 0);
4976 sockaddr_copy(&wga->wga_sa_mask,
4977 sizeof(sin6_mask), sin6tosa(&sin6_mask));
4978
4979 break;
4980 }
4981 #endif
4982 default:
4983 error = EINVAL;
4984 goto out;
4985 }
4986 wga->wga_peer = wgp;
4987
4988 error = wg_rtable_add_route(wg, wga);
4989 if (error != 0)
4990 goto out;
4991 }
4992 KASSERT(wgp->wgp_n_allowedips <= WG_ALLOWEDIPS);
4993 skip:
4994 *wgpp = wgp;
4995 wgp = NULL;
4996 out:
4997 if (wgp)
4998 wg_destroy_peer(wgp);
4999 return error;
5000 }
5001
5002 static int
5003 wg_alloc_prop_buf(char **_buf, struct ifdrv *ifd)
5004 {
5005 int error;
5006 char *buf;
5007
5008 WG_DLOG("buf=%p, len=%zu\n", ifd->ifd_data, ifd->ifd_len);
5009 if (ifd->ifd_len >= WG_MAX_PROPLEN)
5010 return E2BIG;
5011 buf = kmem_alloc(ifd->ifd_len + 1, KM_SLEEP);
5012 error = copyin(ifd->ifd_data, buf, ifd->ifd_len);
5013 if (error != 0)
5014 return error;
5015 buf[ifd->ifd_len] = '\0';
5016 #ifdef WG_DEBUG_DUMP
5017 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
5018 log(LOG_DEBUG, "%.*s\n", (int)MIN(INT_MAX, ifd->ifd_len),
5019 (const char *)buf);
5020 }
5021 #endif
5022 *_buf = buf;
5023 return 0;
5024 }
5025
5026 static int
5027 wg_ioctl_set_private_key(struct wg_softc *wg, struct ifdrv *ifd)
5028 {
5029 int error;
5030 prop_dictionary_t prop_dict = NULL;
5031 char *buf = NULL;
5032 const void *privkey;
5033 size_t privkey_len;
5034
5035 error = wg_alloc_prop_buf(&buf, ifd);
5036 if (error != 0)
5037 return error;
5038 error = EINVAL;
5039 prop_dict = prop_dictionary_internalize(buf);
5040 if (prop_dict == NULL)
5041 goto out;
5042 if (!prop_dictionary_get_data(prop_dict, "private_key",
5043 &privkey, &privkey_len))
5044 goto out;
5045 #ifdef WG_DEBUG_DUMP
5046 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
5047 char *hex = gethexdump(privkey, privkey_len);
5048 log(LOG_DEBUG, "privkey=%p, privkey_len=%zu\n%s\n",
5049 privkey, privkey_len, hex);
5050 puthexdump(hex, privkey, privkey_len);
5051 }
5052 #endif
5053 if (privkey_len != WG_STATIC_KEY_LEN)
5054 goto out;
5055 memcpy(wg->wg_privkey, privkey, WG_STATIC_KEY_LEN);
5056 wg_calc_pubkey(wg->wg_pubkey, wg->wg_privkey);
5057 error = 0;
5058
5059 out:
5060 if (prop_dict)
5061 prop_object_release(prop_dict);
5062 kmem_free(buf, ifd->ifd_len + 1);
5063 return error;
5064 }
5065
5066 static int
5067 wg_ioctl_set_listen_port(struct wg_softc *wg, struct ifdrv *ifd)
5068 {
5069 int error;
5070 prop_dictionary_t prop_dict = NULL;
5071 char *buf = NULL;
5072 uint16_t port;
5073
5074 error = wg_alloc_prop_buf(&buf, ifd);
5075 if (error != 0)
5076 return error;
5077 error = EINVAL;
5078 prop_dict = prop_dictionary_internalize(buf);
5079 if (prop_dict == NULL)
5080 goto out;
5081 if (!prop_dictionary_get_uint16(prop_dict, "listen_port", &port))
5082 goto out;
5083
5084 error = wg->wg_ops->bind_port(wg, (uint16_t)port);
5085
5086 out:
5087 if (prop_dict)
5088 prop_object_release(prop_dict);
5089 kmem_free(buf, ifd->ifd_len + 1);
5090 return error;
5091 }
5092
5093 static int
5094 wg_ioctl_add_peer(struct wg_softc *wg, struct ifdrv *ifd)
5095 {
5096 int error;
5097 prop_dictionary_t prop_dict = NULL;
5098 char *buf = NULL;
5099 struct wg_peer *wgp = NULL, *wgp0 __diagused;
5100
5101 error = wg_alloc_prop_buf(&buf, ifd);
5102 if (error != 0)
5103 return error;
5104 error = EINVAL;
5105 prop_dict = prop_dictionary_internalize(buf);
5106 if (prop_dict == NULL)
5107 goto out;
5108
5109 error = wg_handle_prop_peer(wg, prop_dict, &wgp);
5110 if (error != 0)
5111 goto out;
5112
5113 mutex_enter(wg->wg_lock);
5114 if (thmap_get(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
5115 sizeof(wgp->wgp_pubkey)) != NULL ||
5116 (wgp->wgp_name[0] &&
5117 thmap_get(wg->wg_peers_byname, wgp->wgp_name,
5118 strlen(wgp->wgp_name)) != NULL)) {
5119 mutex_exit(wg->wg_lock);
5120 wg_destroy_peer(wgp);
5121 error = EEXIST;
5122 goto out;
5123 }
5124 wgp0 = thmap_put(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
5125 sizeof(wgp->wgp_pubkey), wgp);
5126 KASSERT(wgp0 == wgp);
5127 if (wgp->wgp_name[0]) {
5128 wgp0 = thmap_put(wg->wg_peers_byname, wgp->wgp_name,
5129 strlen(wgp->wgp_name), wgp);
5130 KASSERT(wgp0 == wgp);
5131 }
5132 WG_PEER_WRITER_INSERT_HEAD(wgp, wg);
5133 wg->wg_npeers++;
5134 mutex_exit(wg->wg_lock);
5135
5136 if_link_state_change(&wg->wg_if, LINK_STATE_UP);
5137
5138 out:
5139 if (prop_dict)
5140 prop_object_release(prop_dict);
5141 kmem_free(buf, ifd->ifd_len + 1);
5142 return error;
5143 }
5144
5145 static int
5146 wg_ioctl_delete_peer(struct wg_softc *wg, struct ifdrv *ifd)
5147 {
5148 int error;
5149 prop_dictionary_t prop_dict = NULL;
5150 char *buf = NULL;
5151 const char *name;
5152
5153 error = wg_alloc_prop_buf(&buf, ifd);
5154 if (error != 0)
5155 return error;
5156 error = EINVAL;
5157 prop_dict = prop_dictionary_internalize(buf);
5158 if (prop_dict == NULL)
5159 goto out;
5160
5161 if (!prop_dictionary_get_string(prop_dict, "name", &name))
5162 goto out;
5163 if (strlen(name) > WG_PEER_NAME_MAXLEN)
5164 goto out;
5165
5166 error = wg_destroy_peer_name(wg, name);
5167 out:
5168 if (prop_dict)
5169 prop_object_release(prop_dict);
5170 kmem_free(buf, ifd->ifd_len + 1);
5171 return error;
5172 }
5173
5174 static bool
5175 wg_is_authorized(struct wg_softc *wg, u_long cmd)
5176 {
5177 int au = cmd == SIOCGDRVSPEC ?
5178 KAUTH_REQ_NETWORK_INTERFACE_WG_GETPRIV :
5179 KAUTH_REQ_NETWORK_INTERFACE_WG_SETPRIV;
5180 return kauth_authorize_network(kauth_cred_get(),
5181 KAUTH_NETWORK_INTERFACE_WG, au, &wg->wg_if,
5182 (void *)cmd, NULL) == 0;
5183 }
5184
5185 static int
5186 wg_ioctl_get(struct wg_softc *wg, struct ifdrv *ifd)
5187 {
5188 int error = ENOMEM;
5189 prop_dictionary_t prop_dict;
5190 prop_array_t peers = NULL;
5191 char *buf;
5192 struct wg_peer *wgp;
5193 int s, i;
5194
5195 prop_dict = prop_dictionary_create();
5196 if (prop_dict == NULL)
5197 goto error;
5198
5199 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
5200 if (!prop_dictionary_set_data(prop_dict, "private_key",
5201 wg->wg_privkey, WG_STATIC_KEY_LEN))
5202 goto error;
5203 }
5204
5205 if (wg->wg_listen_port != 0) {
5206 if (!prop_dictionary_set_uint16(prop_dict, "listen_port",
5207 wg->wg_listen_port))
5208 goto error;
5209 }
5210
5211 if (wg->wg_npeers == 0)
5212 goto skip_peers;
5213
5214 peers = prop_array_create();
5215 if (peers == NULL)
5216 goto error;
5217
5218 s = pserialize_read_enter();
5219 i = 0;
5220 WG_PEER_READER_FOREACH(wgp, wg) {
5221 struct wg_sockaddr *wgsa;
5222 struct psref wgp_psref, wgsa_psref;
5223 prop_dictionary_t prop_peer;
5224
5225 wg_get_peer(wgp, &wgp_psref);
5226 pserialize_read_exit(s);
5227
5228 prop_peer = prop_dictionary_create();
5229 if (prop_peer == NULL)
5230 goto next;
5231
5232 if (strlen(wgp->wgp_name) > 0) {
5233 if (!prop_dictionary_set_string(prop_peer, "name",
5234 wgp->wgp_name))
5235 goto next;
5236 }
5237
5238 if (!prop_dictionary_set_data(prop_peer, "public_key",
5239 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey)))
5240 goto next;
5241
5242 uint8_t psk_zero[WG_PRESHARED_KEY_LEN] = {0};
5243 if (!consttime_memequal(wgp->wgp_psk, psk_zero,
5244 sizeof(wgp->wgp_psk))) {
5245 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
5246 if (!prop_dictionary_set_data(prop_peer,
5247 "preshared_key",
5248 wgp->wgp_psk, sizeof(wgp->wgp_psk)))
5249 goto next;
5250 }
5251 }
5252
5253 wgsa = wg_get_endpoint_sa(wgp, &wgsa_psref);
5254 CTASSERT(AF_UNSPEC == 0);
5255 if (wgsa_family(wgsa) != 0 /*AF_UNSPEC*/ &&
5256 !prop_dictionary_set_data(prop_peer, "endpoint",
5257 wgsatoss(wgsa),
5258 sockaddr_getsize_by_family(wgsa_family(wgsa)))) {
5259 wg_put_sa(wgp, wgsa, &wgsa_psref);
5260 goto next;
5261 }
5262 wg_put_sa(wgp, wgsa, &wgsa_psref);
5263
5264 const struct timespec *t = &wgp->wgp_last_handshake_time;
5265
5266 if (!prop_dictionary_set_uint64(prop_peer,
5267 "last_handshake_time_sec", (uint64_t)t->tv_sec))
5268 goto next;
5269 if (!prop_dictionary_set_uint32(prop_peer,
5270 "last_handshake_time_nsec", (uint32_t)t->tv_nsec))
5271 goto next;
5272
5273 if (wgp->wgp_n_allowedips == 0)
5274 goto skip_allowedips;
5275
5276 prop_array_t allowedips = prop_array_create();
5277 if (allowedips == NULL)
5278 goto next;
5279 KASSERT(wgp->wgp_n_allowedips <= WG_ALLOWEDIPS);
5280 for (int j = 0; j < wgp->wgp_n_allowedips; j++) {
5281 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
5282 prop_dictionary_t prop_allowedip;
5283
5284 prop_allowedip = prop_dictionary_create();
5285 if (prop_allowedip == NULL)
5286 break;
5287
5288 if (!prop_dictionary_set_int(prop_allowedip, "family",
5289 wga->wga_family))
5290 goto _next;
5291 if (!prop_dictionary_set_uint8(prop_allowedip, "cidr",
5292 wga->wga_cidr))
5293 goto _next;
5294
5295 switch (wga->wga_family) {
5296 #ifdef INET
5297 case AF_INET:
5298 if (!prop_dictionary_set_data(prop_allowedip,
5299 "ip", &wga->wga_addr4,
5300 sizeof(wga->wga_addr4)))
5301 goto _next;
5302 break;
5303 #endif
5304 #ifdef INET6
5305 case AF_INET6:
5306 if (!prop_dictionary_set_data(prop_allowedip,
5307 "ip", &wga->wga_addr6,
5308 sizeof(wga->wga_addr6)))
5309 goto _next;
5310 break;
5311 #endif
5312 default:
5313 panic("invalid af=%d", wga->wga_family);
5314 }
5315 prop_array_set(allowedips, j, prop_allowedip);
5316 _next:
5317 prop_object_release(prop_allowedip);
5318 }
5319 prop_dictionary_set(prop_peer, "allowedips", allowedips);
5320 prop_object_release(allowedips);
5321
5322 skip_allowedips:
5323
5324 prop_array_set(peers, i, prop_peer);
5325 next:
5326 if (prop_peer)
5327 prop_object_release(prop_peer);
5328 i++;
5329
5330 s = pserialize_read_enter();
5331 wg_put_peer(wgp, &wgp_psref);
5332 }
5333 pserialize_read_exit(s);
5334
5335 prop_dictionary_set(prop_dict, "peers", peers);
5336 prop_object_release(peers);
5337 peers = NULL;
5338
5339 skip_peers:
5340 buf = prop_dictionary_externalize(prop_dict);
5341 if (buf == NULL)
5342 goto error;
5343 if (ifd->ifd_len < (strlen(buf) + 1)) {
5344 error = EINVAL;
5345 goto error;
5346 }
5347 error = copyout(buf, ifd->ifd_data, strlen(buf) + 1);
5348
5349 free(buf, 0);
5350 error:
5351 if (peers != NULL)
5352 prop_object_release(peers);
5353 if (prop_dict != NULL)
5354 prop_object_release(prop_dict);
5355
5356 return error;
5357 }
5358
5359 static int
5360 wg_ioctl(struct ifnet *ifp, u_long cmd, void *data)
5361 {
5362 struct wg_softc *wg = ifp->if_softc;
5363 struct ifreq *ifr = data;
5364 struct ifaddr *ifa = data;
5365 struct ifdrv *ifd = data;
5366 int error = 0;
5367
5368 switch (cmd) {
5369 case SIOCINITIFADDR:
5370 if (ifa->ifa_addr->sa_family != AF_LINK &&
5371 (ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
5372 (IFF_UP | IFF_RUNNING)) {
5373 ifp->if_flags |= IFF_UP;
5374 error = if_init(ifp);
5375 }
5376 return error;
5377 case SIOCADDMULTI:
5378 case SIOCDELMULTI:
5379 switch (ifr->ifr_addr.sa_family) {
5380 #ifdef INET
5381 case AF_INET: /* IP supports Multicast */
5382 break;
5383 #endif
5384 #ifdef INET6
5385 case AF_INET6: /* IP6 supports Multicast */
5386 break;
5387 #endif
5388 default: /* Other protocols doesn't support Multicast */
5389 error = EAFNOSUPPORT;
5390 break;
5391 }
5392 return error;
5393 case SIOCSDRVSPEC:
5394 if (!wg_is_authorized(wg, cmd)) {
5395 return EPERM;
5396 }
5397 switch (ifd->ifd_cmd) {
5398 case WG_IOCTL_SET_PRIVATE_KEY:
5399 error = wg_ioctl_set_private_key(wg, ifd);
5400 break;
5401 case WG_IOCTL_SET_LISTEN_PORT:
5402 error = wg_ioctl_set_listen_port(wg, ifd);
5403 break;
5404 case WG_IOCTL_ADD_PEER:
5405 error = wg_ioctl_add_peer(wg, ifd);
5406 break;
5407 case WG_IOCTL_DELETE_PEER:
5408 error = wg_ioctl_delete_peer(wg, ifd);
5409 break;
5410 default:
5411 error = EINVAL;
5412 break;
5413 }
5414 return error;
5415 case SIOCGDRVSPEC:
5416 return wg_ioctl_get(wg, ifd);
5417 case SIOCSIFFLAGS:
5418 if ((error = ifioctl_common(ifp, cmd, data)) != 0)
5419 break;
5420 switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
5421 case IFF_RUNNING:
5422 /*
5423 * If interface is marked down and it is running,
5424 * then stop and disable it.
5425 */
5426 if_stop(ifp, 1);
5427 break;
5428 case IFF_UP:
5429 /*
5430 * If interface is marked up and it is stopped, then
5431 * start it.
5432 */
5433 error = if_init(ifp);
5434 break;
5435 default:
5436 break;
5437 }
5438 return error;
5439 #ifdef WG_RUMPKERNEL
5440 case SIOCSLINKSTR:
5441 error = wg_ioctl_linkstr(wg, ifd);
5442 if (error)
5443 return error;
5444 wg->wg_ops = &wg_ops_rumpuser;
5445 return 0;
5446 #endif
5447 default:
5448 break;
5449 }
5450
5451 error = ifioctl_common(ifp, cmd, data);
5452
5453 #ifdef WG_RUMPKERNEL
5454 if (!wg_user_mode(wg))
5455 return error;
5456
5457 /* Do the same to the corresponding tun device on the host */
5458 /*
5459 * XXX Actually the command has not been handled yet. It
5460 * will be handled via pr_ioctl form doifioctl later.
5461 */
5462 switch (cmd) {
5463 #ifdef INET
5464 case SIOCAIFADDR:
5465 case SIOCDIFADDR: {
5466 struct in_aliasreq _ifra = *(const struct in_aliasreq *)data;
5467 struct in_aliasreq *ifra = &_ifra;
5468 KASSERT(error == ENOTTY);
5469 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5470 IFNAMSIZ);
5471 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET);
5472 if (error == 0)
5473 error = ENOTTY;
5474 break;
5475 }
5476 #endif
5477 #ifdef INET6
5478 case SIOCAIFADDR_IN6:
5479 case SIOCDIFADDR_IN6: {
5480 struct in6_aliasreq _ifra = *(const struct in6_aliasreq *)data;
5481 struct in6_aliasreq *ifra = &_ifra;
5482 KASSERT(error == ENOTTY);
5483 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5484 IFNAMSIZ);
5485 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET6);
5486 if (error == 0)
5487 error = ENOTTY;
5488 break;
5489 }
5490 #endif
5491 default:
5492 break;
5493 }
5494 #endif /* WG_RUMPKERNEL */
5495
5496 return error;
5497 }
5498
5499 static int
5500 wg_init(struct ifnet *ifp)
5501 {
5502
5503 ifp->if_flags |= IFF_RUNNING;
5504
5505 /* TODO flush pending packets. */
5506 return 0;
5507 }
5508
5509 #ifdef ALTQ
5510 static void
5511 wg_start(struct ifnet *ifp)
5512 {
5513 struct mbuf *m;
5514
5515 for (;;) {
5516 IFQ_DEQUEUE(&ifp->if_snd, m);
5517 if (m == NULL)
5518 break;
5519
5520 kpreempt_disable();
5521 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
5522 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
5523 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
5524 if_name(ifp));
5525 m_freem(m);
5526 }
5527 kpreempt_enable();
5528 }
5529 }
5530 #endif
5531
5532 static void
5533 wg_stop(struct ifnet *ifp, int disable)
5534 {
5535
5536 KASSERT((ifp->if_flags & IFF_RUNNING) != 0);
5537 ifp->if_flags &= ~IFF_RUNNING;
5538
5539 /* Need to do something? */
5540 }
5541
5542 #ifdef WG_DEBUG_PARAMS
5543 SYSCTL_SETUP(sysctl_net_wg_setup, "sysctl net.wg setup")
5544 {
5545 const struct sysctlnode *node = NULL;
5546
5547 sysctl_createv(clog, 0, NULL, &node,
5548 CTLFLAG_PERMANENT,
5549 CTLTYPE_NODE, "wg",
5550 SYSCTL_DESCR("wg(4)"),
5551 NULL, 0, NULL, 0,
5552 CTL_NET, CTL_CREATE, CTL_EOL);
5553 sysctl_createv(clog, 0, &node, NULL,
5554 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5555 CTLTYPE_QUAD, "rekey_after_messages",
5556 SYSCTL_DESCR("session lifetime by messages"),
5557 NULL, 0, &wg_rekey_after_messages, 0, CTL_CREATE, CTL_EOL);
5558 sysctl_createv(clog, 0, &node, NULL,
5559 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5560 CTLTYPE_INT, "rekey_after_time",
5561 SYSCTL_DESCR("session lifetime"),
5562 NULL, 0, &wg_rekey_after_time, 0, CTL_CREATE, CTL_EOL);
5563 sysctl_createv(clog, 0, &node, NULL,
5564 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5565 CTLTYPE_INT, "rekey_timeout",
5566 SYSCTL_DESCR("session handshake retry time"),
5567 NULL, 0, &wg_rekey_timeout, 0, CTL_CREATE, CTL_EOL);
5568 sysctl_createv(clog, 0, &node, NULL,
5569 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5570 CTLTYPE_INT, "rekey_attempt_time",
5571 SYSCTL_DESCR("session handshake timeout"),
5572 NULL, 0, &wg_rekey_attempt_time, 0, CTL_CREATE, CTL_EOL);
5573 sysctl_createv(clog, 0, &node, NULL,
5574 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5575 CTLTYPE_INT, "keepalive_timeout",
5576 SYSCTL_DESCR("keepalive timeout"),
5577 NULL, 0, &wg_keepalive_timeout, 0, CTL_CREATE, CTL_EOL);
5578 sysctl_createv(clog, 0, &node, NULL,
5579 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5580 CTLTYPE_BOOL, "force_underload",
5581 SYSCTL_DESCR("force to detemine under load"),
5582 NULL, 0, &wg_force_underload, 0, CTL_CREATE, CTL_EOL);
5583 sysctl_createv(clog, 0, &node, NULL,
5584 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5585 CTLTYPE_INT, "debug",
5586 SYSCTL_DESCR("set debug flags 1=log 2=trace 4=dump 8=packet"),
5587 NULL, 0, &wg_debug, 0, CTL_CREATE, CTL_EOL);
5588 }
5589 #endif
5590
5591 #ifdef WG_RUMPKERNEL
5592 static bool
5593 wg_user_mode(struct wg_softc *wg)
5594 {
5595
5596 return wg->wg_user != NULL;
5597 }
5598
5599 static int
5600 wg_ioctl_linkstr(struct wg_softc *wg, struct ifdrv *ifd)
5601 {
5602 struct ifnet *ifp = &wg->wg_if;
5603 int error;
5604
5605 if (ifp->if_flags & IFF_UP)
5606 return EBUSY;
5607
5608 if (ifd->ifd_cmd == IFLINKSTR_UNSET) {
5609 /* XXX do nothing */
5610 return 0;
5611 } else if (ifd->ifd_cmd != 0) {
5612 return EINVAL;
5613 } else if (wg->wg_user != NULL) {
5614 return EBUSY;
5615 }
5616
5617 /* Assume \0 included */
5618 if (ifd->ifd_len > IFNAMSIZ) {
5619 return E2BIG;
5620 } else if (ifd->ifd_len < 1) {
5621 return EINVAL;
5622 }
5623
5624 char tun_name[IFNAMSIZ];
5625 error = copyinstr(ifd->ifd_data, tun_name, ifd->ifd_len, NULL);
5626 if (error != 0)
5627 return error;
5628
5629 if (strncmp(tun_name, "tun", 3) != 0)
5630 return EINVAL;
5631
5632 error = rumpuser_wg_create(tun_name, wg, &wg->wg_user);
5633
5634 return error;
5635 }
5636
5637 static int
5638 wg_send_user(struct wg_peer *wgp, struct mbuf *m, bool handshake)
5639 {
5640 int error;
5641 struct psref psref;
5642 struct wg_sockaddr *wgsa;
5643 struct wg_softc *wg = wgp->wgp_sc;
5644 void *pkt;
5645 size_t pktlen;
5646
5647 wgsa = wg_get_endpoint_sa(wgp, &psref);
5648
5649 #ifdef WG_DEBUG_LOG
5650 if (handshake) {
5651 char addr[128];
5652 sockaddr_format(wgsatosa(wgsa), addr, sizeof(addr));
5653 WG_DLOG("send handshake msg to %s\n", addr);
5654 }
5655 #endif
5656
5657 pkt = mtod(m, void *);
5658 pktlen = m->m_len;
5659
5660 /* Send messages to a peer via an ordinary socket. */
5661 error = rumpuser_wg_send_peer(wg->wg_user, wgsatosa(wgsa),
5662 pkt, pktlen);
5663
5664 wg_put_sa(wgp, wgsa, &psref);
5665
5666 m_freem(m);
5667
5668 return error;
5669 }
5670
5671 static int
5672 wg_send_cookie_user(struct wg_softc *wg, const struct sockaddr *src,
5673 struct mbuf *m)
5674 {
5675 union {
5676 struct sockaddr sa;
5677 struct sockaddr_in sin;
5678 struct sockaddr_in6 sin6;
5679 } dst;
5680 void *pkt;
5681 size_t pktlen;
5682 int error;
5683
5684 #ifdef WG_DEBUG_LOG
5685 char addr[128];
5686 sockaddr_format(src, addr, sizeof(addr));
5687 WG_DLOG("send cookie to %s\n", addr);
5688 #endif
5689
5690 sockaddr_copy(&dst.sa, sizeof(dst), src);
5691 pkt = mtod(m, void *);
5692 pktlen = m->m_len;
5693 error = rumpuser_wg_send_peer(wg->wg_user, &dst.sa, pkt, pktlen);
5694 m_freem(m);
5695 return error;
5696 }
5697
5698 static int
5699 wg_send_hs_user(struct wg_peer *wgp, struct mbuf *m)
5700 {
5701
5702 return wg_send_user(wgp, m, /*handshake*/true);
5703 }
5704
5705 static int
5706 wg_send_data_user(struct wg_peer *wgp, struct mbuf *m)
5707 {
5708
5709 return wg_send_user(wgp, m, /*handshake*/false);
5710 }
5711
5712 static void
5713 wg_input_user(struct ifnet *ifp, struct mbuf *m, const int af)
5714 {
5715 struct wg_softc *wg = ifp->if_softc;
5716 union {
5717 struct sockaddr sa;
5718 #ifdef INET
5719 struct sockaddr_in sin;
5720 #endif
5721 #ifdef INET6
5722 struct sockaddr_in6 sin6;
5723 #endif
5724 } dst;
5725 const void *pkt;
5726 size_t pktlen;
5727
5728 KASSERT(af == AF_INET || af == AF_INET6);
5729
5730 WG_TRACE("");
5731
5732 switch (af) {
5733 #ifdef INET
5734 case AF_INET: {
5735 struct ip *ip;
5736
5737 KASSERT(m->m_len >= sizeof(struct ip));
5738 ip = mtod(m, struct ip *);
5739 sockaddr_in_init(&dst.sin, &ip->ip_dst, 0);
5740 break;
5741 }
5742 #endif
5743 #ifdef INET6
5744 case AF_INET6: {
5745 struct ip6_hdr *ip6;
5746
5747 KASSERT(m->m_len >= sizeof(struct ip6_hdr));
5748 ip6 = mtod(m, struct ip6_hdr *);
5749 sockaddr_in6_init(&dst.sin6, &ip6->ip6_dst, 0, 0, 0);
5750 break;
5751 }
5752 #endif
5753 default:
5754 goto out;
5755 }
5756
5757 pkt = mtod(m, void *);
5758 pktlen = m->m_len;
5759
5760 WG_DUMP_BUF(pkt, pktlen);
5761
5762 /* Send decrypted packets to users via a tun. */
5763 rumpuser_wg_send_user(wg->wg_user, &dst.sa, pkt, pktlen);
5764
5765 out: m_freem(m);
5766 }
5767
5768 static int
5769 wg_bind_port_user(struct wg_softc *wg, const uint16_t port)
5770 {
5771 int error;
5772 uint16_t old_port = wg->wg_listen_port;
5773
5774 if (port != 0 && old_port == port)
5775 return 0;
5776
5777 error = rumpuser_wg_sock_bind(wg->wg_user, port);
5778 if (error)
5779 return error;
5780
5781 wg->wg_listen_port = port;
5782 return 0;
5783 }
5784
5785 /*
5786 * Receive outgoing packets from the kernel network stack on the wgN
5787 * interface (actually, tunN).
5788 */
5789 void
5790 rumpkern_wg_recv_user(struct wg_softc *wg, const struct sockaddr *dst,
5791 const void *pkt, size_t pktlen)
5792 {
5793 struct ifnet *ifp = &wg->wg_if;
5794 struct mbuf *m;
5795 int error;
5796
5797 WG_TRACE("");
5798
5799 if (pktlen > INT_MAX) /* paranoia */
5800 return;
5801
5802 m = m_gethdr(M_DONTWAIT, MT_DATA);
5803 if (m == NULL)
5804 return;
5805 m->m_len = m->m_pkthdr.len = 0;
5806 m_copyback(m, 0, (int)pktlen, pkt);
5807
5808 WG_DLOG("iov_len=%zu\n", pktlen);
5809 WG_DUMP_BUF(pkt, pktlen);
5810
5811 error = wg_output(ifp, m, dst, NULL); /* consumes m */
5812 if (error)
5813 WG_DLOG("wg_output failed, error=%d\n", error);
5814 }
5815
5816 /*
5817 * Receive incoming packets packets from a peer on the network.
5818 */
5819 void
5820 rumpkern_wg_recv_peer(struct wg_softc *wg, const struct sockaddr *src,
5821 const void *pkt, size_t pktlen)
5822 {
5823 struct mbuf *m;
5824 int bound;
5825
5826 WG_TRACE("");
5827
5828 if (pktlen > INT_MAX) /* paranoia */
5829 return;
5830
5831 /*
5832 * If the input UDP packet is too short, just drop it on the
5833 * floor like the kernel does.
5834 */
5835 if (pktlen < sizeof(struct wg_msg))
5836 return;
5837
5838 /*
5839 * Create an mbuf with the data. Can't use the caller's buffer
5840 * -- don't know how long it will last. (XXX Should maybe push
5841 * mbuf allocation into the caller to we don't have to memcpy
5842 * here.)
5843 */
5844 m = m_gethdr(M_DONTWAIT, MT_DATA);
5845 if (m == NULL)
5846 return;
5847 m->m_len = m->m_pkthdr.len = 0;
5848 m_copyback(m, 0, (int)pktlen, pkt);
5849
5850 WG_DLOG("iov_len=%zu\n", pktlen);
5851 WG_DUMP_BUF(pkt, pktlen);
5852
5853 bound = curlwp_bind();
5854 wg_handle_packet(wg, m, src);
5855 curlwp_bindx(bound);
5856 }
5857 #endif /* WG_RUMPKERNEL */
5858
5859 /*
5860 * Module infrastructure
5861 */
5862 #include "if_module.h"
5863
5864 IF_MODULE(MODULE_CLASS_DRIVER, wg, "sodium,blake2s")
5865