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