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