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