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