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