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