if_wg.c revision 1.123 1 /* $NetBSD: if_wg.c,v 1.123 2024/07/29 18:43:11 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.123 2024/07/29 18:43:11 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 m_freem(m);
1915 return;
1916 }
1917
1918 WG_TRACE("init msg sent");
1919 if (wgp->wgp_handshake_start_time == 0)
1920 wgp->wgp_handshake_start_time = time_uptime;
1921 callout_schedule(&wgp->wgp_handshake_timeout_timer,
1922 MIN(wg_rekey_timeout, (unsigned)(INT_MAX / hz)) * hz);
1923 }
1924
1925 static void
1926 wg_fill_msg_resp(struct wg_softc *wg, struct wg_peer *wgp,
1927 struct wg_session *wgs, struct wg_msg_resp *wgmr,
1928 const struct wg_msg_init *wgmi)
1929 {
1930 uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.3: Cr */
1931 uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.3: Hr */
1932 uint8_t cipher_key[WG_KDF_OUTPUT_LEN];
1933 uint8_t pubkey[WG_EPHEMERAL_KEY_LEN];
1934 uint8_t privkey[WG_EPHEMERAL_KEY_LEN];
1935
1936 KASSERT(mutex_owned(wgp->wgp_lock));
1937 KASSERT(wgs == wgp->wgp_session_unstable);
1938 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
1939 wgs->wgs_state);
1940
1941 memcpy(hash, wgs->wgs_handshake_hash, sizeof(hash));
1942 memcpy(ckey, wgs->wgs_chaining_key, sizeof(ckey));
1943
1944 wgmr->wgmr_type = htole32(WG_MSG_TYPE_RESP);
1945 wgmr->wgmr_sender = wgs->wgs_local_index;
1946 wgmr->wgmr_receiver = wgmi->wgmi_sender;
1947
1948 /* [W] 5.4.3 Second Message: Responder to Initiator */
1949
1950 /* [N] 2.2: "e" */
1951 /* Er^priv, Er^pub := DH-GENERATE() */
1952 wg_algo_generate_keypair(pubkey, privkey);
1953 /* Cr := KDF1(Cr, Er^pub) */
1954 wg_algo_kdf(ckey, NULL, NULL, ckey, pubkey, sizeof(pubkey));
1955 /* msg.ephemeral := Er^pub */
1956 memcpy(wgmr->wgmr_ephemeral, pubkey, sizeof(wgmr->wgmr_ephemeral));
1957 /* Hr := HASH(Hr || msg.ephemeral) */
1958 wg_algo_hash(hash, pubkey, sizeof(pubkey));
1959
1960 WG_DUMP_HASH("ckey", ckey);
1961 WG_DUMP_HASH("hash", hash);
1962
1963 /* [N] 2.2: "ee" */
1964 /* Cr := KDF1(Cr, DH(Er^priv, Ei^pub)) */
1965 wg_algo_dh_kdf(ckey, NULL, privkey, wgs->wgs_ephemeral_key_peer);
1966
1967 /* [N] 2.2: "se" */
1968 /* Cr := KDF1(Cr, DH(Er^priv, Si^pub)) */
1969 wg_algo_dh_kdf(ckey, NULL, privkey, wgp->wgp_pubkey);
1970
1971 /* [N] 9.2: "psk" */
1972 {
1973 uint8_t kdfout[WG_KDF_OUTPUT_LEN];
1974 /* Cr, r, k := KDF3(Cr, Q) */
1975 wg_algo_kdf(ckey, kdfout, cipher_key, ckey, wgp->wgp_psk,
1976 sizeof(wgp->wgp_psk));
1977 /* Hr := HASH(Hr || r) */
1978 wg_algo_hash(hash, kdfout, sizeof(kdfout));
1979 }
1980
1981 /* msg.empty := AEAD(k, 0, e, Hr) */
1982 wg_algo_aead_enc(wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty),
1983 cipher_key, 0, NULL, 0, hash, sizeof(hash));
1984 /* Hr := HASH(Hr || msg.empty) */
1985 wg_algo_hash(hash, wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty));
1986
1987 WG_DUMP_HASH("wgmr_empty", wgmr->wgmr_empty);
1988
1989 /* [W] 5.4.4: Cookie MACs */
1990 /* msg.mac1 := MAC(HASH(LABEL-MAC1 || Sm'^pub), msg_a) */
1991 wg_algo_mac_mac1(wgmr->wgmr_mac1, sizeof(wgmi->wgmi_mac1),
1992 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey),
1993 (const uint8_t *)wgmr, offsetof(struct wg_msg_resp, wgmr_mac1));
1994 /* Need mac1 to decrypt a cookie from a cookie message */
1995 memcpy(wgp->wgp_last_sent_mac1, wgmr->wgmr_mac1,
1996 sizeof(wgp->wgp_last_sent_mac1));
1997 wgp->wgp_last_sent_mac1_valid = true;
1998
1999 if (wgp->wgp_latest_cookie_time == 0 ||
2000 (time_uptime - wgp->wgp_latest_cookie_time) >= WG_COOKIE_TIME)
2001 /* msg.mac2 := 0^16 */
2002 memset(wgmr->wgmr_mac2, 0, sizeof(wgmr->wgmr_mac2));
2003 else {
2004 /* msg.mac2 := MAC(Lm, msg_b) */
2005 wg_algo_mac(wgmr->wgmr_mac2, sizeof(wgmi->wgmi_mac2),
2006 wgp->wgp_latest_cookie, WG_COOKIE_LEN,
2007 (const uint8_t *)wgmr,
2008 offsetof(struct wg_msg_resp, wgmr_mac2),
2009 NULL, 0);
2010 }
2011
2012 memcpy(wgs->wgs_handshake_hash, hash, sizeof(hash));
2013 memcpy(wgs->wgs_chaining_key, ckey, sizeof(ckey));
2014 memcpy(wgs->wgs_ephemeral_key_pub, pubkey, sizeof(pubkey));
2015 memcpy(wgs->wgs_ephemeral_key_priv, privkey, sizeof(privkey));
2016 wgs->wgs_remote_index = wgmi->wgmi_sender;
2017 WG_DLOG("sender=%x\n", wgs->wgs_local_index);
2018 WG_DLOG("receiver=%x\n", wgs->wgs_remote_index);
2019 }
2020
2021 /*
2022 * wg_swap_sessions(wg, wgp)
2023 *
2024 * Caller has just finished establishing the unstable session in
2025 * wg for peer wgp. Publish it as the stable session, send queued
2026 * packets or keepalives as necessary to kick off the session,
2027 * move the previously stable session to unstable, and begin
2028 * destroying it.
2029 */
2030 static void
2031 wg_swap_sessions(struct wg_softc *wg, struct wg_peer *wgp)
2032 {
2033 struct wg_session *wgs, *wgs_prev;
2034 struct mbuf *m;
2035
2036 KASSERT(mutex_owned(wgp->wgp_lock));
2037
2038 /*
2039 * Get the newly established session, to become the new
2040 * session. Caller must have transitioned from INIT_ACTIVE to
2041 * INIT_PASSIVE or to ESTABLISHED already. This will become
2042 * the stable session.
2043 */
2044 wgs = wgp->wgp_session_unstable;
2045 KASSERTMSG(wgs->wgs_state == WGS_STATE_ESTABLISHED, "state=%d",
2046 wgs->wgs_state);
2047
2048 /*
2049 * Get the stable session, which is either the previously
2050 * established session in the ESTABLISHED state, or has not
2051 * been established at all and is UNKNOWN. This will become
2052 * the unstable session.
2053 */
2054 wgs_prev = wgp->wgp_session_stable;
2055 KASSERTMSG((wgs_prev->wgs_state == WGS_STATE_ESTABLISHED ||
2056 wgs_prev->wgs_state == WGS_STATE_UNKNOWN),
2057 "state=%d", wgs_prev->wgs_state);
2058
2059 /*
2060 * Publish the newly established session for the tx path to use
2061 * and make the other one the unstable session to handle
2062 * stragglers in the rx path and later be used for the next
2063 * session's handshake.
2064 */
2065 atomic_store_release(&wgp->wgp_session_stable, wgs);
2066 wgp->wgp_session_unstable = wgs_prev;
2067
2068 /*
2069 * Record the handshake time and reset the handshake state.
2070 */
2071 getnanotime(&wgp->wgp_last_handshake_time);
2072 wgp->wgp_handshake_start_time = 0;
2073 wgp->wgp_last_sent_mac1_valid = false;
2074 wgp->wgp_last_sent_cookie_valid = false;
2075
2076 /*
2077 * If we had a data packet queued up, send it.
2078 *
2079 * If not, but we're the initiator, send a keepalive message --
2080 * if we're the initiator we have to send something immediately
2081 * or else the responder will never answer.
2082 */
2083 if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
2084 kpreempt_disable();
2085 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
2086 M_SETCTX(m, wgp);
2087 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
2088 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
2089 if_name(&wg->wg_if));
2090 m_freem(m);
2091 }
2092 kpreempt_enable();
2093 } else if (wgs->wgs_is_initiator) {
2094 wg_send_keepalive_msg(wgp, wgs);
2095 }
2096
2097 /*
2098 * If the previous stable session was established, begin to
2099 * destroy it.
2100 */
2101 if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
2102 /*
2103 * Transition ESTABLISHED->DESTROYING. The session
2104 * will remain usable for the data rx path to process
2105 * packets still in flight to us, but we won't use it
2106 * for data tx.
2107 */
2108 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
2109 " -> WGS_STATE_DESTROYING\n",
2110 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
2111 atomic_store_relaxed(&wgs_prev->wgs_state,
2112 WGS_STATE_DESTROYING);
2113 } else {
2114 KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
2115 "state=%d", wgs_prev->wgs_state);
2116 wgs_prev->wgs_local_index = 0; /* paranoia */
2117 wgs_prev->wgs_remote_index = 0; /* paranoia */
2118 wg_clear_states(wgs_prev); /* paranoia */
2119 wgs_prev->wgs_state = WGS_STATE_UNKNOWN;
2120 }
2121 }
2122
2123 static void __noinline
2124 wg_handle_msg_resp(struct wg_softc *wg, const struct wg_msg_resp *wgmr,
2125 const struct sockaddr *src)
2126 {
2127 uint8_t ckey[WG_CHAINING_KEY_LEN]; /* [W] 5.4.3: Cr */
2128 uint8_t hash[WG_HASH_LEN]; /* [W] 5.4.3: Kr */
2129 uint8_t cipher_key[WG_KDF_OUTPUT_LEN];
2130 struct wg_peer *wgp;
2131 struct wg_session *wgs;
2132 struct psref psref;
2133 int error;
2134 uint8_t mac1[WG_MAC_LEN];
2135
2136 wg_algo_mac_mac1(mac1, sizeof(mac1),
2137 wg->wg_pubkey, sizeof(wg->wg_pubkey),
2138 (const uint8_t *)wgmr, offsetof(struct wg_msg_resp, wgmr_mac1));
2139
2140 /*
2141 * [W] 5.3: Denial of Service Mitigation & Cookies
2142 * "the responder, ..., must always reject messages with an invalid
2143 * msg.mac1"
2144 */
2145 if (!consttime_memequal(mac1, wgmr->wgmr_mac1, sizeof(mac1))) {
2146 WG_DLOG("mac1 is invalid\n");
2147 return;
2148 }
2149
2150 WG_TRACE("resp msg received");
2151 wgs = wg_lookup_session_by_index(wg, wgmr->wgmr_receiver, &psref);
2152 if (wgs == NULL) {
2153 WG_TRACE("No session found");
2154 return;
2155 }
2156
2157 wgp = wgs->wgs_peer;
2158
2159 mutex_enter(wgp->wgp_lock);
2160
2161 /* If we weren't waiting for a handshake response, drop it. */
2162 if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE) {
2163 WG_TRACE("peer sent spurious handshake response, ignoring");
2164 goto out;
2165 }
2166
2167 if (__predict_false(wg_is_underload(wg, wgp, WG_MSG_TYPE_RESP))) {
2168 WG_TRACE("under load");
2169 /*
2170 * [W] 5.3: Denial of Service Mitigation & Cookies
2171 * "the responder, ..., and when under load may reject messages
2172 * with an invalid msg.mac2. If the responder receives a
2173 * message with a valid msg.mac1 yet with an invalid msg.mac2,
2174 * and is under load, it may respond with a cookie reply
2175 * message"
2176 */
2177 uint8_t zero[WG_MAC_LEN] = {0};
2178 if (consttime_memequal(wgmr->wgmr_mac2, zero, sizeof(zero))) {
2179 WG_TRACE("sending a cookie message: no cookie included");
2180 wg_send_cookie_msg(wg, wgp, wgmr->wgmr_sender,
2181 wgmr->wgmr_mac1, src);
2182 goto out;
2183 }
2184 if (!wgp->wgp_last_sent_cookie_valid) {
2185 WG_TRACE("sending a cookie message: no cookie sent ever");
2186 wg_send_cookie_msg(wg, wgp, wgmr->wgmr_sender,
2187 wgmr->wgmr_mac1, src);
2188 goto out;
2189 }
2190 uint8_t mac2[WG_MAC_LEN];
2191 wg_algo_mac(mac2, sizeof(mac2), wgp->wgp_last_sent_cookie,
2192 WG_COOKIE_LEN, (const uint8_t *)wgmr,
2193 offsetof(struct wg_msg_resp, wgmr_mac2), NULL, 0);
2194 if (!consttime_memequal(mac2, wgmr->wgmr_mac2, sizeof(mac2))) {
2195 WG_DLOG("mac2 is invalid\n");
2196 goto out;
2197 }
2198 WG_TRACE("under load, but continue to sending");
2199 }
2200
2201 memcpy(hash, wgs->wgs_handshake_hash, sizeof(hash));
2202 memcpy(ckey, wgs->wgs_chaining_key, sizeof(ckey));
2203
2204 /*
2205 * [W] 5.4.3 Second Message: Responder to Initiator
2206 * "When the initiator receives this message, it does the same
2207 * operations so that its final state variables are identical,
2208 * replacing the operands of the DH function to produce equivalent
2209 * values."
2210 * Note that the following comments of operations are just copies of
2211 * the initiator's ones.
2212 */
2213
2214 /* [N] 2.2: "e" */
2215 /* Cr := KDF1(Cr, Er^pub) */
2216 wg_algo_kdf(ckey, NULL, NULL, ckey, wgmr->wgmr_ephemeral,
2217 sizeof(wgmr->wgmr_ephemeral));
2218 /* Hr := HASH(Hr || msg.ephemeral) */
2219 wg_algo_hash(hash, wgmr->wgmr_ephemeral, sizeof(wgmr->wgmr_ephemeral));
2220
2221 WG_DUMP_HASH("ckey", ckey);
2222 WG_DUMP_HASH("hash", hash);
2223
2224 /* [N] 2.2: "ee" */
2225 /* Cr := KDF1(Cr, DH(Er^priv, Ei^pub)) */
2226 wg_algo_dh_kdf(ckey, NULL, wgs->wgs_ephemeral_key_priv,
2227 wgmr->wgmr_ephemeral);
2228
2229 /* [N] 2.2: "se" */
2230 /* Cr := KDF1(Cr, DH(Er^priv, Si^pub)) */
2231 wg_algo_dh_kdf(ckey, NULL, wg->wg_privkey, wgmr->wgmr_ephemeral);
2232
2233 /* [N] 9.2: "psk" */
2234 {
2235 uint8_t kdfout[WG_KDF_OUTPUT_LEN];
2236 /* Cr, r, k := KDF3(Cr, Q) */
2237 wg_algo_kdf(ckey, kdfout, cipher_key, ckey, wgp->wgp_psk,
2238 sizeof(wgp->wgp_psk));
2239 /* Hr := HASH(Hr || r) */
2240 wg_algo_hash(hash, kdfout, sizeof(kdfout));
2241 }
2242
2243 {
2244 uint8_t out[sizeof(wgmr->wgmr_empty)]; /* for safety */
2245 /* msg.empty := AEAD(k, 0, e, Hr) */
2246 error = wg_algo_aead_dec(out, 0, cipher_key, 0, wgmr->wgmr_empty,
2247 sizeof(wgmr->wgmr_empty), hash, sizeof(hash));
2248 WG_DUMP_HASH("wgmr_empty", wgmr->wgmr_empty);
2249 if (error != 0) {
2250 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2251 "%s: peer %s: wg_algo_aead_dec for empty message failed\n",
2252 if_name(&wg->wg_if), wgp->wgp_name);
2253 goto out;
2254 }
2255 /* Hr := HASH(Hr || msg.empty) */
2256 wg_algo_hash(hash, wgmr->wgmr_empty, sizeof(wgmr->wgmr_empty));
2257 }
2258
2259 memcpy(wgs->wgs_handshake_hash, hash, sizeof(wgs->wgs_handshake_hash));
2260 memcpy(wgs->wgs_chaining_key, ckey, sizeof(wgs->wgs_chaining_key));
2261 wgs->wgs_remote_index = wgmr->wgmr_sender;
2262 WG_DLOG("receiver=%x\n", wgs->wgs_remote_index);
2263
2264 /*
2265 * The packet is genuine. Update the peer's endpoint if the
2266 * source address changed.
2267 *
2268 * XXX How to prevent DoS by replaying genuine packets from the
2269 * wrong source address?
2270 */
2271 wg_update_endpoint_if_necessary(wgp, src);
2272
2273 KASSERTMSG(wgs->wgs_state == WGS_STATE_INIT_ACTIVE, "state=%d",
2274 wgs->wgs_state);
2275 wgs->wgs_time_established = time_uptime32;
2276 wg_schedule_session_dtor_timer(wgp);
2277 wgs->wgs_time_last_data_sent = 0;
2278 wgs->wgs_is_initiator = true;
2279 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]:"
2280 " calculate keys as initiator\n",
2281 wgs->wgs_local_index, wgs->wgs_remote_index);
2282 wg_calculate_keys(wgs, true);
2283 wg_clear_states(wgs);
2284
2285 /*
2286 * Session is ready to receive data now that we have received
2287 * the responder's response.
2288 *
2289 * Transition from INIT_ACTIVE to ESTABLISHED to publish it to
2290 * the data rx path, wg_handle_msg_data.
2291 */
2292 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32" -> WGS_STATE_ESTABLISHED\n",
2293 wgs->wgs_local_index, wgs->wgs_remote_index);
2294 atomic_store_release(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
2295 WG_TRACE("WGS_STATE_ESTABLISHED");
2296
2297 callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
2298
2299 /*
2300 * Session is ready to send data now that we have received the
2301 * responder's response.
2302 *
2303 * Swap the sessions to publish the new one as the stable
2304 * session for the data tx path, wg_output.
2305 */
2306 wg_swap_sessions(wg, wgp);
2307 KASSERT(wgs == wgp->wgp_session_stable);
2308
2309 out:
2310 mutex_exit(wgp->wgp_lock);
2311 wg_put_session(wgs, &psref);
2312 }
2313
2314 static void
2315 wg_send_handshake_msg_resp(struct wg_softc *wg, struct wg_peer *wgp,
2316 struct wg_session *wgs, const struct wg_msg_init *wgmi)
2317 {
2318 int error;
2319 struct mbuf *m;
2320 struct wg_msg_resp *wgmr;
2321
2322 KASSERT(mutex_owned(wgp->wgp_lock));
2323 KASSERT(wgs == wgp->wgp_session_unstable);
2324 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
2325 wgs->wgs_state);
2326
2327 m = m_gethdr(M_WAIT, MT_DATA);
2328 if (sizeof(*wgmr) > MHLEN) {
2329 m_clget(m, M_WAIT);
2330 CTASSERT(sizeof(*wgmr) <= MCLBYTES);
2331 }
2332 m->m_pkthdr.len = m->m_len = sizeof(*wgmr);
2333 wgmr = mtod(m, struct wg_msg_resp *);
2334 wg_fill_msg_resp(wg, wgp, wgs, wgmr, wgmi);
2335
2336 error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
2337 if (error) {
2338 WG_DLOG("send_hs_msg failed, error=%d\n", error);
2339 return;
2340 }
2341
2342 WG_TRACE("resp msg sent");
2343 }
2344
2345 static struct wg_peer *
2346 wg_lookup_peer_by_pubkey(struct wg_softc *wg,
2347 const uint8_t pubkey[static WG_STATIC_KEY_LEN], struct psref *psref)
2348 {
2349 struct wg_peer *wgp;
2350
2351 int s = pserialize_read_enter();
2352 wgp = thmap_get(wg->wg_peers_bypubkey, pubkey, WG_STATIC_KEY_LEN);
2353 if (wgp != NULL)
2354 wg_get_peer(wgp, psref);
2355 pserialize_read_exit(s);
2356
2357 return wgp;
2358 }
2359
2360 static void
2361 wg_fill_msg_cookie(struct wg_softc *wg, struct wg_peer *wgp,
2362 struct wg_msg_cookie *wgmc, const uint32_t sender,
2363 const uint8_t mac1[static WG_MAC_LEN], const struct sockaddr *src)
2364 {
2365 uint8_t cookie[WG_COOKIE_LEN];
2366 uint8_t key[WG_HASH_LEN];
2367 uint8_t addr[sizeof(struct in6_addr)];
2368 size_t addrlen;
2369 uint16_t uh_sport; /* be */
2370
2371 KASSERT(mutex_owned(wgp->wgp_lock));
2372
2373 wgmc->wgmc_type = htole32(WG_MSG_TYPE_COOKIE);
2374 wgmc->wgmc_receiver = sender;
2375 cprng_fast(wgmc->wgmc_salt, sizeof(wgmc->wgmc_salt));
2376
2377 /*
2378 * [W] 5.4.7: Under Load: Cookie Reply Message
2379 * "The secret variable, Rm, changes every two minutes to a
2380 * random value"
2381 */
2382 if ((time_uptime - wgp->wgp_last_cookiesecret_time) >
2383 WG_COOKIESECRET_TIME) {
2384 cprng_strong(kern_cprng, wgp->wgp_cookiesecret,
2385 sizeof(wgp->wgp_cookiesecret), 0);
2386 wgp->wgp_last_cookiesecret_time = time_uptime;
2387 }
2388
2389 switch (src->sa_family) {
2390 #ifdef INET
2391 case AF_INET: {
2392 const struct sockaddr_in *sin = satocsin(src);
2393 addrlen = sizeof(sin->sin_addr);
2394 memcpy(addr, &sin->sin_addr, addrlen);
2395 uh_sport = sin->sin_port;
2396 break;
2397 }
2398 #endif
2399 #ifdef INET6
2400 case AF_INET6: {
2401 const struct sockaddr_in6 *sin6 = satocsin6(src);
2402 addrlen = sizeof(sin6->sin6_addr);
2403 memcpy(addr, &sin6->sin6_addr, addrlen);
2404 uh_sport = sin6->sin6_port;
2405 break;
2406 }
2407 #endif
2408 default:
2409 panic("invalid af=%d", src->sa_family);
2410 }
2411
2412 wg_algo_mac(cookie, sizeof(cookie),
2413 wgp->wgp_cookiesecret, sizeof(wgp->wgp_cookiesecret),
2414 addr, addrlen, (const uint8_t *)&uh_sport, sizeof(uh_sport));
2415 wg_algo_mac_cookie(key, sizeof(key), wg->wg_pubkey,
2416 sizeof(wg->wg_pubkey));
2417 wg_algo_xaead_enc(wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie), key,
2418 cookie, sizeof(cookie), mac1, WG_MAC_LEN, wgmc->wgmc_salt);
2419
2420 /* Need to store to calculate mac2 */
2421 memcpy(wgp->wgp_last_sent_cookie, cookie, sizeof(cookie));
2422 wgp->wgp_last_sent_cookie_valid = true;
2423 }
2424
2425 static void
2426 wg_send_cookie_msg(struct wg_softc *wg, struct wg_peer *wgp,
2427 const uint32_t sender, const uint8_t mac1[static WG_MAC_LEN],
2428 const struct sockaddr *src)
2429 {
2430 int error;
2431 struct mbuf *m;
2432 struct wg_msg_cookie *wgmc;
2433
2434 KASSERT(mutex_owned(wgp->wgp_lock));
2435
2436 m = m_gethdr(M_WAIT, MT_DATA);
2437 if (sizeof(*wgmc) > MHLEN) {
2438 m_clget(m, M_WAIT);
2439 CTASSERT(sizeof(*wgmc) <= MCLBYTES);
2440 }
2441 m->m_pkthdr.len = m->m_len = sizeof(*wgmc);
2442 wgmc = mtod(m, struct wg_msg_cookie *);
2443 wg_fill_msg_cookie(wg, wgp, wgmc, sender, mac1, src);
2444
2445 error = wg->wg_ops->send_hs_msg(wgp, m); /* consumes m */
2446 if (error) {
2447 WG_DLOG("send_hs_msg failed, error=%d\n", error);
2448 return;
2449 }
2450
2451 WG_TRACE("cookie msg sent");
2452 }
2453
2454 static bool
2455 wg_is_underload(struct wg_softc *wg, struct wg_peer *wgp, int msgtype)
2456 {
2457 #ifdef WG_DEBUG_PARAMS
2458 if (wg_force_underload)
2459 return true;
2460 #endif
2461
2462 /*
2463 * XXX we don't have a means of a load estimation. The purpose of
2464 * the mechanism is a DoS mitigation, so we consider frequent handshake
2465 * messages as (a kind of) load; if a message of the same type comes
2466 * to a peer within 1 second, we consider we are under load.
2467 */
2468 time_t last = wgp->wgp_last_msg_received_time[msgtype];
2469 wgp->wgp_last_msg_received_time[msgtype] = time_uptime;
2470 return (time_uptime - last) == 0;
2471 }
2472
2473 static void
2474 wg_calculate_keys(struct wg_session *wgs, const bool initiator)
2475 {
2476
2477 KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
2478
2479 /*
2480 * [W] 5.4.5: Ti^send = Tr^recv, Ti^recv = Tr^send := KDF2(Ci = Cr, e)
2481 */
2482 if (initiator) {
2483 wg_algo_kdf(wgs->wgs_tkey_send, wgs->wgs_tkey_recv, NULL,
2484 wgs->wgs_chaining_key, NULL, 0);
2485 } else {
2486 wg_algo_kdf(wgs->wgs_tkey_recv, wgs->wgs_tkey_send, NULL,
2487 wgs->wgs_chaining_key, NULL, 0);
2488 }
2489 WG_DUMP_HASH("wgs_tkey_send", wgs->wgs_tkey_send);
2490 WG_DUMP_HASH("wgs_tkey_recv", wgs->wgs_tkey_recv);
2491 }
2492
2493 static uint64_t
2494 wg_session_get_send_counter(struct wg_session *wgs)
2495 {
2496 #ifdef __HAVE_ATOMIC64_LOADSTORE
2497 return atomic_load_relaxed(&wgs->wgs_send_counter);
2498 #else
2499 uint64_t send_counter;
2500
2501 mutex_enter(&wgs->wgs_send_counter_lock);
2502 send_counter = wgs->wgs_send_counter;
2503 mutex_exit(&wgs->wgs_send_counter_lock);
2504
2505 return send_counter;
2506 #endif
2507 }
2508
2509 static uint64_t
2510 wg_session_inc_send_counter(struct wg_session *wgs)
2511 {
2512 #ifdef __HAVE_ATOMIC64_LOADSTORE
2513 return atomic_inc_64_nv(&wgs->wgs_send_counter) - 1;
2514 #else
2515 uint64_t send_counter;
2516
2517 mutex_enter(&wgs->wgs_send_counter_lock);
2518 send_counter = wgs->wgs_send_counter++;
2519 mutex_exit(&wgs->wgs_send_counter_lock);
2520
2521 return send_counter;
2522 #endif
2523 }
2524
2525 static void
2526 wg_clear_states(struct wg_session *wgs)
2527 {
2528
2529 KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
2530
2531 wgs->wgs_send_counter = 0;
2532 sliwin_reset(&wgs->wgs_recvwin->window);
2533
2534 #define wgs_clear(v) explicit_memset(wgs->wgs_##v, 0, sizeof(wgs->wgs_##v))
2535 wgs_clear(handshake_hash);
2536 wgs_clear(chaining_key);
2537 wgs_clear(ephemeral_key_pub);
2538 wgs_clear(ephemeral_key_priv);
2539 wgs_clear(ephemeral_key_peer);
2540 #undef wgs_clear
2541 }
2542
2543 static struct wg_session *
2544 wg_lookup_session_by_index(struct wg_softc *wg, const uint32_t index,
2545 struct psref *psref)
2546 {
2547 struct wg_session *wgs;
2548
2549 int s = pserialize_read_enter();
2550 wgs = thmap_get(wg->wg_sessions_byindex, &index, sizeof index);
2551 if (wgs != NULL) {
2552 KASSERTMSG(index == wgs->wgs_local_index,
2553 "index=%"PRIx32" wgs->wgs_local_index=%"PRIx32,
2554 index, wgs->wgs_local_index);
2555 psref_acquire(psref, &wgs->wgs_psref, wg_psref_class);
2556 }
2557 pserialize_read_exit(s);
2558
2559 return wgs;
2560 }
2561
2562 static void
2563 wg_send_keepalive_msg(struct wg_peer *wgp, struct wg_session *wgs)
2564 {
2565 struct mbuf *m;
2566
2567 /*
2568 * [W] 6.5 Passive Keepalive
2569 * "A keepalive message is simply a transport data message with
2570 * a zero-length encapsulated encrypted inner-packet."
2571 */
2572 WG_TRACE("");
2573 m = m_gethdr(M_WAIT, MT_DATA);
2574 wg_send_data_msg(wgp, wgs, m);
2575 }
2576
2577 static bool
2578 wg_need_to_send_init_message(struct wg_session *wgs)
2579 {
2580 /*
2581 * [W] 6.2 Transport Message Limits
2582 * "if a peer is the initiator of a current secure session,
2583 * WireGuard will send a handshake initiation message to begin
2584 * a new secure session ... if after receiving a transport data
2585 * message, the current secure session is (REJECT-AFTER-TIME
2586 * KEEPALIVE-TIMEOUT REKEY-TIMEOUT) seconds old and it has
2587 * not yet acted upon this event."
2588 */
2589 return wgs->wgs_is_initiator &&
2590 atomic_load_relaxed(&wgs->wgs_time_last_data_sent) == 0 &&
2591 (time_uptime32 - wgs->wgs_time_established >=
2592 (wg_reject_after_time - wg_keepalive_timeout -
2593 wg_rekey_timeout));
2594 }
2595
2596 static void
2597 wg_schedule_peer_task(struct wg_peer *wgp, unsigned int task)
2598 {
2599
2600 mutex_enter(wgp->wgp_intr_lock);
2601 WG_DLOG("tasks=%d, task=%d\n", wgp->wgp_tasks, task);
2602 if (wgp->wgp_tasks == 0)
2603 /*
2604 * XXX If the current CPU is already loaded -- e.g., if
2605 * there's already a bunch of handshakes queued up --
2606 * consider tossing this over to another CPU to
2607 * distribute the load.
2608 */
2609 workqueue_enqueue(wg_wq, &wgp->wgp_work, NULL);
2610 wgp->wgp_tasks |= task;
2611 mutex_exit(wgp->wgp_intr_lock);
2612 }
2613
2614 static void
2615 wg_change_endpoint(struct wg_peer *wgp, const struct sockaddr *new)
2616 {
2617 struct wg_sockaddr *wgsa_prev;
2618
2619 WG_TRACE("Changing endpoint");
2620
2621 memcpy(wgp->wgp_endpoint0, new, new->sa_len);
2622 wgsa_prev = wgp->wgp_endpoint;
2623 atomic_store_release(&wgp->wgp_endpoint, wgp->wgp_endpoint0);
2624 wgp->wgp_endpoint0 = wgsa_prev;
2625 atomic_store_release(&wgp->wgp_endpoint_available, true);
2626
2627 wg_schedule_peer_task(wgp, WGP_TASK_ENDPOINT_CHANGED);
2628 }
2629
2630 static bool
2631 wg_validate_inner_packet(const char *packet, size_t decrypted_len, int *af)
2632 {
2633 uint16_t packet_len;
2634 const struct ip *ip;
2635
2636 if (__predict_false(decrypted_len < sizeof(*ip))) {
2637 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2638 sizeof(*ip));
2639 return false;
2640 }
2641
2642 ip = (const struct ip *)packet;
2643 if (ip->ip_v == 4)
2644 *af = AF_INET;
2645 else if (ip->ip_v == 6)
2646 *af = AF_INET6;
2647 else {
2648 WG_DLOG("ip_v=%d\n", ip->ip_v);
2649 return false;
2650 }
2651
2652 WG_DLOG("af=%d\n", *af);
2653
2654 switch (*af) {
2655 #ifdef INET
2656 case AF_INET:
2657 packet_len = ntohs(ip->ip_len);
2658 break;
2659 #endif
2660 #ifdef INET6
2661 case AF_INET6: {
2662 const struct ip6_hdr *ip6;
2663
2664 if (__predict_false(decrypted_len < sizeof(*ip6))) {
2665 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2666 sizeof(*ip6));
2667 return false;
2668 }
2669
2670 ip6 = (const struct ip6_hdr *)packet;
2671 packet_len = sizeof(*ip6) + ntohs(ip6->ip6_plen);
2672 break;
2673 }
2674 #endif
2675 default:
2676 return false;
2677 }
2678
2679 if (packet_len > decrypted_len) {
2680 WG_DLOG("packet_len %u > decrypted_len %zu\n", packet_len,
2681 decrypted_len);
2682 return false;
2683 }
2684
2685 return true;
2686 }
2687
2688 static bool
2689 wg_validate_route(struct wg_softc *wg, struct wg_peer *wgp_expected,
2690 int af, char *packet)
2691 {
2692 struct sockaddr_storage ss;
2693 struct sockaddr *sa;
2694 struct psref psref;
2695 struct wg_peer *wgp;
2696 bool ok;
2697
2698 /*
2699 * II CRYPTOKEY ROUTING
2700 * "it will only accept it if its source IP resolves in the
2701 * table to the public key used in the secure session for
2702 * decrypting it."
2703 */
2704
2705 switch (af) {
2706 #ifdef INET
2707 case AF_INET: {
2708 const struct ip *ip = (const struct ip *)packet;
2709 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
2710 sockaddr_in_init(sin, &ip->ip_src, 0);
2711 sa = sintosa(sin);
2712 break;
2713 }
2714 #endif
2715 #ifdef INET6
2716 case AF_INET6: {
2717 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)packet;
2718 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
2719 sockaddr_in6_init(sin6, &ip6->ip6_src, 0, 0, 0);
2720 sa = sin6tosa(sin6);
2721 break;
2722 }
2723 #endif
2724 default:
2725 __USE(ss);
2726 return false;
2727 }
2728
2729 wgp = wg_pick_peer_by_sa(wg, sa, &psref);
2730 ok = (wgp == wgp_expected);
2731 if (wgp != NULL)
2732 wg_put_peer(wgp, &psref);
2733
2734 return ok;
2735 }
2736
2737 static void
2738 wg_session_dtor_timer(void *arg)
2739 {
2740 struct wg_peer *wgp = arg;
2741
2742 WG_TRACE("enter");
2743
2744 wg_schedule_session_dtor_timer(wgp);
2745 wg_schedule_peer_task(wgp, WGP_TASK_DESTROY_PREV_SESSION);
2746 }
2747
2748 static void
2749 wg_schedule_session_dtor_timer(struct wg_peer *wgp)
2750 {
2751
2752 /*
2753 * If the periodic session destructor is already pending to
2754 * handle the previous session, that's fine -- leave it in
2755 * place; it will be scheduled again.
2756 */
2757 if (callout_pending(&wgp->wgp_session_dtor_timer)) {
2758 WG_DLOG("session dtor already pending\n");
2759 return;
2760 }
2761
2762 WG_DLOG("scheduling session dtor in %u secs\n", wg_reject_after_time);
2763 callout_schedule(&wgp->wgp_session_dtor_timer,
2764 wg_reject_after_time*hz);
2765 }
2766
2767 static bool
2768 sockaddr_port_match(const struct sockaddr *sa1, const struct sockaddr *sa2)
2769 {
2770 if (sa1->sa_family != sa2->sa_family)
2771 return false;
2772
2773 switch (sa1->sa_family) {
2774 #ifdef INET
2775 case AF_INET:
2776 return satocsin(sa1)->sin_port == satocsin(sa2)->sin_port;
2777 #endif
2778 #ifdef INET6
2779 case AF_INET6:
2780 return satocsin6(sa1)->sin6_port == satocsin6(sa2)->sin6_port;
2781 #endif
2782 default:
2783 return false;
2784 }
2785 }
2786
2787 static void
2788 wg_update_endpoint_if_necessary(struct wg_peer *wgp,
2789 const struct sockaddr *src)
2790 {
2791 struct wg_sockaddr *wgsa;
2792 struct psref psref;
2793
2794 wgsa = wg_get_endpoint_sa(wgp, &psref);
2795
2796 #ifdef WG_DEBUG_LOG
2797 char oldaddr[128], newaddr[128];
2798 sockaddr_format(wgsatosa(wgsa), oldaddr, sizeof(oldaddr));
2799 sockaddr_format(src, newaddr, sizeof(newaddr));
2800 WG_DLOG("old=%s, new=%s\n", oldaddr, newaddr);
2801 #endif
2802
2803 /*
2804 * III: "Since the packet has authenticated correctly, the source IP of
2805 * the outer UDP/IP packet is used to update the endpoint for peer..."
2806 */
2807 if (__predict_false(sockaddr_cmp(src, wgsatosa(wgsa)) != 0 ||
2808 !sockaddr_port_match(src, wgsatosa(wgsa)))) {
2809 /* XXX We can't change the endpoint twice in a short period */
2810 if (atomic_swap_uint(&wgp->wgp_endpoint_changing, 1) == 0) {
2811 wg_change_endpoint(wgp, src);
2812 }
2813 }
2814
2815 wg_put_sa(wgp, wgsa, &psref);
2816 }
2817
2818 static void __noinline
2819 wg_handle_msg_data(struct wg_softc *wg, struct mbuf *m,
2820 const struct sockaddr *src)
2821 {
2822 struct wg_msg_data *wgmd;
2823 char *encrypted_buf = NULL, *decrypted_buf;
2824 size_t encrypted_len, decrypted_len;
2825 struct wg_session *wgs;
2826 struct wg_peer *wgp;
2827 int state;
2828 uint32_t age;
2829 size_t mlen;
2830 struct psref psref;
2831 int error, af;
2832 bool success, free_encrypted_buf = false, ok;
2833 struct mbuf *n;
2834
2835 KASSERT(m->m_len >= sizeof(struct wg_msg_data));
2836 wgmd = mtod(m, struct wg_msg_data *);
2837
2838 KASSERT(wgmd->wgmd_type == htole32(WG_MSG_TYPE_DATA));
2839 WG_TRACE("data");
2840
2841 /* Find the putative session, or drop. */
2842 wgs = wg_lookup_session_by_index(wg, wgmd->wgmd_receiver, &psref);
2843 if (wgs == NULL) {
2844 WG_TRACE("No session found");
2845 m_freem(m);
2846 return;
2847 }
2848
2849 /*
2850 * We are only ready to handle data when in INIT_PASSIVE,
2851 * ESTABLISHED, or DESTROYING. All transitions out of that
2852 * state dissociate the session index and drain psrefs.
2853 *
2854 * atomic_load_acquire matches atomic_store_release in either
2855 * wg_handle_msg_init or wg_handle_msg_resp. (The transition
2856 * INIT_PASSIVE to ESTABLISHED in wg_task_establish_session
2857 * doesn't make a difference for this rx path.)
2858 */
2859 state = atomic_load_acquire(&wgs->wgs_state);
2860 switch (state) {
2861 case WGS_STATE_UNKNOWN:
2862 case WGS_STATE_INIT_ACTIVE:
2863 WG_TRACE("not yet ready for data");
2864 goto out;
2865 case WGS_STATE_INIT_PASSIVE:
2866 case WGS_STATE_ESTABLISHED:
2867 case WGS_STATE_DESTROYING:
2868 break;
2869 }
2870
2871 /*
2872 * Reject if the session is too old.
2873 */
2874 age = time_uptime32 - wgs->wgs_time_established;
2875 if (__predict_false(age >= wg_reject_after_time)) {
2876 WG_DLOG("session %"PRIx32" too old, %"PRIu32" sec\n",
2877 wgmd->wgmd_receiver, age);
2878 goto out;
2879 }
2880
2881 /*
2882 * Get the peer, for rate-limited logs (XXX MPSAFE, dtrace) and
2883 * to update the endpoint if authentication succeeds.
2884 */
2885 wgp = wgs->wgs_peer;
2886
2887 /*
2888 * Reject outrageously wrong sequence numbers before doing any
2889 * crypto work or taking any locks.
2890 */
2891 error = sliwin_check_fast(&wgs->wgs_recvwin->window,
2892 le64toh(wgmd->wgmd_counter));
2893 if (error) {
2894 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2895 "%s: peer %s: out-of-window packet: %"PRIu64"\n",
2896 if_name(&wg->wg_if), wgp->wgp_name,
2897 le64toh(wgmd->wgmd_counter));
2898 goto out;
2899 }
2900
2901 /* Ensure the payload and authenticator are contiguous. */
2902 mlen = m_length(m);
2903 encrypted_len = mlen - sizeof(*wgmd);
2904 if (encrypted_len < WG_AUTHTAG_LEN) {
2905 WG_DLOG("Short encrypted_len: %zu\n", encrypted_len);
2906 goto out;
2907 }
2908 success = m_ensure_contig(&m, sizeof(*wgmd) + encrypted_len);
2909 if (success) {
2910 encrypted_buf = mtod(m, char *) + sizeof(*wgmd);
2911 } else {
2912 encrypted_buf = kmem_intr_alloc(encrypted_len, KM_NOSLEEP);
2913 if (encrypted_buf == NULL) {
2914 WG_DLOG("failed to allocate encrypted_buf\n");
2915 goto out;
2916 }
2917 m_copydata(m, sizeof(*wgmd), encrypted_len, encrypted_buf);
2918 free_encrypted_buf = true;
2919 }
2920 /* m_ensure_contig may change m regardless of its result */
2921 KASSERT(m->m_len >= sizeof(*wgmd));
2922 wgmd = mtod(m, struct wg_msg_data *);
2923
2924 /*
2925 * Get a buffer for the plaintext. Add WG_AUTHTAG_LEN to avoid
2926 * a zero-length buffer (XXX). Drop if plaintext is longer
2927 * than MCLBYTES (XXX).
2928 */
2929 decrypted_len = encrypted_len - WG_AUTHTAG_LEN;
2930 if (decrypted_len > MCLBYTES) {
2931 /* FIXME handle larger data than MCLBYTES */
2932 WG_DLOG("couldn't handle larger data than MCLBYTES\n");
2933 goto out;
2934 }
2935 n = wg_get_mbuf(0, decrypted_len + WG_AUTHTAG_LEN);
2936 if (n == NULL) {
2937 WG_DLOG("wg_get_mbuf failed\n");
2938 goto out;
2939 }
2940 decrypted_buf = mtod(n, char *);
2941
2942 /* Decrypt and verify the packet. */
2943 WG_DLOG("mlen=%zu, encrypted_len=%zu\n", mlen, encrypted_len);
2944 error = wg_algo_aead_dec(decrypted_buf,
2945 encrypted_len - WG_AUTHTAG_LEN /* can be 0 */,
2946 wgs->wgs_tkey_recv, le64toh(wgmd->wgmd_counter), encrypted_buf,
2947 encrypted_len, NULL, 0);
2948 if (error != 0) {
2949 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2950 "%s: peer %s: failed to wg_algo_aead_dec\n",
2951 if_name(&wg->wg_if), wgp->wgp_name);
2952 m_freem(n);
2953 goto out;
2954 }
2955 WG_DLOG("outsize=%u\n", (u_int)decrypted_len);
2956
2957 /* Packet is genuine. Reject it if a replay or just too old. */
2958 mutex_enter(&wgs->wgs_recvwin->lock);
2959 error = sliwin_update(&wgs->wgs_recvwin->window,
2960 le64toh(wgmd->wgmd_counter));
2961 mutex_exit(&wgs->wgs_recvwin->lock);
2962 if (error) {
2963 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2964 "%s: peer %s: replay or out-of-window packet: %"PRIu64"\n",
2965 if_name(&wg->wg_if), wgp->wgp_name,
2966 le64toh(wgmd->wgmd_counter));
2967 m_freem(n);
2968 goto out;
2969 }
2970
2971 /* We're done with m now; free it and chuck the pointers. */
2972 m_freem(m);
2973 m = NULL;
2974 wgmd = NULL;
2975
2976 /*
2977 * The packet is genuine. Update the peer's endpoint if the
2978 * source address changed.
2979 *
2980 * XXX How to prevent DoS by replaying genuine packets from the
2981 * wrong source address?
2982 */
2983 wg_update_endpoint_if_necessary(wgp, src);
2984
2985 /*
2986 * Validate the encapsulated packet header and get the address
2987 * family, or drop.
2988 */
2989 ok = wg_validate_inner_packet(decrypted_buf, decrypted_len, &af);
2990 if (!ok) {
2991 m_freem(n);
2992 goto update_state;
2993 }
2994
2995 /* Submit it into our network stack if routable. */
2996 ok = wg_validate_route(wg, wgp, af, decrypted_buf);
2997 if (ok) {
2998 wg->wg_ops->input(&wg->wg_if, n, af);
2999 } else {
3000 char addrstr[INET6_ADDRSTRLEN];
3001 memset(addrstr, 0, sizeof(addrstr));
3002 switch (af) {
3003 #ifdef INET
3004 case AF_INET: {
3005 const struct ip *ip = (const struct ip *)decrypted_buf;
3006 IN_PRINT(addrstr, &ip->ip_src);
3007 break;
3008 }
3009 #endif
3010 #ifdef INET6
3011 case AF_INET6: {
3012 const struct ip6_hdr *ip6 =
3013 (const struct ip6_hdr *)decrypted_buf;
3014 IN6_PRINT(addrstr, &ip6->ip6_src);
3015 break;
3016 }
3017 #endif
3018 default:
3019 panic("invalid af=%d", af);
3020 }
3021 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3022 "%s: peer %s: invalid source address (%s)\n",
3023 if_name(&wg->wg_if), wgp->wgp_name, addrstr);
3024 m_freem(n);
3025 /*
3026 * The inner address is invalid however the session is valid
3027 * so continue the session processing below.
3028 */
3029 }
3030 n = NULL;
3031
3032 update_state:
3033 /* Update the state machine if necessary. */
3034 if (__predict_false(state == WGS_STATE_INIT_PASSIVE)) {
3035 /*
3036 * We were waiting for the initiator to send their
3037 * first data transport message, and that has happened.
3038 * Schedule a task to establish this session.
3039 */
3040 wg_schedule_peer_task(wgp, WGP_TASK_ESTABLISH_SESSION);
3041 } else {
3042 if (__predict_false(wg_need_to_send_init_message(wgs))) {
3043 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3044 }
3045 /*
3046 * [W] 6.5 Passive Keepalive
3047 * "If a peer has received a validly-authenticated transport
3048 * data message (section 5.4.6), but does not have any packets
3049 * itself to send back for KEEPALIVE-TIMEOUT seconds, it sends
3050 * a keepalive message."
3051 */
3052 const uint32_t now = time_uptime32;
3053 const uint32_t time_last_data_sent =
3054 atomic_load_relaxed(&wgs->wgs_time_last_data_sent);
3055 WG_DLOG("time_uptime32=%"PRIu32
3056 " wgs_time_last_data_sent=%"PRIu32"\n",
3057 now, time_last_data_sent);
3058 if ((now - time_last_data_sent) >= wg_keepalive_timeout) {
3059 WG_TRACE("Schedule sending keepalive message");
3060 /*
3061 * We can't send a keepalive message here to avoid
3062 * a deadlock; we already hold the solock of a socket
3063 * that is used to send the message.
3064 */
3065 wg_schedule_peer_task(wgp,
3066 WGP_TASK_SEND_KEEPALIVE_MESSAGE);
3067 }
3068 }
3069 out:
3070 wg_put_session(wgs, &psref);
3071 m_freem(m);
3072 if (free_encrypted_buf)
3073 kmem_intr_free(encrypted_buf, encrypted_len);
3074 }
3075
3076 static void __noinline
3077 wg_handle_msg_cookie(struct wg_softc *wg, const struct wg_msg_cookie *wgmc)
3078 {
3079 struct wg_session *wgs;
3080 struct wg_peer *wgp;
3081 struct psref psref;
3082 int error;
3083 uint8_t key[WG_HASH_LEN];
3084 uint8_t cookie[WG_COOKIE_LEN];
3085
3086 WG_TRACE("cookie msg received");
3087
3088 /* Find the putative session. */
3089 wgs = wg_lookup_session_by_index(wg, wgmc->wgmc_receiver, &psref);
3090 if (wgs == NULL) {
3091 WG_TRACE("No session found");
3092 return;
3093 }
3094
3095 /* Lock the peer so we can update the cookie state. */
3096 wgp = wgs->wgs_peer;
3097 mutex_enter(wgp->wgp_lock);
3098
3099 if (!wgp->wgp_last_sent_mac1_valid) {
3100 WG_TRACE("No valid mac1 sent (or expired)");
3101 goto out;
3102 }
3103
3104 /*
3105 * wgp_last_sent_mac1_valid is only set to true when we are
3106 * transitioning to INIT_ACTIVE or INIT_PASSIVE, and always
3107 * cleared on transition out of them.
3108 */
3109 KASSERTMSG((wgs->wgs_state == WGS_STATE_INIT_ACTIVE ||
3110 wgs->wgs_state == WGS_STATE_INIT_PASSIVE),
3111 "state=%d", wgs->wgs_state);
3112
3113 /* Decrypt the cookie and store it for later handshake retry. */
3114 wg_algo_mac_cookie(key, sizeof(key), wgp->wgp_pubkey,
3115 sizeof(wgp->wgp_pubkey));
3116 error = wg_algo_xaead_dec(cookie, sizeof(cookie), key,
3117 wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie),
3118 wgp->wgp_last_sent_mac1, sizeof(wgp->wgp_last_sent_mac1),
3119 wgmc->wgmc_salt);
3120 if (error != 0) {
3121 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
3122 "%s: peer %s: wg_algo_aead_dec for cookie failed: "
3123 "error=%d\n", if_name(&wg->wg_if), wgp->wgp_name, error);
3124 goto out;
3125 }
3126 /*
3127 * [W] 6.6: Interaction with Cookie Reply System
3128 * "it should simply store the decrypted cookie value from the cookie
3129 * reply message, and wait for the expiration of the REKEY-TIMEOUT
3130 * timer for retrying a handshake initiation message."
3131 */
3132 wgp->wgp_latest_cookie_time = time_uptime;
3133 memcpy(wgp->wgp_latest_cookie, cookie, sizeof(wgp->wgp_latest_cookie));
3134 out:
3135 mutex_exit(wgp->wgp_lock);
3136 wg_put_session(wgs, &psref);
3137 }
3138
3139 static struct mbuf *
3140 wg_validate_msg_header(struct wg_softc *wg, struct mbuf *m)
3141 {
3142 struct wg_msg wgm;
3143 size_t mbuflen;
3144 size_t msglen;
3145
3146 /*
3147 * Get the mbuf chain length. It is already guaranteed, by
3148 * wg_overudp_cb, to be large enough for a struct wg_msg.
3149 */
3150 mbuflen = m_length(m);
3151 KASSERT(mbuflen >= sizeof(struct wg_msg));
3152
3153 /*
3154 * Copy the message header (32-bit message type) out -- we'll
3155 * worry about contiguity and alignment later.
3156 */
3157 m_copydata(m, 0, sizeof(wgm), &wgm);
3158 switch (le32toh(wgm.wgm_type)) {
3159 case WG_MSG_TYPE_INIT:
3160 msglen = sizeof(struct wg_msg_init);
3161 break;
3162 case WG_MSG_TYPE_RESP:
3163 msglen = sizeof(struct wg_msg_resp);
3164 break;
3165 case WG_MSG_TYPE_COOKIE:
3166 msglen = sizeof(struct wg_msg_cookie);
3167 break;
3168 case WG_MSG_TYPE_DATA:
3169 msglen = sizeof(struct wg_msg_data);
3170 break;
3171 default:
3172 WG_LOG_RATECHECK(&wg->wg_ppsratecheck, LOG_DEBUG,
3173 "%s: Unexpected msg type: %u\n", if_name(&wg->wg_if),
3174 le32toh(wgm.wgm_type));
3175 goto error;
3176 }
3177
3178 /* Verify the mbuf chain is long enough for this type of message. */
3179 if (__predict_false(mbuflen < msglen)) {
3180 WG_DLOG("Invalid msg size: mbuflen=%zu type=%u\n", mbuflen,
3181 le32toh(wgm.wgm_type));
3182 goto error;
3183 }
3184
3185 /* Make the message header contiguous if necessary. */
3186 if (__predict_false(m->m_len < msglen)) {
3187 m = m_pullup(m, msglen);
3188 if (m == NULL)
3189 return NULL;
3190 }
3191
3192 return m;
3193
3194 error:
3195 m_freem(m);
3196 return NULL;
3197 }
3198
3199 static void
3200 wg_handle_packet(struct wg_softc *wg, struct mbuf *m,
3201 const struct sockaddr *src)
3202 {
3203 struct wg_msg *wgm;
3204
3205 KASSERT(curlwp->l_pflag & LP_BOUND);
3206
3207 m = wg_validate_msg_header(wg, m);
3208 if (__predict_false(m == NULL))
3209 return;
3210
3211 KASSERT(m->m_len >= sizeof(struct wg_msg));
3212 wgm = mtod(m, struct wg_msg *);
3213 switch (le32toh(wgm->wgm_type)) {
3214 case WG_MSG_TYPE_INIT:
3215 wg_handle_msg_init(wg, (struct wg_msg_init *)wgm, src);
3216 break;
3217 case WG_MSG_TYPE_RESP:
3218 wg_handle_msg_resp(wg, (struct wg_msg_resp *)wgm, src);
3219 break;
3220 case WG_MSG_TYPE_COOKIE:
3221 wg_handle_msg_cookie(wg, (struct wg_msg_cookie *)wgm);
3222 break;
3223 case WG_MSG_TYPE_DATA:
3224 wg_handle_msg_data(wg, m, src);
3225 /* wg_handle_msg_data frees m for us */
3226 return;
3227 default:
3228 panic("invalid message type: %d", le32toh(wgm->wgm_type));
3229 }
3230
3231 m_freem(m);
3232 }
3233
3234 static void
3235 wg_receive_packets(struct wg_softc *wg, const int af)
3236 {
3237
3238 for (;;) {
3239 int error, flags;
3240 struct socket *so;
3241 struct mbuf *m = NULL;
3242 struct uio dummy_uio;
3243 struct mbuf *paddr = NULL;
3244 struct sockaddr *src;
3245
3246 so = wg_get_so_by_af(wg, af);
3247 flags = MSG_DONTWAIT;
3248 dummy_uio.uio_resid = 1000000000;
3249
3250 error = so->so_receive(so, &paddr, &dummy_uio, &m, NULL,
3251 &flags);
3252 if (error || m == NULL) {
3253 //if (error == EWOULDBLOCK)
3254 return;
3255 }
3256
3257 KASSERT(paddr != NULL);
3258 KASSERT(paddr->m_len >= sizeof(struct sockaddr));
3259 src = mtod(paddr, struct sockaddr *);
3260
3261 wg_handle_packet(wg, m, src);
3262 }
3263 }
3264
3265 static void
3266 wg_get_peer(struct wg_peer *wgp, struct psref *psref)
3267 {
3268
3269 psref_acquire(psref, &wgp->wgp_psref, wg_psref_class);
3270 }
3271
3272 static void
3273 wg_put_peer(struct wg_peer *wgp, struct psref *psref)
3274 {
3275
3276 psref_release(psref, &wgp->wgp_psref, wg_psref_class);
3277 }
3278
3279 static void
3280 wg_task_send_init_message(struct wg_softc *wg, struct wg_peer *wgp)
3281 {
3282 struct wg_session *wgs;
3283
3284 WG_TRACE("WGP_TASK_SEND_INIT_MESSAGE");
3285
3286 KASSERT(mutex_owned(wgp->wgp_lock));
3287
3288 if (!atomic_load_acquire(&wgp->wgp_endpoint_available)) {
3289 WGLOG(LOG_DEBUG, "%s: No endpoint available\n",
3290 if_name(&wg->wg_if));
3291 /* XXX should do something? */
3292 return;
3293 }
3294
3295 /*
3296 * If we already have an established session, there's no need
3297 * to initiate a new one -- unless the rekey-after-time or
3298 * rekey-after-messages limits have passed.
3299 */
3300 wgs = wgp->wgp_session_stable;
3301 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3302 !atomic_load_relaxed(&wgs->wgs_force_rekey))
3303 return;
3304
3305 /*
3306 * Ensure we're initiating a new session. If the unstable
3307 * session is already INIT_ACTIVE or INIT_PASSIVE, this does
3308 * nothing.
3309 */
3310 wg_send_handshake_msg_init(wg, wgp);
3311 }
3312
3313 static void
3314 wg_task_retry_handshake(struct wg_softc *wg, struct wg_peer *wgp)
3315 {
3316 struct wg_session *wgs;
3317
3318 WG_TRACE("WGP_TASK_RETRY_HANDSHAKE");
3319
3320 KASSERT(mutex_owned(wgp->wgp_lock));
3321 KASSERT(wgp->wgp_handshake_start_time != 0);
3322
3323 wgs = wgp->wgp_session_unstable;
3324 if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE)
3325 return;
3326
3327 /*
3328 * XXX no real need to assign a new index here, but we do need
3329 * to transition to UNKNOWN temporarily
3330 */
3331 wg_put_session_index(wg, wgs);
3332
3333 /* [W] 6.4 Handshake Initiation Retransmission */
3334 if ((time_uptime - wgp->wgp_handshake_start_time) >
3335 wg_rekey_attempt_time) {
3336 /* Give up handshaking */
3337 wgp->wgp_handshake_start_time = 0;
3338 WG_TRACE("give up");
3339
3340 /*
3341 * If a new data packet comes, handshaking will be retried
3342 * and a new session would be established at that time,
3343 * however we don't want to send pending packets then.
3344 */
3345 wg_purge_pending_packets(wgp);
3346 return;
3347 }
3348
3349 wg_task_send_init_message(wg, wgp);
3350 }
3351
3352 static void
3353 wg_task_establish_session(struct wg_softc *wg, struct wg_peer *wgp)
3354 {
3355 struct wg_session *wgs;
3356
3357 KASSERT(mutex_owned(wgp->wgp_lock));
3358
3359 wgs = wgp->wgp_session_unstable;
3360 if (wgs->wgs_state != WGS_STATE_INIT_PASSIVE)
3361 /* XXX Can this happen? */
3362 return;
3363
3364 wgs->wgs_time_last_data_sent = 0;
3365 wgs->wgs_is_initiator = false;
3366
3367 /*
3368 * Session was already ready to receive data. Transition from
3369 * INIT_PASSIVE to ESTABLISHED just so we can swap the
3370 * sessions.
3371 *
3372 * atomic_store_relaxed because this doesn't affect the data rx
3373 * path, wg_handle_msg_data -- changing from INIT_PASSIVE to
3374 * ESTABLISHED makes no difference to the data rx path, and the
3375 * transition to INIT_PASSIVE with store-release already
3376 * published the state needed by the data rx path.
3377 */
3378 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_ESTABLISHED\n",
3379 wgs->wgs_local_index, wgs->wgs_remote_index);
3380 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
3381 WG_TRACE("WGS_STATE_ESTABLISHED");
3382
3383 /*
3384 * Session is ready to send data too now that we have received
3385 * the peer initiator's first data packet.
3386 *
3387 * Swap the sessions to publish the new one as the stable
3388 * session for the data tx path, wg_output.
3389 */
3390 wg_swap_sessions(wg, wgp);
3391 KASSERT(wgs == wgp->wgp_session_stable);
3392 }
3393
3394 static void
3395 wg_task_endpoint_changed(struct wg_softc *wg, struct wg_peer *wgp)
3396 {
3397
3398 WG_TRACE("WGP_TASK_ENDPOINT_CHANGED");
3399
3400 KASSERT(mutex_owned(wgp->wgp_lock));
3401
3402 if (atomic_load_relaxed(&wgp->wgp_endpoint_changing)) {
3403 pserialize_perform(wgp->wgp_psz);
3404 mutex_exit(wgp->wgp_lock);
3405 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref,
3406 wg_psref_class);
3407 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref,
3408 wg_psref_class);
3409 mutex_enter(wgp->wgp_lock);
3410 atomic_store_release(&wgp->wgp_endpoint_changing, 0);
3411 }
3412 }
3413
3414 static void
3415 wg_task_send_keepalive_message(struct wg_softc *wg, struct wg_peer *wgp)
3416 {
3417 struct wg_session *wgs;
3418
3419 WG_TRACE("WGP_TASK_SEND_KEEPALIVE_MESSAGE");
3420
3421 KASSERT(mutex_owned(wgp->wgp_lock));
3422
3423 wgs = wgp->wgp_session_stable;
3424 if (wgs->wgs_state != WGS_STATE_ESTABLISHED)
3425 return;
3426
3427 wg_send_keepalive_msg(wgp, wgs);
3428 }
3429
3430 static void
3431 wg_task_destroy_prev_session(struct wg_softc *wg, struct wg_peer *wgp)
3432 {
3433 struct wg_session *wgs;
3434 uint32_t age;
3435
3436 WG_TRACE("WGP_TASK_DESTROY_PREV_SESSION");
3437
3438 KASSERT(mutex_owned(wgp->wgp_lock));
3439
3440 /*
3441 * If theres's any previous unstable session, i.e., one that
3442 * was ESTABLISHED and is now DESTROYING, older than
3443 * reject-after-time, destroy it. Upcoming sessions are still
3444 * in INIT_ACTIVE or INIT_PASSIVE -- we don't touch those here.
3445 */
3446 wgs = wgp->wgp_session_unstable;
3447 KASSERT(wgs->wgs_state != WGS_STATE_ESTABLISHED);
3448 if (wgs->wgs_state == WGS_STATE_DESTROYING &&
3449 ((age = (time_uptime32 - wgs->wgs_time_established)) >=
3450 wg_reject_after_time)) {
3451 WG_DLOG("destroying past session %"PRIu32" sec old\n", age);
3452 wg_put_session_index(wg, wgs);
3453 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
3454 wgs->wgs_state);
3455 }
3456
3457 /*
3458 * If theres's any ESTABLISHED stable session older than
3459 * reject-after-time, destroy it. (The stable session can also
3460 * be in UNKNOWN state -- nothing to do in that case)
3461 */
3462 wgs = wgp->wgp_session_stable;
3463 KASSERT(wgs->wgs_state != WGS_STATE_INIT_ACTIVE);
3464 KASSERT(wgs->wgs_state != WGS_STATE_INIT_PASSIVE);
3465 KASSERT(wgs->wgs_state != WGS_STATE_DESTROYING);
3466 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3467 ((age = (time_uptime32 - wgs->wgs_time_established)) >=
3468 wg_reject_after_time)) {
3469 WG_DLOG("destroying current session %"PRIu32" sec old\n", age);
3470 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_DESTROYING);
3471 wg_put_session_index(wg, wgs);
3472 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
3473 wgs->wgs_state);
3474 }
3475
3476 /*
3477 * If there's no sessions left, no need to have the timer run
3478 * until the next time around -- halt it.
3479 *
3480 * It is only ever scheduled with wgp_lock held or in the
3481 * callout itself, and callout_halt prevents rescheudling
3482 * itself, so this never races with rescheduling.
3483 */
3484 if (wgp->wgp_session_unstable->wgs_state == WGS_STATE_UNKNOWN &&
3485 wgp->wgp_session_stable->wgs_state == WGS_STATE_UNKNOWN)
3486 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
3487 }
3488
3489 static void
3490 wg_peer_work(struct work *wk, void *cookie)
3491 {
3492 struct wg_peer *wgp = container_of(wk, struct wg_peer, wgp_work);
3493 struct wg_softc *wg = wgp->wgp_sc;
3494 unsigned int tasks;
3495
3496 mutex_enter(wgp->wgp_intr_lock);
3497 while ((tasks = wgp->wgp_tasks) != 0) {
3498 wgp->wgp_tasks = 0;
3499 mutex_exit(wgp->wgp_intr_lock);
3500
3501 mutex_enter(wgp->wgp_lock);
3502 if (ISSET(tasks, WGP_TASK_SEND_INIT_MESSAGE))
3503 wg_task_send_init_message(wg, wgp);
3504 if (ISSET(tasks, WGP_TASK_RETRY_HANDSHAKE))
3505 wg_task_retry_handshake(wg, wgp);
3506 if (ISSET(tasks, WGP_TASK_ESTABLISH_SESSION))
3507 wg_task_establish_session(wg, wgp);
3508 if (ISSET(tasks, WGP_TASK_ENDPOINT_CHANGED))
3509 wg_task_endpoint_changed(wg, wgp);
3510 if (ISSET(tasks, WGP_TASK_SEND_KEEPALIVE_MESSAGE))
3511 wg_task_send_keepalive_message(wg, wgp);
3512 if (ISSET(tasks, WGP_TASK_DESTROY_PREV_SESSION))
3513 wg_task_destroy_prev_session(wg, wgp);
3514 mutex_exit(wgp->wgp_lock);
3515
3516 mutex_enter(wgp->wgp_intr_lock);
3517 }
3518 mutex_exit(wgp->wgp_intr_lock);
3519 }
3520
3521 static void
3522 wg_job(struct threadpool_job *job)
3523 {
3524 struct wg_softc *wg = container_of(job, struct wg_softc, wg_job);
3525 int bound, upcalls;
3526
3527 mutex_enter(wg->wg_intr_lock);
3528 while ((upcalls = wg->wg_upcalls) != 0) {
3529 wg->wg_upcalls = 0;
3530 mutex_exit(wg->wg_intr_lock);
3531 bound = curlwp_bind();
3532 if (ISSET(upcalls, WG_UPCALL_INET))
3533 wg_receive_packets(wg, AF_INET);
3534 if (ISSET(upcalls, WG_UPCALL_INET6))
3535 wg_receive_packets(wg, AF_INET6);
3536 curlwp_bindx(bound);
3537 mutex_enter(wg->wg_intr_lock);
3538 }
3539 threadpool_job_done(job);
3540 mutex_exit(wg->wg_intr_lock);
3541 }
3542
3543 static int
3544 wg_bind_port(struct wg_softc *wg, const uint16_t port)
3545 {
3546 int error = 0;
3547 uint16_t old_port = wg->wg_listen_port;
3548
3549 if (port != 0 && old_port == port)
3550 return 0;
3551
3552 #ifdef INET
3553 struct sockaddr_in _sin, *sin = &_sin;
3554 sin->sin_len = sizeof(*sin);
3555 sin->sin_family = AF_INET;
3556 sin->sin_addr.s_addr = INADDR_ANY;
3557 sin->sin_port = htons(port);
3558
3559 error = sobind(wg->wg_so4, sintosa(sin), curlwp);
3560 if (error)
3561 return error;
3562 #endif
3563
3564 #ifdef INET6
3565 struct sockaddr_in6 _sin6, *sin6 = &_sin6;
3566 sin6->sin6_len = sizeof(*sin6);
3567 sin6->sin6_family = AF_INET6;
3568 sin6->sin6_addr = in6addr_any;
3569 sin6->sin6_port = htons(port);
3570
3571 error = sobind(wg->wg_so6, sin6tosa(sin6), curlwp);
3572 if (error)
3573 return error;
3574 #endif
3575
3576 wg->wg_listen_port = port;
3577
3578 return error;
3579 }
3580
3581 static void
3582 wg_so_upcall(struct socket *so, void *cookie, int events, int waitflag)
3583 {
3584 struct wg_softc *wg = cookie;
3585 int reason;
3586
3587 reason = (so->so_proto->pr_domain->dom_family == AF_INET) ?
3588 WG_UPCALL_INET :
3589 WG_UPCALL_INET6;
3590
3591 mutex_enter(wg->wg_intr_lock);
3592 wg->wg_upcalls |= reason;
3593 threadpool_schedule_job(wg->wg_threadpool, &wg->wg_job);
3594 mutex_exit(wg->wg_intr_lock);
3595 }
3596
3597 static int
3598 wg_overudp_cb(struct mbuf **mp, int offset, struct socket *so,
3599 struct sockaddr *src, void *arg)
3600 {
3601 struct wg_softc *wg = arg;
3602 struct wg_msg wgm;
3603 struct mbuf *m = *mp;
3604
3605 WG_TRACE("enter");
3606
3607 /* Verify the mbuf chain is long enough to have a wg msg header. */
3608 KASSERT(offset <= m_length(m));
3609 if (__predict_false(m_length(m) - offset < sizeof(struct wg_msg))) {
3610 /* drop on the floor */
3611 m_freem(m);
3612 return -1;
3613 }
3614
3615 /*
3616 * Copy the message header (32-bit message type) out -- we'll
3617 * worry about contiguity and alignment later.
3618 */
3619 m_copydata(m, offset, sizeof(struct wg_msg), &wgm);
3620 WG_DLOG("type=%d\n", le32toh(wgm.wgm_type));
3621
3622 /*
3623 * Handle DATA packets promptly as they arrive, if they are in
3624 * an active session. Other packets may require expensive
3625 * public-key crypto and are not as sensitive to latency, so
3626 * defer them to the worker thread.
3627 */
3628 switch (le32toh(wgm.wgm_type)) {
3629 case WG_MSG_TYPE_DATA:
3630 /* handle immediately */
3631 m_adj(m, offset);
3632 if (__predict_false(m->m_len < sizeof(struct wg_msg_data))) {
3633 m = m_pullup(m, sizeof(struct wg_msg_data));
3634 if (m == NULL)
3635 return -1;
3636 }
3637 wg_handle_msg_data(wg, m, src);
3638 *mp = NULL;
3639 return 1;
3640 case WG_MSG_TYPE_INIT:
3641 case WG_MSG_TYPE_RESP:
3642 case WG_MSG_TYPE_COOKIE:
3643 /* pass through to so_receive in wg_receive_packets */
3644 return 0;
3645 default:
3646 /* drop on the floor */
3647 m_freem(m);
3648 return -1;
3649 }
3650 }
3651
3652 static int
3653 wg_socreate(struct wg_softc *wg, int af, struct socket **sop)
3654 {
3655 int error;
3656 struct socket *so;
3657
3658 error = socreate(af, &so, SOCK_DGRAM, 0, curlwp, NULL);
3659 if (error != 0)
3660 return error;
3661
3662 solock(so);
3663 so->so_upcallarg = wg;
3664 so->so_upcall = wg_so_upcall;
3665 so->so_rcv.sb_flags |= SB_UPCALL;
3666 inpcb_register_overudp_cb(sotoinpcb(so), wg_overudp_cb, wg);
3667 sounlock(so);
3668
3669 *sop = so;
3670
3671 return 0;
3672 }
3673
3674 static bool
3675 wg_session_hit_limits(struct wg_session *wgs)
3676 {
3677
3678 /*
3679 * [W] 6.2: Transport Message Limits
3680 * "After REJECT-AFTER-MESSAGES transport data messages or after the
3681 * current secure session is REJECT-AFTER-TIME seconds old, whichever
3682 * comes first, WireGuard will refuse to send or receive any more
3683 * transport data messages using the current secure session, ..."
3684 */
3685 KASSERT(wgs->wgs_time_established != 0 || time_uptime > UINT32_MAX);
3686 if (time_uptime32 - wgs->wgs_time_established > wg_reject_after_time) {
3687 WG_DLOG("The session hits REJECT_AFTER_TIME\n");
3688 return true;
3689 } else if (wg_session_get_send_counter(wgs) >
3690 wg_reject_after_messages) {
3691 WG_DLOG("The session hits REJECT_AFTER_MESSAGES\n");
3692 return true;
3693 }
3694
3695 return false;
3696 }
3697
3698 static void
3699 wgintr(void *cookie)
3700 {
3701 struct wg_peer *wgp;
3702 struct wg_session *wgs;
3703 struct mbuf *m;
3704 struct psref psref;
3705
3706 while ((m = pktq_dequeue(wg_pktq)) != NULL) {
3707 wgp = M_GETCTX(m, struct wg_peer *);
3708 if ((wgs = wg_get_stable_session(wgp, &psref)) == NULL) {
3709 WG_TRACE("no stable session");
3710 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3711 goto next0;
3712 }
3713 if (__predict_false(wg_session_hit_limits(wgs))) {
3714 WG_TRACE("stable session hit limits");
3715 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3716 goto next1;
3717 }
3718 wg_send_data_msg(wgp, wgs, m);
3719 m = NULL; /* consumed */
3720 next1: wg_put_session(wgs, &psref);
3721 next0: m_freem(m);
3722 /* XXX Yield to avoid userland starvation? */
3723 }
3724 }
3725
3726 static void
3727 wg_purge_pending_packets(struct wg_peer *wgp)
3728 {
3729 struct mbuf *m;
3730
3731 m = atomic_swap_ptr(&wgp->wgp_pending, NULL);
3732 m_freem(m);
3733 #ifdef ALTQ
3734 wg_start(&wgp->wgp_sc->wg_if);
3735 #endif
3736 pktq_barrier(wg_pktq);
3737 }
3738
3739 static void
3740 wg_handshake_timeout_timer(void *arg)
3741 {
3742 struct wg_peer *wgp = arg;
3743
3744 WG_TRACE("enter");
3745
3746 wg_schedule_peer_task(wgp, WGP_TASK_RETRY_HANDSHAKE);
3747 }
3748
3749 static struct wg_peer *
3750 wg_alloc_peer(struct wg_softc *wg)
3751 {
3752 struct wg_peer *wgp;
3753
3754 wgp = kmem_zalloc(sizeof(*wgp), KM_SLEEP);
3755
3756 wgp->wgp_sc = wg;
3757 callout_init(&wgp->wgp_handshake_timeout_timer, CALLOUT_MPSAFE);
3758 callout_setfunc(&wgp->wgp_handshake_timeout_timer,
3759 wg_handshake_timeout_timer, wgp);
3760 callout_init(&wgp->wgp_session_dtor_timer, CALLOUT_MPSAFE);
3761 callout_setfunc(&wgp->wgp_session_dtor_timer,
3762 wg_session_dtor_timer, wgp);
3763 PSLIST_ENTRY_INIT(wgp, wgp_peerlist_entry);
3764 wgp->wgp_endpoint_changing = false;
3765 wgp->wgp_endpoint_available = false;
3766 wgp->wgp_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
3767 wgp->wgp_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
3768 wgp->wgp_psz = pserialize_create();
3769 psref_target_init(&wgp->wgp_psref, wg_psref_class);
3770
3771 wgp->wgp_endpoint = kmem_zalloc(sizeof(*wgp->wgp_endpoint), KM_SLEEP);
3772 wgp->wgp_endpoint0 = kmem_zalloc(sizeof(*wgp->wgp_endpoint0), KM_SLEEP);
3773 psref_target_init(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
3774 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
3775
3776 struct wg_session *wgs;
3777 wgp->wgp_session_stable =
3778 kmem_zalloc(sizeof(*wgp->wgp_session_stable), KM_SLEEP);
3779 wgp->wgp_session_unstable =
3780 kmem_zalloc(sizeof(*wgp->wgp_session_unstable), KM_SLEEP);
3781 wgs = wgp->wgp_session_stable;
3782 wgs->wgs_peer = wgp;
3783 wgs->wgs_state = WGS_STATE_UNKNOWN;
3784 psref_target_init(&wgs->wgs_psref, wg_psref_class);
3785 #ifndef __HAVE_ATOMIC64_LOADSTORE
3786 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
3787 #endif
3788 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
3789 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
3790
3791 wgs = wgp->wgp_session_unstable;
3792 wgs->wgs_peer = wgp;
3793 wgs->wgs_state = WGS_STATE_UNKNOWN;
3794 psref_target_init(&wgs->wgs_psref, wg_psref_class);
3795 #ifndef __HAVE_ATOMIC64_LOADSTORE
3796 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
3797 #endif
3798 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
3799 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
3800
3801 return wgp;
3802 }
3803
3804 static void
3805 wg_destroy_peer(struct wg_peer *wgp)
3806 {
3807 struct wg_session *wgs;
3808 struct wg_softc *wg = wgp->wgp_sc;
3809
3810 /* Prevent new packets from this peer on any source address. */
3811 rw_enter(wg->wg_rwlock, RW_WRITER);
3812 for (int i = 0; i < wgp->wgp_n_allowedips; i++) {
3813 struct wg_allowedip *wga = &wgp->wgp_allowedips[i];
3814 struct radix_node_head *rnh = wg_rnh(wg, wga->wga_family);
3815 struct radix_node *rn;
3816
3817 KASSERT(rnh != NULL);
3818 rn = rnh->rnh_deladdr(&wga->wga_sa_addr,
3819 &wga->wga_sa_mask, rnh);
3820 if (rn == NULL) {
3821 char addrstr[128];
3822 sockaddr_format(&wga->wga_sa_addr, addrstr,
3823 sizeof(addrstr));
3824 WGLOG(LOG_WARNING, "%s: Couldn't delete %s",
3825 if_name(&wg->wg_if), addrstr);
3826 }
3827 }
3828 rw_exit(wg->wg_rwlock);
3829
3830 /* Purge pending packets. */
3831 wg_purge_pending_packets(wgp);
3832
3833 /* Halt all packet processing and timeouts. */
3834 callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
3835 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
3836
3837 /* Wait for any queued work to complete. */
3838 workqueue_wait(wg_wq, &wgp->wgp_work);
3839
3840 wgs = wgp->wgp_session_unstable;
3841 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
3842 mutex_enter(wgp->wgp_lock);
3843 wg_destroy_session(wg, wgs);
3844 mutex_exit(wgp->wgp_lock);
3845 }
3846 mutex_destroy(&wgs->wgs_recvwin->lock);
3847 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
3848 #ifndef __HAVE_ATOMIC64_LOADSTORE
3849 mutex_destroy(&wgs->wgs_send_counter_lock);
3850 #endif
3851 kmem_free(wgs, sizeof(*wgs));
3852
3853 wgs = wgp->wgp_session_stable;
3854 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
3855 mutex_enter(wgp->wgp_lock);
3856 wg_destroy_session(wg, wgs);
3857 mutex_exit(wgp->wgp_lock);
3858 }
3859 mutex_destroy(&wgs->wgs_recvwin->lock);
3860 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
3861 #ifndef __HAVE_ATOMIC64_LOADSTORE
3862 mutex_destroy(&wgs->wgs_send_counter_lock);
3863 #endif
3864 kmem_free(wgs, sizeof(*wgs));
3865
3866 psref_target_destroy(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
3867 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
3868 kmem_free(wgp->wgp_endpoint, sizeof(*wgp->wgp_endpoint));
3869 kmem_free(wgp->wgp_endpoint0, sizeof(*wgp->wgp_endpoint0));
3870
3871 pserialize_destroy(wgp->wgp_psz);
3872 mutex_obj_free(wgp->wgp_intr_lock);
3873 mutex_obj_free(wgp->wgp_lock);
3874
3875 kmem_free(wgp, sizeof(*wgp));
3876 }
3877
3878 static void
3879 wg_destroy_all_peers(struct wg_softc *wg)
3880 {
3881 struct wg_peer *wgp, *wgp0 __diagused;
3882 void *garbage_byname, *garbage_bypubkey;
3883
3884 restart:
3885 garbage_byname = garbage_bypubkey = NULL;
3886 mutex_enter(wg->wg_lock);
3887 WG_PEER_WRITER_FOREACH(wgp, wg) {
3888 if (wgp->wgp_name[0]) {
3889 wgp0 = thmap_del(wg->wg_peers_byname, wgp->wgp_name,
3890 strlen(wgp->wgp_name));
3891 KASSERT(wgp0 == wgp);
3892 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
3893 }
3894 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
3895 sizeof(wgp->wgp_pubkey));
3896 KASSERT(wgp0 == wgp);
3897 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
3898 WG_PEER_WRITER_REMOVE(wgp);
3899 wg->wg_npeers--;
3900 mutex_enter(wgp->wgp_lock);
3901 pserialize_perform(wgp->wgp_psz);
3902 mutex_exit(wgp->wgp_lock);
3903 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
3904 break;
3905 }
3906 mutex_exit(wg->wg_lock);
3907
3908 if (wgp == NULL)
3909 return;
3910
3911 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
3912
3913 wg_destroy_peer(wgp);
3914 thmap_gc(wg->wg_peers_byname, garbage_byname);
3915 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
3916
3917 goto restart;
3918 }
3919
3920 static int
3921 wg_destroy_peer_name(struct wg_softc *wg, const char *name)
3922 {
3923 struct wg_peer *wgp, *wgp0 __diagused;
3924 void *garbage_byname, *garbage_bypubkey;
3925
3926 mutex_enter(wg->wg_lock);
3927 wgp = thmap_del(wg->wg_peers_byname, name, strlen(name));
3928 if (wgp != NULL) {
3929 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
3930 sizeof(wgp->wgp_pubkey));
3931 KASSERT(wgp0 == wgp);
3932 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
3933 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
3934 WG_PEER_WRITER_REMOVE(wgp);
3935 wg->wg_npeers--;
3936 if (wg->wg_npeers == 0)
3937 if_link_state_change(&wg->wg_if, LINK_STATE_DOWN);
3938 mutex_enter(wgp->wgp_lock);
3939 pserialize_perform(wgp->wgp_psz);
3940 mutex_exit(wgp->wgp_lock);
3941 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
3942 }
3943 mutex_exit(wg->wg_lock);
3944
3945 if (wgp == NULL)
3946 return ENOENT;
3947
3948 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
3949
3950 wg_destroy_peer(wgp);
3951 thmap_gc(wg->wg_peers_byname, garbage_byname);
3952 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
3953
3954 return 0;
3955 }
3956
3957 static int
3958 wg_if_attach(struct wg_softc *wg)
3959 {
3960
3961 wg->wg_if.if_addrlen = 0;
3962 wg->wg_if.if_mtu = WG_MTU;
3963 wg->wg_if.if_flags = IFF_MULTICAST;
3964 wg->wg_if.if_extflags = IFEF_MPSAFE;
3965 wg->wg_if.if_ioctl = wg_ioctl;
3966 wg->wg_if.if_output = wg_output;
3967 wg->wg_if.if_init = wg_init;
3968 #ifdef ALTQ
3969 wg->wg_if.if_start = wg_start;
3970 #endif
3971 wg->wg_if.if_stop = wg_stop;
3972 wg->wg_if.if_type = IFT_OTHER;
3973 wg->wg_if.if_dlt = DLT_NULL;
3974 wg->wg_if.if_softc = wg;
3975 #ifdef ALTQ
3976 IFQ_SET_READY(&wg->wg_if.if_snd);
3977 #endif
3978 if_initialize(&wg->wg_if);
3979
3980 wg->wg_if.if_link_state = LINK_STATE_DOWN;
3981 if_alloc_sadl(&wg->wg_if);
3982 if_register(&wg->wg_if);
3983
3984 bpf_attach(&wg->wg_if, DLT_NULL, sizeof(uint32_t));
3985
3986 return 0;
3987 }
3988
3989 static void
3990 wg_if_detach(struct wg_softc *wg)
3991 {
3992 struct ifnet *ifp = &wg->wg_if;
3993
3994 bpf_detach(ifp);
3995 if_detach(ifp);
3996 }
3997
3998 static int
3999 wg_clone_create(struct if_clone *ifc, int unit)
4000 {
4001 struct wg_softc *wg;
4002 int error;
4003
4004 wg_guarantee_initialized();
4005
4006 error = wg_count_inc();
4007 if (error)
4008 return error;
4009
4010 wg = kmem_zalloc(sizeof(*wg), KM_SLEEP);
4011
4012 if_initname(&wg->wg_if, ifc->ifc_name, unit);
4013
4014 PSLIST_INIT(&wg->wg_peers);
4015 wg->wg_peers_bypubkey = thmap_create(0, NULL, THMAP_NOCOPY);
4016 wg->wg_peers_byname = thmap_create(0, NULL, THMAP_NOCOPY);
4017 wg->wg_sessions_byindex = thmap_create(0, NULL, THMAP_NOCOPY);
4018 wg->wg_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
4019 wg->wg_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
4020 wg->wg_rwlock = rw_obj_alloc();
4021 threadpool_job_init(&wg->wg_job, wg_job, wg->wg_intr_lock,
4022 "%s", if_name(&wg->wg_if));
4023 wg->wg_ops = &wg_ops_rumpkernel;
4024
4025 error = threadpool_get(&wg->wg_threadpool, PRI_NONE);
4026 if (error)
4027 goto fail0;
4028
4029 #ifdef INET
4030 error = wg_socreate(wg, AF_INET, &wg->wg_so4);
4031 if (error)
4032 goto fail1;
4033 rn_inithead((void **)&wg->wg_rtable_ipv4,
4034 offsetof(struct sockaddr_in, sin_addr) * NBBY);
4035 #endif
4036 #ifdef INET6
4037 error = wg_socreate(wg, AF_INET6, &wg->wg_so6);
4038 if (error)
4039 goto fail2;
4040 rn_inithead((void **)&wg->wg_rtable_ipv6,
4041 offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
4042 #endif
4043
4044 error = wg_if_attach(wg);
4045 if (error)
4046 goto fail3;
4047
4048 return 0;
4049
4050 fail4: __unused
4051 wg_destroy_all_peers(wg);
4052 wg_if_detach(wg);
4053 fail3:
4054 #ifdef INET6
4055 solock(wg->wg_so6);
4056 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
4057 sounlock(wg->wg_so6);
4058 #endif
4059 #ifdef INET
4060 solock(wg->wg_so4);
4061 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
4062 sounlock(wg->wg_so4);
4063 #endif
4064 mutex_enter(wg->wg_intr_lock);
4065 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
4066 mutex_exit(wg->wg_intr_lock);
4067 #ifdef INET6
4068 if (wg->wg_rtable_ipv6 != NULL)
4069 free(wg->wg_rtable_ipv6, M_RTABLE);
4070 soclose(wg->wg_so6);
4071 fail2:
4072 #endif
4073 #ifdef INET
4074 if (wg->wg_rtable_ipv4 != NULL)
4075 free(wg->wg_rtable_ipv4, M_RTABLE);
4076 soclose(wg->wg_so4);
4077 fail1:
4078 #endif
4079 threadpool_put(wg->wg_threadpool, PRI_NONE);
4080 fail0: threadpool_job_destroy(&wg->wg_job);
4081 rw_obj_free(wg->wg_rwlock);
4082 mutex_obj_free(wg->wg_intr_lock);
4083 mutex_obj_free(wg->wg_lock);
4084 thmap_destroy(wg->wg_sessions_byindex);
4085 thmap_destroy(wg->wg_peers_byname);
4086 thmap_destroy(wg->wg_peers_bypubkey);
4087 PSLIST_DESTROY(&wg->wg_peers);
4088 kmem_free(wg, sizeof(*wg));
4089 wg_count_dec();
4090 return error;
4091 }
4092
4093 static int
4094 wg_clone_destroy(struct ifnet *ifp)
4095 {
4096 struct wg_softc *wg = container_of(ifp, struct wg_softc, wg_if);
4097
4098 #ifdef WG_RUMPKERNEL
4099 if (wg_user_mode(wg)) {
4100 rumpuser_wg_destroy(wg->wg_user);
4101 wg->wg_user = NULL;
4102 }
4103 #endif
4104
4105 wg_destroy_all_peers(wg);
4106 wg_if_detach(wg);
4107 #ifdef INET6
4108 solock(wg->wg_so6);
4109 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
4110 sounlock(wg->wg_so6);
4111 #endif
4112 #ifdef INET
4113 solock(wg->wg_so4);
4114 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
4115 sounlock(wg->wg_so4);
4116 #endif
4117 mutex_enter(wg->wg_intr_lock);
4118 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
4119 mutex_exit(wg->wg_intr_lock);
4120 #ifdef INET6
4121 if (wg->wg_rtable_ipv6 != NULL)
4122 free(wg->wg_rtable_ipv6, M_RTABLE);
4123 soclose(wg->wg_so6);
4124 #endif
4125 #ifdef INET
4126 if (wg->wg_rtable_ipv4 != NULL)
4127 free(wg->wg_rtable_ipv4, M_RTABLE);
4128 soclose(wg->wg_so4);
4129 #endif
4130 threadpool_put(wg->wg_threadpool, PRI_NONE);
4131 threadpool_job_destroy(&wg->wg_job);
4132 rw_obj_free(wg->wg_rwlock);
4133 mutex_obj_free(wg->wg_intr_lock);
4134 mutex_obj_free(wg->wg_lock);
4135 thmap_destroy(wg->wg_sessions_byindex);
4136 thmap_destroy(wg->wg_peers_byname);
4137 thmap_destroy(wg->wg_peers_bypubkey);
4138 PSLIST_DESTROY(&wg->wg_peers);
4139 kmem_free(wg, sizeof(*wg));
4140 wg_count_dec();
4141
4142 return 0;
4143 }
4144
4145 static struct wg_peer *
4146 wg_pick_peer_by_sa(struct wg_softc *wg, const struct sockaddr *sa,
4147 struct psref *psref)
4148 {
4149 struct radix_node_head *rnh;
4150 struct radix_node *rn;
4151 struct wg_peer *wgp = NULL;
4152 struct wg_allowedip *wga;
4153
4154 #ifdef WG_DEBUG_LOG
4155 char addrstr[128];
4156 sockaddr_format(sa, addrstr, sizeof(addrstr));
4157 WG_DLOG("sa=%s\n", addrstr);
4158 #endif
4159
4160 rw_enter(wg->wg_rwlock, RW_READER);
4161
4162 rnh = wg_rnh(wg, sa->sa_family);
4163 if (rnh == NULL)
4164 goto out;
4165
4166 rn = rnh->rnh_matchaddr(sa, rnh);
4167 if (rn == NULL || (rn->rn_flags & RNF_ROOT) != 0)
4168 goto out;
4169
4170 WG_TRACE("success");
4171
4172 wga = container_of(rn, struct wg_allowedip, wga_nodes[0]);
4173 wgp = wga->wga_peer;
4174 wg_get_peer(wgp, psref);
4175
4176 out:
4177 rw_exit(wg->wg_rwlock);
4178 return wgp;
4179 }
4180
4181 static void
4182 wg_fill_msg_data(struct wg_softc *wg, struct wg_peer *wgp,
4183 struct wg_session *wgs, struct wg_msg_data *wgmd)
4184 {
4185
4186 memset(wgmd, 0, sizeof(*wgmd));
4187 wgmd->wgmd_type = htole32(WG_MSG_TYPE_DATA);
4188 wgmd->wgmd_receiver = wgs->wgs_remote_index;
4189 /* [W] 5.4.6: msg.counter := Nm^send */
4190 /* [W] 5.4.6: Nm^send := Nm^send + 1 */
4191 wgmd->wgmd_counter = htole64(wg_session_inc_send_counter(wgs));
4192 WG_DLOG("counter=%"PRIu64"\n", le64toh(wgmd->wgmd_counter));
4193 }
4194
4195 static int
4196 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
4197 const struct rtentry *rt)
4198 {
4199 struct wg_softc *wg = ifp->if_softc;
4200 struct wg_peer *wgp = NULL;
4201 struct wg_session *wgs = NULL;
4202 struct psref wgp_psref, wgs_psref;
4203 int bound;
4204 int error;
4205
4206 bound = curlwp_bind();
4207
4208 /* TODO make the nest limit configurable via sysctl */
4209 error = if_tunnel_check_nesting(ifp, m, 1);
4210 if (error) {
4211 WGLOG(LOG_ERR,
4212 "%s: tunneling loop detected and packet dropped\n",
4213 if_name(&wg->wg_if));
4214 goto out0;
4215 }
4216
4217 #ifdef ALTQ
4218 bool altq = atomic_load_relaxed(&ifp->if_snd.altq_flags)
4219 & ALTQF_ENABLED;
4220 if (altq)
4221 IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
4222 #endif
4223
4224 bpf_mtap_af(ifp, dst->sa_family, m, BPF_D_OUT);
4225
4226 m->m_flags &= ~(M_BCAST|M_MCAST);
4227
4228 wgp = wg_pick_peer_by_sa(wg, dst, &wgp_psref);
4229 if (wgp == NULL) {
4230 WG_TRACE("peer not found");
4231 error = EHOSTUNREACH;
4232 goto out0;
4233 }
4234
4235 /* Clear checksum-offload flags. */
4236 m->m_pkthdr.csum_flags = 0;
4237 m->m_pkthdr.csum_data = 0;
4238
4239 /* Check whether there's an established session. */
4240 wgs = wg_get_stable_session(wgp, &wgs_psref);
4241 if (wgs == NULL) {
4242 /*
4243 * No established session. If we're the first to try
4244 * sending data, schedule a handshake and queue the
4245 * packet for when the handshake is done; otherwise
4246 * just drop the packet and let the ongoing handshake
4247 * attempt continue. We could queue more data packets
4248 * but it's not clear that's worthwhile.
4249 */
4250 if ((m = atomic_swap_ptr(&wgp->wgp_pending, m)) == NULL) {
4251 WG_TRACE("queued first packet; init handshake");
4252 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4253 } else {
4254 WG_TRACE("first packet already queued, dropping");
4255 }
4256 goto out1;
4257 }
4258
4259 /* There's an established session. Toss it in the queue. */
4260 #ifdef ALTQ
4261 if (altq) {
4262 mutex_enter(ifp->if_snd.ifq_lock);
4263 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
4264 M_SETCTX(m, wgp);
4265 ALTQ_ENQUEUE(&ifp->if_snd, m, error);
4266 m = NULL; /* consume */
4267 }
4268 mutex_exit(ifp->if_snd.ifq_lock);
4269 if (m == NULL) {
4270 wg_start(ifp);
4271 goto out2;
4272 }
4273 }
4274 #endif
4275 kpreempt_disable();
4276 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
4277 M_SETCTX(m, wgp);
4278 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
4279 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
4280 if_name(&wg->wg_if));
4281 error = ENOBUFS;
4282 goto out3;
4283 }
4284 m = NULL; /* consumed */
4285 error = 0;
4286 out3: kpreempt_enable();
4287
4288 #ifdef ALTQ
4289 out2:
4290 #endif
4291 wg_put_session(wgs, &wgs_psref);
4292 out1: wg_put_peer(wgp, &wgp_psref);
4293 out0: m_freem(m);
4294 curlwp_bindx(bound);
4295 return error;
4296 }
4297
4298 static int
4299 wg_send_udp(struct wg_peer *wgp, struct mbuf *m)
4300 {
4301 struct psref psref;
4302 struct wg_sockaddr *wgsa;
4303 int error;
4304 struct socket *so;
4305
4306 wgsa = wg_get_endpoint_sa(wgp, &psref);
4307 so = wg_get_so_by_peer(wgp, wgsa);
4308 solock(so);
4309 switch (wgsatosa(wgsa)->sa_family) {
4310 #ifdef INET
4311 case AF_INET:
4312 error = udp_send(so, m, wgsatosa(wgsa), NULL, curlwp);
4313 break;
4314 #endif
4315 #ifdef INET6
4316 case AF_INET6:
4317 error = udp6_output(sotoinpcb(so), m, wgsatosin6(wgsa),
4318 NULL, curlwp);
4319 break;
4320 #endif
4321 default:
4322 m_freem(m);
4323 error = EPFNOSUPPORT;
4324 }
4325 sounlock(so);
4326 wg_put_sa(wgp, wgsa, &psref);
4327
4328 return error;
4329 }
4330
4331 /* Inspired by pppoe_get_mbuf */
4332 static struct mbuf *
4333 wg_get_mbuf(size_t leading_len, size_t len)
4334 {
4335 struct mbuf *m;
4336
4337 KASSERT(leading_len <= MCLBYTES);
4338 KASSERT(len <= MCLBYTES - leading_len);
4339
4340 m = m_gethdr(M_DONTWAIT, MT_DATA);
4341 if (m == NULL)
4342 return NULL;
4343 if (len + leading_len > MHLEN) {
4344 m_clget(m, M_DONTWAIT);
4345 if ((m->m_flags & M_EXT) == 0) {
4346 m_free(m);
4347 return NULL;
4348 }
4349 }
4350 m->m_data += leading_len;
4351 m->m_pkthdr.len = m->m_len = len;
4352
4353 return m;
4354 }
4355
4356 static void
4357 wg_send_data_msg(struct wg_peer *wgp, struct wg_session *wgs, struct mbuf *m)
4358 {
4359 struct wg_softc *wg = wgp->wgp_sc;
4360 int error;
4361 size_t inner_len, padded_len, encrypted_len;
4362 char *padded_buf = NULL;
4363 size_t mlen;
4364 struct wg_msg_data *wgmd;
4365 bool free_padded_buf = false;
4366 struct mbuf *n;
4367 size_t leading_len = max_hdr + sizeof(struct udphdr);
4368
4369 mlen = m_length(m);
4370 inner_len = mlen;
4371 padded_len = roundup(mlen, 16);
4372 encrypted_len = padded_len + WG_AUTHTAG_LEN;
4373 WG_DLOG("inner=%zu, padded=%zu, encrypted_len=%zu\n",
4374 inner_len, padded_len, encrypted_len);
4375 if (mlen != 0) {
4376 bool success;
4377 success = m_ensure_contig(&m, padded_len);
4378 if (success) {
4379 padded_buf = mtod(m, char *);
4380 } else {
4381 padded_buf = kmem_intr_alloc(padded_len, KM_NOSLEEP);
4382 if (padded_buf == NULL) {
4383 error = ENOBUFS;
4384 goto out;
4385 }
4386 free_padded_buf = true;
4387 m_copydata(m, 0, mlen, padded_buf);
4388 }
4389 memset(padded_buf + mlen, 0, padded_len - inner_len);
4390 }
4391
4392 n = wg_get_mbuf(leading_len, sizeof(*wgmd) + encrypted_len);
4393 if (n == NULL) {
4394 error = ENOBUFS;
4395 goto out;
4396 }
4397 KASSERT(n->m_len >= sizeof(*wgmd));
4398 wgmd = mtod(n, struct wg_msg_data *);
4399 wg_fill_msg_data(wg, wgp, wgs, wgmd);
4400
4401 /* [W] 5.4.6: AEAD(Tm^send, Nm^send, P, e) */
4402 wg_algo_aead_enc((char *)wgmd + sizeof(*wgmd), encrypted_len,
4403 wgs->wgs_tkey_send, le64toh(wgmd->wgmd_counter),
4404 padded_buf, padded_len,
4405 NULL, 0);
4406
4407 error = wg->wg_ops->send_data_msg(wgp, n); /* consumes n */
4408 if (error) {
4409 WG_DLOG("send_data_msg failed, error=%d\n", error);
4410 goto out;
4411 }
4412
4413 /*
4414 * Packet was sent out -- count it in the interface statistics.
4415 */
4416 if_statadd(&wg->wg_if, if_obytes, mlen);
4417 if_statinc(&wg->wg_if, if_opackets);
4418
4419 /*
4420 * Record when we last sent data, for determining when we need
4421 * to send a passive keepalive.
4422 *
4423 * Other logic assumes that wgs_time_last_data_sent is zero iff
4424 * we have never sent data on this session. Early at boot, if
4425 * wg(4) starts operating within <1sec, or after 136 years of
4426 * uptime, we may observe time_uptime32 = 0. In that case,
4427 * pretend we observed 1 instead. That way, we correctly
4428 * indicate we have sent data on this session; the only logic
4429 * this might adversely affect is the keepalive timeout
4430 * detection, which might spuriously send a keepalive during
4431 * one second every 136 years. All of this is very silly, of
4432 * course, but the cost to guaranteeing wgs_time_last_data_sent
4433 * is nonzero is negligible here.
4434 */
4435 const uint32_t now = time_uptime32;
4436 atomic_store_relaxed(&wgs->wgs_time_last_data_sent, MAX(now, 1));
4437
4438 /*
4439 * Check rekey-after-time.
4440 */
4441 if (wgs->wgs_is_initiator &&
4442 now - wgs->wgs_time_established >= wg_rekey_after_time) {
4443 /*
4444 * [W] 6.2 Transport Message Limits
4445 * "if a peer is the initiator of a current secure
4446 * session, WireGuard will send a handshake initiation
4447 * message to begin a new secure session if, after
4448 * transmitting a transport data message, the current
4449 * secure session is REKEY-AFTER-TIME seconds old,"
4450 */
4451 WG_TRACE("rekey after time");
4452 atomic_store_relaxed(&wgs->wgs_force_rekey, true);
4453 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4454 }
4455
4456 /*
4457 * Check rekey-after-messages.
4458 */
4459 if (wg_session_get_send_counter(wgs) >= wg_rekey_after_messages) {
4460 /*
4461 * [W] 6.2 Transport Message Limits
4462 * "WireGuard will try to create a new session, by
4463 * sending a handshake initiation message (section
4464 * 5.4.2), after it has sent REKEY-AFTER-MESSAGES
4465 * transport data messages..."
4466 */
4467 WG_TRACE("rekey after messages");
4468 atomic_store_relaxed(&wgs->wgs_force_rekey, true);
4469 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4470 }
4471
4472 out: m_freem(m);
4473 if (free_padded_buf)
4474 kmem_intr_free(padded_buf, padded_len);
4475 }
4476
4477 static void
4478 wg_input(struct ifnet *ifp, struct mbuf *m, const int af)
4479 {
4480 pktqueue_t *pktq;
4481 size_t pktlen;
4482
4483 KASSERT(af == AF_INET || af == AF_INET6);
4484
4485 WG_TRACE("");
4486
4487 m_set_rcvif(m, ifp);
4488 pktlen = m->m_pkthdr.len;
4489
4490 bpf_mtap_af(ifp, af, m, BPF_D_IN);
4491
4492 switch (af) {
4493 #ifdef INET
4494 case AF_INET:
4495 pktq = ip_pktq;
4496 break;
4497 #endif
4498 #ifdef INET6
4499 case AF_INET6:
4500 pktq = ip6_pktq;
4501 break;
4502 #endif
4503 default:
4504 panic("invalid af=%d", af);
4505 }
4506
4507 kpreempt_disable();
4508 const u_int h = curcpu()->ci_index;
4509 if (__predict_true(pktq_enqueue(pktq, m, h))) {
4510 if_statadd(ifp, if_ibytes, pktlen);
4511 if_statinc(ifp, if_ipackets);
4512 } else {
4513 m_freem(m);
4514 }
4515 kpreempt_enable();
4516 }
4517
4518 static void
4519 wg_calc_pubkey(uint8_t pubkey[static WG_STATIC_KEY_LEN],
4520 const uint8_t privkey[static WG_STATIC_KEY_LEN])
4521 {
4522
4523 crypto_scalarmult_base(pubkey, privkey);
4524 }
4525
4526 static int
4527 wg_rtable_add_route(struct wg_softc *wg, struct wg_allowedip *wga)
4528 {
4529 struct radix_node_head *rnh;
4530 struct radix_node *rn;
4531 int error = 0;
4532
4533 rw_enter(wg->wg_rwlock, RW_WRITER);
4534 rnh = wg_rnh(wg, wga->wga_family);
4535 KASSERT(rnh != NULL);
4536 rn = rnh->rnh_addaddr(&wga->wga_sa_addr, &wga->wga_sa_mask, rnh,
4537 wga->wga_nodes);
4538 rw_exit(wg->wg_rwlock);
4539
4540 if (rn == NULL)
4541 error = EEXIST;
4542
4543 return error;
4544 }
4545
4546 static int
4547 wg_handle_prop_peer(struct wg_softc *wg, prop_dictionary_t peer,
4548 struct wg_peer **wgpp)
4549 {
4550 int error = 0;
4551 const void *pubkey;
4552 size_t pubkey_len;
4553 const void *psk;
4554 size_t psk_len;
4555 const char *name = NULL;
4556
4557 if (prop_dictionary_get_string(peer, "name", &name)) {
4558 if (strlen(name) > WG_PEER_NAME_MAXLEN) {
4559 error = EINVAL;
4560 goto out;
4561 }
4562 }
4563
4564 if (!prop_dictionary_get_data(peer, "public_key",
4565 &pubkey, &pubkey_len)) {
4566 error = EINVAL;
4567 goto out;
4568 }
4569 #ifdef WG_DEBUG_DUMP
4570 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4571 char *hex = gethexdump(pubkey, pubkey_len);
4572 log(LOG_DEBUG, "pubkey=%p, pubkey_len=%zu\n%s\n",
4573 pubkey, pubkey_len, hex);
4574 puthexdump(hex, pubkey, pubkey_len);
4575 }
4576 #endif
4577
4578 struct wg_peer *wgp = wg_alloc_peer(wg);
4579 memcpy(wgp->wgp_pubkey, pubkey, sizeof(wgp->wgp_pubkey));
4580 if (name != NULL)
4581 strncpy(wgp->wgp_name, name, sizeof(wgp->wgp_name));
4582
4583 if (prop_dictionary_get_data(peer, "preshared_key", &psk, &psk_len)) {
4584 if (psk_len != sizeof(wgp->wgp_psk)) {
4585 error = EINVAL;
4586 goto out;
4587 }
4588 memcpy(wgp->wgp_psk, psk, sizeof(wgp->wgp_psk));
4589 }
4590
4591 const void *addr;
4592 size_t addr_len;
4593 struct wg_sockaddr *wgsa = wgp->wgp_endpoint;
4594
4595 if (!prop_dictionary_get_data(peer, "endpoint", &addr, &addr_len))
4596 goto skip_endpoint;
4597 if (addr_len < sizeof(*wgsatosa(wgsa)) ||
4598 addr_len > sizeof(*wgsatoss(wgsa))) {
4599 error = EINVAL;
4600 goto out;
4601 }
4602 memcpy(wgsatoss(wgsa), addr, addr_len);
4603 switch (wgsa_family(wgsa)) {
4604 #ifdef INET
4605 case AF_INET:
4606 break;
4607 #endif
4608 #ifdef INET6
4609 case AF_INET6:
4610 break;
4611 #endif
4612 default:
4613 error = EPFNOSUPPORT;
4614 goto out;
4615 }
4616 if (addr_len != sockaddr_getsize_by_family(wgsa_family(wgsa))) {
4617 error = EINVAL;
4618 goto out;
4619 }
4620 {
4621 char addrstr[128];
4622 sockaddr_format(wgsatosa(wgsa), addrstr, sizeof(addrstr));
4623 WG_DLOG("addr=%s\n", addrstr);
4624 }
4625 wgp->wgp_endpoint_available = true;
4626
4627 prop_array_t allowedips;
4628 skip_endpoint:
4629 allowedips = prop_dictionary_get(peer, "allowedips");
4630 if (allowedips == NULL)
4631 goto skip;
4632
4633 prop_object_iterator_t _it = prop_array_iterator(allowedips);
4634 prop_dictionary_t prop_allowedip;
4635 int j = 0;
4636 while ((prop_allowedip = prop_object_iterator_next(_it)) != NULL) {
4637 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
4638
4639 if (!prop_dictionary_get_int(prop_allowedip, "family",
4640 &wga->wga_family))
4641 continue;
4642 if (!prop_dictionary_get_data(prop_allowedip, "ip",
4643 &addr, &addr_len))
4644 continue;
4645 if (!prop_dictionary_get_uint8(prop_allowedip, "cidr",
4646 &wga->wga_cidr))
4647 continue;
4648
4649 switch (wga->wga_family) {
4650 #ifdef INET
4651 case AF_INET: {
4652 struct sockaddr_in sin;
4653 char addrstr[128];
4654 struct in_addr mask;
4655 struct sockaddr_in sin_mask;
4656
4657 if (addr_len != sizeof(struct in_addr))
4658 return EINVAL;
4659 memcpy(&wga->wga_addr4, addr, addr_len);
4660
4661 sockaddr_in_init(&sin, (const struct in_addr *)addr,
4662 0);
4663 sockaddr_copy(&wga->wga_sa_addr,
4664 sizeof(sin), sintosa(&sin));
4665
4666 sockaddr_format(sintosa(&sin),
4667 addrstr, sizeof(addrstr));
4668 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4669
4670 in_len2mask(&mask, wga->wga_cidr);
4671 sockaddr_in_init(&sin_mask, &mask, 0);
4672 sockaddr_copy(&wga->wga_sa_mask,
4673 sizeof(sin_mask), sintosa(&sin_mask));
4674
4675 break;
4676 }
4677 #endif
4678 #ifdef INET6
4679 case AF_INET6: {
4680 struct sockaddr_in6 sin6;
4681 char addrstr[128];
4682 struct in6_addr mask;
4683 struct sockaddr_in6 sin6_mask;
4684
4685 if (addr_len != sizeof(struct in6_addr))
4686 return EINVAL;
4687 memcpy(&wga->wga_addr6, addr, addr_len);
4688
4689 sockaddr_in6_init(&sin6, (const struct in6_addr *)addr,
4690 0, 0, 0);
4691 sockaddr_copy(&wga->wga_sa_addr,
4692 sizeof(sin6), sin6tosa(&sin6));
4693
4694 sockaddr_format(sin6tosa(&sin6),
4695 addrstr, sizeof(addrstr));
4696 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4697
4698 in6_prefixlen2mask(&mask, wga->wga_cidr);
4699 sockaddr_in6_init(&sin6_mask, &mask, 0, 0, 0);
4700 sockaddr_copy(&wga->wga_sa_mask,
4701 sizeof(sin6_mask), sin6tosa(&sin6_mask));
4702
4703 break;
4704 }
4705 #endif
4706 default:
4707 error = EINVAL;
4708 goto out;
4709 }
4710 wga->wga_peer = wgp;
4711
4712 error = wg_rtable_add_route(wg, wga);
4713 if (error != 0)
4714 goto out;
4715
4716 j++;
4717 }
4718 wgp->wgp_n_allowedips = j;
4719 skip:
4720 *wgpp = wgp;
4721 out:
4722 return error;
4723 }
4724
4725 static int
4726 wg_alloc_prop_buf(char **_buf, struct ifdrv *ifd)
4727 {
4728 int error;
4729 char *buf;
4730
4731 WG_DLOG("buf=%p, len=%zu\n", ifd->ifd_data, ifd->ifd_len);
4732 if (ifd->ifd_len >= WG_MAX_PROPLEN)
4733 return E2BIG;
4734 buf = kmem_alloc(ifd->ifd_len + 1, KM_SLEEP);
4735 error = copyin(ifd->ifd_data, buf, ifd->ifd_len);
4736 if (error != 0)
4737 return error;
4738 buf[ifd->ifd_len] = '\0';
4739 #ifdef WG_DEBUG_DUMP
4740 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4741 log(LOG_DEBUG, "%.*s\n", (int)MIN(INT_MAX, ifd->ifd_len),
4742 (const char *)buf);
4743 }
4744 #endif
4745 *_buf = buf;
4746 return 0;
4747 }
4748
4749 static int
4750 wg_ioctl_set_private_key(struct wg_softc *wg, struct ifdrv *ifd)
4751 {
4752 int error;
4753 prop_dictionary_t prop_dict;
4754 char *buf = NULL;
4755 const void *privkey;
4756 size_t privkey_len;
4757
4758 error = wg_alloc_prop_buf(&buf, ifd);
4759 if (error != 0)
4760 return error;
4761 error = EINVAL;
4762 prop_dict = prop_dictionary_internalize(buf);
4763 if (prop_dict == NULL)
4764 goto out;
4765 if (!prop_dictionary_get_data(prop_dict, "private_key",
4766 &privkey, &privkey_len))
4767 goto out;
4768 #ifdef WG_DEBUG_DUMP
4769 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4770 char *hex = gethexdump(privkey, privkey_len);
4771 log(LOG_DEBUG, "privkey=%p, privkey_len=%zu\n%s\n",
4772 privkey, privkey_len, hex);
4773 puthexdump(hex, privkey, privkey_len);
4774 }
4775 #endif
4776 if (privkey_len != WG_STATIC_KEY_LEN)
4777 goto out;
4778 memcpy(wg->wg_privkey, privkey, WG_STATIC_KEY_LEN);
4779 wg_calc_pubkey(wg->wg_pubkey, wg->wg_privkey);
4780 error = 0;
4781
4782 out:
4783 kmem_free(buf, ifd->ifd_len + 1);
4784 return error;
4785 }
4786
4787 static int
4788 wg_ioctl_set_listen_port(struct wg_softc *wg, struct ifdrv *ifd)
4789 {
4790 int error;
4791 prop_dictionary_t prop_dict;
4792 char *buf = NULL;
4793 uint16_t port;
4794
4795 error = wg_alloc_prop_buf(&buf, ifd);
4796 if (error != 0)
4797 return error;
4798 error = EINVAL;
4799 prop_dict = prop_dictionary_internalize(buf);
4800 if (prop_dict == NULL)
4801 goto out;
4802 if (!prop_dictionary_get_uint16(prop_dict, "listen_port", &port))
4803 goto out;
4804
4805 error = wg->wg_ops->bind_port(wg, (uint16_t)port);
4806
4807 out:
4808 kmem_free(buf, ifd->ifd_len + 1);
4809 return error;
4810 }
4811
4812 static int
4813 wg_ioctl_add_peer(struct wg_softc *wg, struct ifdrv *ifd)
4814 {
4815 int error;
4816 prop_dictionary_t prop_dict;
4817 char *buf = NULL;
4818 struct wg_peer *wgp = NULL, *wgp0 __diagused;
4819
4820 error = wg_alloc_prop_buf(&buf, ifd);
4821 if (error != 0)
4822 return error;
4823 error = EINVAL;
4824 prop_dict = prop_dictionary_internalize(buf);
4825 if (prop_dict == NULL)
4826 goto out;
4827
4828 error = wg_handle_prop_peer(wg, prop_dict, &wgp);
4829 if (error != 0)
4830 goto out;
4831
4832 mutex_enter(wg->wg_lock);
4833 if (thmap_get(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4834 sizeof(wgp->wgp_pubkey)) != NULL ||
4835 (wgp->wgp_name[0] &&
4836 thmap_get(wg->wg_peers_byname, wgp->wgp_name,
4837 strlen(wgp->wgp_name)) != NULL)) {
4838 mutex_exit(wg->wg_lock);
4839 wg_destroy_peer(wgp);
4840 error = EEXIST;
4841 goto out;
4842 }
4843 wgp0 = thmap_put(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4844 sizeof(wgp->wgp_pubkey), wgp);
4845 KASSERT(wgp0 == wgp);
4846 if (wgp->wgp_name[0]) {
4847 wgp0 = thmap_put(wg->wg_peers_byname, wgp->wgp_name,
4848 strlen(wgp->wgp_name), wgp);
4849 KASSERT(wgp0 == wgp);
4850 }
4851 WG_PEER_WRITER_INSERT_HEAD(wgp, wg);
4852 wg->wg_npeers++;
4853 mutex_exit(wg->wg_lock);
4854
4855 if_link_state_change(&wg->wg_if, LINK_STATE_UP);
4856
4857 out:
4858 kmem_free(buf, ifd->ifd_len + 1);
4859 return error;
4860 }
4861
4862 static int
4863 wg_ioctl_delete_peer(struct wg_softc *wg, struct ifdrv *ifd)
4864 {
4865 int error;
4866 prop_dictionary_t prop_dict;
4867 char *buf = NULL;
4868 const char *name;
4869
4870 error = wg_alloc_prop_buf(&buf, ifd);
4871 if (error != 0)
4872 return error;
4873 error = EINVAL;
4874 prop_dict = prop_dictionary_internalize(buf);
4875 if (prop_dict == NULL)
4876 goto out;
4877
4878 if (!prop_dictionary_get_string(prop_dict, "name", &name))
4879 goto out;
4880 if (strlen(name) > WG_PEER_NAME_MAXLEN)
4881 goto out;
4882
4883 error = wg_destroy_peer_name(wg, name);
4884 out:
4885 kmem_free(buf, ifd->ifd_len + 1);
4886 return error;
4887 }
4888
4889 static bool
4890 wg_is_authorized(struct wg_softc *wg, u_long cmd)
4891 {
4892 int au = cmd == SIOCGDRVSPEC ?
4893 KAUTH_REQ_NETWORK_INTERFACE_WG_GETPRIV :
4894 KAUTH_REQ_NETWORK_INTERFACE_WG_SETPRIV;
4895 return kauth_authorize_network(kauth_cred_get(),
4896 KAUTH_NETWORK_INTERFACE_WG, au, &wg->wg_if,
4897 (void *)cmd, NULL) == 0;
4898 }
4899
4900 static int
4901 wg_ioctl_get(struct wg_softc *wg, struct ifdrv *ifd)
4902 {
4903 int error = ENOMEM;
4904 prop_dictionary_t prop_dict;
4905 prop_array_t peers = NULL;
4906 char *buf;
4907 struct wg_peer *wgp;
4908 int s, i;
4909
4910 prop_dict = prop_dictionary_create();
4911 if (prop_dict == NULL)
4912 goto error;
4913
4914 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
4915 if (!prop_dictionary_set_data(prop_dict, "private_key",
4916 wg->wg_privkey, WG_STATIC_KEY_LEN))
4917 goto error;
4918 }
4919
4920 if (wg->wg_listen_port != 0) {
4921 if (!prop_dictionary_set_uint16(prop_dict, "listen_port",
4922 wg->wg_listen_port))
4923 goto error;
4924 }
4925
4926 if (wg->wg_npeers == 0)
4927 goto skip_peers;
4928
4929 peers = prop_array_create();
4930 if (peers == NULL)
4931 goto error;
4932
4933 s = pserialize_read_enter();
4934 i = 0;
4935 WG_PEER_READER_FOREACH(wgp, wg) {
4936 struct wg_sockaddr *wgsa;
4937 struct psref wgp_psref, wgsa_psref;
4938 prop_dictionary_t prop_peer;
4939
4940 wg_get_peer(wgp, &wgp_psref);
4941 pserialize_read_exit(s);
4942
4943 prop_peer = prop_dictionary_create();
4944 if (prop_peer == NULL)
4945 goto next;
4946
4947 if (strlen(wgp->wgp_name) > 0) {
4948 if (!prop_dictionary_set_string(prop_peer, "name",
4949 wgp->wgp_name))
4950 goto next;
4951 }
4952
4953 if (!prop_dictionary_set_data(prop_peer, "public_key",
4954 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey)))
4955 goto next;
4956
4957 uint8_t psk_zero[WG_PRESHARED_KEY_LEN] = {0};
4958 if (!consttime_memequal(wgp->wgp_psk, psk_zero,
4959 sizeof(wgp->wgp_psk))) {
4960 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
4961 if (!prop_dictionary_set_data(prop_peer,
4962 "preshared_key",
4963 wgp->wgp_psk, sizeof(wgp->wgp_psk)))
4964 goto next;
4965 }
4966 }
4967
4968 wgsa = wg_get_endpoint_sa(wgp, &wgsa_psref);
4969 CTASSERT(AF_UNSPEC == 0);
4970 if (wgsa_family(wgsa) != 0 /*AF_UNSPEC*/ &&
4971 !prop_dictionary_set_data(prop_peer, "endpoint",
4972 wgsatoss(wgsa),
4973 sockaddr_getsize_by_family(wgsa_family(wgsa)))) {
4974 wg_put_sa(wgp, wgsa, &wgsa_psref);
4975 goto next;
4976 }
4977 wg_put_sa(wgp, wgsa, &wgsa_psref);
4978
4979 const struct timespec *t = &wgp->wgp_last_handshake_time;
4980
4981 if (!prop_dictionary_set_uint64(prop_peer,
4982 "last_handshake_time_sec", (uint64_t)t->tv_sec))
4983 goto next;
4984 if (!prop_dictionary_set_uint32(prop_peer,
4985 "last_handshake_time_nsec", (uint32_t)t->tv_nsec))
4986 goto next;
4987
4988 if (wgp->wgp_n_allowedips == 0)
4989 goto skip_allowedips;
4990
4991 prop_array_t allowedips = prop_array_create();
4992 if (allowedips == NULL)
4993 goto next;
4994 for (int j = 0; j < wgp->wgp_n_allowedips; j++) {
4995 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
4996 prop_dictionary_t prop_allowedip;
4997
4998 prop_allowedip = prop_dictionary_create();
4999 if (prop_allowedip == NULL)
5000 break;
5001
5002 if (!prop_dictionary_set_int(prop_allowedip, "family",
5003 wga->wga_family))
5004 goto _next;
5005 if (!prop_dictionary_set_uint8(prop_allowedip, "cidr",
5006 wga->wga_cidr))
5007 goto _next;
5008
5009 switch (wga->wga_family) {
5010 #ifdef INET
5011 case AF_INET:
5012 if (!prop_dictionary_set_data(prop_allowedip,
5013 "ip", &wga->wga_addr4,
5014 sizeof(wga->wga_addr4)))
5015 goto _next;
5016 break;
5017 #endif
5018 #ifdef INET6
5019 case AF_INET6:
5020 if (!prop_dictionary_set_data(prop_allowedip,
5021 "ip", &wga->wga_addr6,
5022 sizeof(wga->wga_addr6)))
5023 goto _next;
5024 break;
5025 #endif
5026 default:
5027 panic("invalid af=%d", wga->wga_family);
5028 }
5029 prop_array_set(allowedips, j, prop_allowedip);
5030 _next:
5031 prop_object_release(prop_allowedip);
5032 }
5033 prop_dictionary_set(prop_peer, "allowedips", allowedips);
5034 prop_object_release(allowedips);
5035
5036 skip_allowedips:
5037
5038 prop_array_set(peers, i, prop_peer);
5039 next:
5040 if (prop_peer)
5041 prop_object_release(prop_peer);
5042 i++;
5043
5044 s = pserialize_read_enter();
5045 wg_put_peer(wgp, &wgp_psref);
5046 }
5047 pserialize_read_exit(s);
5048
5049 prop_dictionary_set(prop_dict, "peers", peers);
5050 prop_object_release(peers);
5051 peers = NULL;
5052
5053 skip_peers:
5054 buf = prop_dictionary_externalize(prop_dict);
5055 if (buf == NULL)
5056 goto error;
5057 if (ifd->ifd_len < (strlen(buf) + 1)) {
5058 error = EINVAL;
5059 goto error;
5060 }
5061 error = copyout(buf, ifd->ifd_data, strlen(buf) + 1);
5062
5063 free(buf, 0);
5064 error:
5065 if (peers != NULL)
5066 prop_object_release(peers);
5067 if (prop_dict != NULL)
5068 prop_object_release(prop_dict);
5069
5070 return error;
5071 }
5072
5073 static int
5074 wg_ioctl(struct ifnet *ifp, u_long cmd, void *data)
5075 {
5076 struct wg_softc *wg = ifp->if_softc;
5077 struct ifreq *ifr = data;
5078 struct ifaddr *ifa = data;
5079 struct ifdrv *ifd = data;
5080 int error = 0;
5081
5082 switch (cmd) {
5083 case SIOCINITIFADDR:
5084 if (ifa->ifa_addr->sa_family != AF_LINK &&
5085 (ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
5086 (IFF_UP | IFF_RUNNING)) {
5087 ifp->if_flags |= IFF_UP;
5088 error = if_init(ifp);
5089 }
5090 return error;
5091 case SIOCADDMULTI:
5092 case SIOCDELMULTI:
5093 switch (ifr->ifr_addr.sa_family) {
5094 #ifdef INET
5095 case AF_INET: /* IP supports Multicast */
5096 break;
5097 #endif
5098 #ifdef INET6
5099 case AF_INET6: /* IP6 supports Multicast */
5100 break;
5101 #endif
5102 default: /* Other protocols doesn't support Multicast */
5103 error = EAFNOSUPPORT;
5104 break;
5105 }
5106 return error;
5107 case SIOCSDRVSPEC:
5108 if (!wg_is_authorized(wg, cmd)) {
5109 return EPERM;
5110 }
5111 switch (ifd->ifd_cmd) {
5112 case WG_IOCTL_SET_PRIVATE_KEY:
5113 error = wg_ioctl_set_private_key(wg, ifd);
5114 break;
5115 case WG_IOCTL_SET_LISTEN_PORT:
5116 error = wg_ioctl_set_listen_port(wg, ifd);
5117 break;
5118 case WG_IOCTL_ADD_PEER:
5119 error = wg_ioctl_add_peer(wg, ifd);
5120 break;
5121 case WG_IOCTL_DELETE_PEER:
5122 error = wg_ioctl_delete_peer(wg, ifd);
5123 break;
5124 default:
5125 error = EINVAL;
5126 break;
5127 }
5128 return error;
5129 case SIOCGDRVSPEC:
5130 return wg_ioctl_get(wg, ifd);
5131 case SIOCSIFFLAGS:
5132 if ((error = ifioctl_common(ifp, cmd, data)) != 0)
5133 break;
5134 switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
5135 case IFF_RUNNING:
5136 /*
5137 * If interface is marked down and it is running,
5138 * then stop and disable it.
5139 */
5140 if_stop(ifp, 1);
5141 break;
5142 case IFF_UP:
5143 /*
5144 * If interface is marked up and it is stopped, then
5145 * start it.
5146 */
5147 error = if_init(ifp);
5148 break;
5149 default:
5150 break;
5151 }
5152 return error;
5153 #ifdef WG_RUMPKERNEL
5154 case SIOCSLINKSTR:
5155 error = wg_ioctl_linkstr(wg, ifd);
5156 if (error)
5157 return error;
5158 wg->wg_ops = &wg_ops_rumpuser;
5159 return 0;
5160 #endif
5161 default:
5162 break;
5163 }
5164
5165 error = ifioctl_common(ifp, cmd, data);
5166
5167 #ifdef WG_RUMPKERNEL
5168 if (!wg_user_mode(wg))
5169 return error;
5170
5171 /* Do the same to the corresponding tun device on the host */
5172 /*
5173 * XXX Actually the command has not been handled yet. It
5174 * will be handled via pr_ioctl form doifioctl later.
5175 */
5176 switch (cmd) {
5177 #ifdef INET
5178 case SIOCAIFADDR:
5179 case SIOCDIFADDR: {
5180 struct in_aliasreq _ifra = *(const struct in_aliasreq *)data;
5181 struct in_aliasreq *ifra = &_ifra;
5182 KASSERT(error == ENOTTY);
5183 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5184 IFNAMSIZ);
5185 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET);
5186 if (error == 0)
5187 error = ENOTTY;
5188 break;
5189 }
5190 #endif
5191 #ifdef INET6
5192 case SIOCAIFADDR_IN6:
5193 case SIOCDIFADDR_IN6: {
5194 struct in6_aliasreq _ifra = *(const struct in6_aliasreq *)data;
5195 struct in6_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_INET6);
5200 if (error == 0)
5201 error = ENOTTY;
5202 break;
5203 }
5204 #endif
5205 default:
5206 break;
5207 }
5208 #endif /* WG_RUMPKERNEL */
5209
5210 return error;
5211 }
5212
5213 static int
5214 wg_init(struct ifnet *ifp)
5215 {
5216
5217 ifp->if_flags |= IFF_RUNNING;
5218
5219 /* TODO flush pending packets. */
5220 return 0;
5221 }
5222
5223 #ifdef ALTQ
5224 static void
5225 wg_start(struct ifnet *ifp)
5226 {
5227 struct mbuf *m;
5228
5229 for (;;) {
5230 IFQ_DEQUEUE(&ifp->if_snd, m);
5231 if (m == NULL)
5232 break;
5233
5234 kpreempt_disable();
5235 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
5236 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
5237 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
5238 if_name(ifp));
5239 m_freem(m);
5240 }
5241 kpreempt_enable();
5242 }
5243 }
5244 #endif
5245
5246 static void
5247 wg_stop(struct ifnet *ifp, int disable)
5248 {
5249
5250 KASSERT((ifp->if_flags & IFF_RUNNING) != 0);
5251 ifp->if_flags &= ~IFF_RUNNING;
5252
5253 /* Need to do something? */
5254 }
5255
5256 #ifdef WG_DEBUG_PARAMS
5257 SYSCTL_SETUP(sysctl_net_wg_setup, "sysctl net.wg setup")
5258 {
5259 const struct sysctlnode *node = NULL;
5260
5261 sysctl_createv(clog, 0, NULL, &node,
5262 CTLFLAG_PERMANENT,
5263 CTLTYPE_NODE, "wg",
5264 SYSCTL_DESCR("wg(4)"),
5265 NULL, 0, NULL, 0,
5266 CTL_NET, CTL_CREATE, CTL_EOL);
5267 sysctl_createv(clog, 0, &node, NULL,
5268 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5269 CTLTYPE_QUAD, "rekey_after_messages",
5270 SYSCTL_DESCR("session liftime by messages"),
5271 NULL, 0, &wg_rekey_after_messages, 0, CTL_CREATE, CTL_EOL);
5272 sysctl_createv(clog, 0, &node, NULL,
5273 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5274 CTLTYPE_INT, "rekey_after_time",
5275 SYSCTL_DESCR("session liftime"),
5276 NULL, 0, &wg_rekey_after_time, 0, CTL_CREATE, CTL_EOL);
5277 sysctl_createv(clog, 0, &node, NULL,
5278 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5279 CTLTYPE_INT, "rekey_timeout",
5280 SYSCTL_DESCR("session handshake retry time"),
5281 NULL, 0, &wg_rekey_timeout, 0, CTL_CREATE, CTL_EOL);
5282 sysctl_createv(clog, 0, &node, NULL,
5283 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5284 CTLTYPE_INT, "rekey_attempt_time",
5285 SYSCTL_DESCR("session handshake timeout"),
5286 NULL, 0, &wg_rekey_attempt_time, 0, CTL_CREATE, CTL_EOL);
5287 sysctl_createv(clog, 0, &node, NULL,
5288 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5289 CTLTYPE_INT, "keepalive_timeout",
5290 SYSCTL_DESCR("keepalive timeout"),
5291 NULL, 0, &wg_keepalive_timeout, 0, CTL_CREATE, CTL_EOL);
5292 sysctl_createv(clog, 0, &node, NULL,
5293 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5294 CTLTYPE_BOOL, "force_underload",
5295 SYSCTL_DESCR("force to detemine under load"),
5296 NULL, 0, &wg_force_underload, 0, CTL_CREATE, CTL_EOL);
5297 sysctl_createv(clog, 0, &node, NULL,
5298 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5299 CTLTYPE_INT, "debug",
5300 SYSCTL_DESCR("set debug flags 1=log 2=trace 4=dump 8=packet"),
5301 NULL, 0, &wg_debug, 0, CTL_CREATE, CTL_EOL);
5302 }
5303 #endif
5304
5305 #ifdef WG_RUMPKERNEL
5306 static bool
5307 wg_user_mode(struct wg_softc *wg)
5308 {
5309
5310 return wg->wg_user != NULL;
5311 }
5312
5313 static int
5314 wg_ioctl_linkstr(struct wg_softc *wg, struct ifdrv *ifd)
5315 {
5316 struct ifnet *ifp = &wg->wg_if;
5317 int error;
5318
5319 if (ifp->if_flags & IFF_UP)
5320 return EBUSY;
5321
5322 if (ifd->ifd_cmd == IFLINKSTR_UNSET) {
5323 /* XXX do nothing */
5324 return 0;
5325 } else if (ifd->ifd_cmd != 0) {
5326 return EINVAL;
5327 } else if (wg->wg_user != NULL) {
5328 return EBUSY;
5329 }
5330
5331 /* Assume \0 included */
5332 if (ifd->ifd_len > IFNAMSIZ) {
5333 return E2BIG;
5334 } else if (ifd->ifd_len < 1) {
5335 return EINVAL;
5336 }
5337
5338 char tun_name[IFNAMSIZ];
5339 error = copyinstr(ifd->ifd_data, tun_name, ifd->ifd_len, NULL);
5340 if (error != 0)
5341 return error;
5342
5343 if (strncmp(tun_name, "tun", 3) != 0)
5344 return EINVAL;
5345
5346 error = rumpuser_wg_create(tun_name, wg, &wg->wg_user);
5347
5348 return error;
5349 }
5350
5351 static int
5352 wg_send_user(struct wg_peer *wgp, struct mbuf *m)
5353 {
5354 int error;
5355 struct psref psref;
5356 struct wg_sockaddr *wgsa;
5357 struct wg_softc *wg = wgp->wgp_sc;
5358 struct iovec iov[1];
5359
5360 wgsa = wg_get_endpoint_sa(wgp, &psref);
5361
5362 iov[0].iov_base = mtod(m, void *);
5363 iov[0].iov_len = m->m_len;
5364
5365 /* Send messages to a peer via an ordinary socket. */
5366 error = rumpuser_wg_send_peer(wg->wg_user, wgsatosa(wgsa), iov, 1);
5367
5368 wg_put_sa(wgp, wgsa, &psref);
5369
5370 m_freem(m);
5371
5372 return error;
5373 }
5374
5375 static void
5376 wg_input_user(struct ifnet *ifp, struct mbuf *m, const int af)
5377 {
5378 struct wg_softc *wg = ifp->if_softc;
5379 struct iovec iov[2];
5380 struct sockaddr_storage ss;
5381
5382 KASSERT(af == AF_INET || af == AF_INET6);
5383
5384 WG_TRACE("");
5385
5386 switch (af) {
5387 #ifdef INET
5388 case AF_INET: {
5389 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
5390 struct ip *ip;
5391
5392 KASSERT(m->m_len >= sizeof(struct ip));
5393 ip = mtod(m, struct ip *);
5394 sockaddr_in_init(sin, &ip->ip_dst, 0);
5395 break;
5396 }
5397 #endif
5398 #ifdef INET6
5399 case AF_INET6: {
5400 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
5401 struct ip6_hdr *ip6;
5402
5403 KASSERT(m->m_len >= sizeof(struct ip6_hdr));
5404 ip6 = mtod(m, struct ip6_hdr *);
5405 sockaddr_in6_init(sin6, &ip6->ip6_dst, 0, 0, 0);
5406 break;
5407 }
5408 #endif
5409 default:
5410 goto out;
5411 }
5412
5413 iov[0].iov_base = &ss;
5414 iov[0].iov_len = ss.ss_len;
5415 iov[1].iov_base = mtod(m, void *);
5416 iov[1].iov_len = m->m_len;
5417
5418 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5419
5420 /* Send decrypted packets to users via a tun. */
5421 rumpuser_wg_send_user(wg->wg_user, iov, 2);
5422
5423 out: m_freem(m);
5424 }
5425
5426 static int
5427 wg_bind_port_user(struct wg_softc *wg, const uint16_t port)
5428 {
5429 int error;
5430 uint16_t old_port = wg->wg_listen_port;
5431
5432 if (port != 0 && old_port == port)
5433 return 0;
5434
5435 error = rumpuser_wg_sock_bind(wg->wg_user, port);
5436 if (error)
5437 return error;
5438
5439 wg->wg_listen_port = port;
5440 return 0;
5441 }
5442
5443 /*
5444 * Receive user packets.
5445 */
5446 void
5447 rumpkern_wg_recv_user(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
5448 {
5449 struct ifnet *ifp = &wg->wg_if;
5450 struct mbuf *m;
5451 const struct sockaddr *dst;
5452 int error;
5453
5454 WG_TRACE("");
5455
5456 dst = iov[0].iov_base;
5457
5458 m = m_gethdr(M_DONTWAIT, MT_DATA);
5459 if (m == NULL)
5460 return;
5461 m->m_len = m->m_pkthdr.len = 0;
5462 m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
5463
5464 WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
5465 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5466
5467 error = wg_output(ifp, m, dst, NULL); /* consumes m */
5468 if (error)
5469 WG_DLOG("wg_output failed, error=%d\n", error);
5470 }
5471
5472 /*
5473 * Receive packets from a peer.
5474 */
5475 void
5476 rumpkern_wg_recv_peer(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
5477 {
5478 struct mbuf *m;
5479 const struct sockaddr *src;
5480 int bound;
5481
5482 WG_TRACE("");
5483
5484 src = iov[0].iov_base;
5485
5486 m = m_gethdr(M_DONTWAIT, MT_DATA);
5487 if (m == NULL)
5488 return;
5489 m->m_len = m->m_pkthdr.len = 0;
5490 m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
5491
5492 WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
5493 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5494
5495 bound = curlwp_bind();
5496 wg_handle_packet(wg, m, src);
5497 curlwp_bindx(bound);
5498 }
5499 #endif /* WG_RUMPKERNEL */
5500
5501 /*
5502 * Module infrastructure
5503 */
5504 #include "if_module.h"
5505
5506 IF_MODULE(MODULE_CLASS_DRIVER, wg, "sodium,blake2s")
5507