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