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