if_wg.c revision 1.99 1 /* $NetBSD: if_wg.c,v 1.99 2024/07/28 14:39:35 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.99 2024/07/28 14:39:35 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_COOKIESECRET_LEN 32
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 *volatile 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_handshake_timeout_timer;
616 callout_t wgp_session_dtor_timer;
617
618 time_t wgp_handshake_start_time;
619
620 volatile unsigned wgp_force_rekey;
621
622 int wgp_n_allowedips;
623 struct wg_allowedip wgp_allowedips[WG_ALLOWEDIPS];
624
625 time_t wgp_latest_cookie_time;
626 uint8_t wgp_latest_cookie[WG_COOKIE_LEN];
627 uint8_t wgp_last_sent_mac1[WG_MAC_LEN];
628 bool wgp_last_sent_mac1_valid;
629 uint8_t wgp_last_sent_cookie[WG_COOKIE_LEN];
630 bool wgp_last_sent_cookie_valid;
631
632 time_t wgp_last_msg_received_time[WG_MSG_TYPE_MAX];
633
634 time_t wgp_last_cookiesecret_time;
635 uint8_t wgp_cookiesecret[WG_COOKIESECRET_LEN];
636
637 struct wg_ppsratecheck wgp_ppsratecheck;
638
639 struct work wgp_work;
640 unsigned int wgp_tasks;
641 #define WGP_TASK_SEND_INIT_MESSAGE __BIT(0)
642 #define WGP_TASK_RETRY_HANDSHAKE __BIT(1)
643 #define WGP_TASK_ESTABLISH_SESSION __BIT(2)
644 #define WGP_TASK_ENDPOINT_CHANGED __BIT(3)
645 #define WGP_TASK_SEND_KEEPALIVE_MESSAGE __BIT(4)
646 #define WGP_TASK_DESTROY_PREV_SESSION __BIT(5)
647 };
648
649 struct wg_ops;
650
651 struct wg_softc {
652 struct ifnet wg_if;
653 LIST_ENTRY(wg_softc) wg_list;
654 kmutex_t *wg_lock;
655 kmutex_t *wg_intr_lock;
656 krwlock_t *wg_rwlock;
657
658 uint8_t wg_privkey[WG_STATIC_KEY_LEN];
659 uint8_t wg_pubkey[WG_STATIC_KEY_LEN];
660
661 int wg_npeers;
662 struct pslist_head wg_peers;
663 struct thmap *wg_peers_bypubkey;
664 struct thmap *wg_peers_byname;
665 struct thmap *wg_sessions_byindex;
666 uint16_t wg_listen_port;
667
668 struct threadpool *wg_threadpool;
669
670 struct threadpool_job wg_job;
671 int wg_upcalls;
672 #define WG_UPCALL_INET __BIT(0)
673 #define WG_UPCALL_INET6 __BIT(1)
674
675 #ifdef INET
676 struct socket *wg_so4;
677 struct radix_node_head *wg_rtable_ipv4;
678 #endif
679 #ifdef INET6
680 struct socket *wg_so6;
681 struct radix_node_head *wg_rtable_ipv6;
682 #endif
683
684 struct wg_ppsratecheck wg_ppsratecheck;
685
686 struct wg_ops *wg_ops;
687
688 #ifdef WG_RUMPKERNEL
689 struct wg_user *wg_user;
690 #endif
691 };
692
693 /* [W] 6.1 Preliminaries */
694 #define WG_REKEY_AFTER_MESSAGES (1ULL << 60)
695 #define WG_REJECT_AFTER_MESSAGES (UINT64_MAX - (1 << 13))
696 #define WG_REKEY_AFTER_TIME 120
697 #define WG_REJECT_AFTER_TIME 180
698 #define WG_REKEY_ATTEMPT_TIME 90
699 #define WG_REKEY_TIMEOUT 5
700 #define WG_KEEPALIVE_TIMEOUT 10
701
702 #define WG_COOKIE_TIME 120
703 #define WG_COOKIESECRET_TIME (2 * 60)
704
705 static uint64_t wg_rekey_after_messages = WG_REKEY_AFTER_MESSAGES;
706 static uint64_t wg_reject_after_messages = WG_REJECT_AFTER_MESSAGES;
707 static unsigned wg_rekey_after_time = WG_REKEY_AFTER_TIME;
708 static unsigned wg_reject_after_time = WG_REJECT_AFTER_TIME;
709 static unsigned wg_rekey_attempt_time = WG_REKEY_ATTEMPT_TIME;
710 static unsigned wg_rekey_timeout = WG_REKEY_TIMEOUT;
711 static unsigned wg_keepalive_timeout = WG_KEEPALIVE_TIMEOUT;
712
713 static struct mbuf *
714 wg_get_mbuf(size_t, size_t);
715
716 static int wg_send_data_msg(struct wg_peer *, struct wg_session *,
717 struct mbuf *);
718 static int wg_send_cookie_msg(struct wg_softc *, struct wg_peer *,
719 const uint32_t, const uint8_t [WG_MAC_LEN],
720 const struct sockaddr *);
721 static int wg_send_handshake_msg_resp(struct wg_softc *, struct wg_peer *,
722 struct wg_session *, const struct wg_msg_init *);
723 static void wg_send_keepalive_msg(struct wg_peer *, struct wg_session *);
724
725 static struct wg_peer *
726 wg_pick_peer_by_sa(struct wg_softc *, const struct sockaddr *,
727 struct psref *);
728 static struct wg_peer *
729 wg_lookup_peer_by_pubkey(struct wg_softc *,
730 const uint8_t [WG_STATIC_KEY_LEN], struct psref *);
731
732 static struct wg_session *
733 wg_lookup_session_by_index(struct wg_softc *,
734 const uint32_t, struct psref *);
735
736 static void wg_update_endpoint_if_necessary(struct wg_peer *,
737 const struct sockaddr *);
738
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_halt(&wgp->wgp_session_dtor_timer, NULL);
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_halt(&wgp->wgp_handshake_timeout_timer, NULL);
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_update_endpoint_if_necessary(wgp, src);
2150
2151 /*
2152 * If we had a data packet queued up, send it; otherwise send a
2153 * keepalive message -- either way we have to send something
2154 * immediately or else the responder will never answer.
2155 */
2156 if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
2157 kpreempt_disable();
2158 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
2159 M_SETCTX(m, wgp);
2160 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
2161 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
2162 if_name(&wg->wg_if));
2163 m_freem(m);
2164 }
2165 kpreempt_enable();
2166 } else {
2167 wg_send_keepalive_msg(wgp, wgs);
2168 }
2169
2170 if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
2171 /*
2172 * Transition ESTABLISHED->DESTROYING. The session
2173 * will remain usable for the data rx path to process
2174 * packets still in flight to us, but we won't use it
2175 * for data tx.
2176 */
2177 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
2178 " -> WGS_STATE_DESTROYING\n",
2179 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
2180 atomic_store_relaxed(&wgs_prev->wgs_state,
2181 WGS_STATE_DESTROYING);
2182
2183 /* We can't destroy the old session immediately */
2184 wg_schedule_session_dtor_timer(wgp);
2185 } else {
2186 KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
2187 "state=%d", wgs_prev->wgs_state);
2188 }
2189
2190 out:
2191 mutex_exit(wgp->wgp_lock);
2192 wg_put_session(wgs, &psref);
2193 }
2194
2195 static int
2196 wg_send_handshake_msg_resp(struct wg_softc *wg, struct wg_peer *wgp,
2197 struct wg_session *wgs, const struct wg_msg_init *wgmi)
2198 {
2199 int error;
2200 struct mbuf *m;
2201 struct wg_msg_resp *wgmr;
2202
2203 KASSERT(mutex_owned(wgp->wgp_lock));
2204 KASSERT(wgs == wgp->wgp_session_unstable);
2205 KASSERTMSG(wgs->wgs_state == WGS_STATE_UNKNOWN, "state=%d",
2206 wgs->wgs_state);
2207
2208 m = m_gethdr(M_WAIT, MT_DATA);
2209 if (sizeof(*wgmr) > MHLEN) {
2210 m_clget(m, M_WAIT);
2211 CTASSERT(sizeof(*wgmr) <= MCLBYTES);
2212 }
2213 m->m_pkthdr.len = m->m_len = sizeof(*wgmr);
2214 wgmr = mtod(m, struct wg_msg_resp *);
2215 wg_fill_msg_resp(wg, wgp, wgs, wgmr, wgmi);
2216
2217 error = wg->wg_ops->send_hs_msg(wgp, m);
2218 if (error == 0)
2219 WG_TRACE("resp msg sent");
2220 return error;
2221 }
2222
2223 static struct wg_peer *
2224 wg_lookup_peer_by_pubkey(struct wg_softc *wg,
2225 const uint8_t pubkey[WG_STATIC_KEY_LEN], struct psref *psref)
2226 {
2227 struct wg_peer *wgp;
2228
2229 int s = pserialize_read_enter();
2230 wgp = thmap_get(wg->wg_peers_bypubkey, pubkey, WG_STATIC_KEY_LEN);
2231 if (wgp != NULL)
2232 wg_get_peer(wgp, psref);
2233 pserialize_read_exit(s);
2234
2235 return wgp;
2236 }
2237
2238 static void
2239 wg_fill_msg_cookie(struct wg_softc *wg, struct wg_peer *wgp,
2240 struct wg_msg_cookie *wgmc, const uint32_t sender,
2241 const uint8_t mac1[WG_MAC_LEN], const struct sockaddr *src)
2242 {
2243 uint8_t cookie[WG_COOKIE_LEN];
2244 uint8_t key[WG_HASH_LEN];
2245 uint8_t addr[sizeof(struct in6_addr)];
2246 size_t addrlen;
2247 uint16_t uh_sport; /* be */
2248
2249 KASSERT(mutex_owned(wgp->wgp_lock));
2250
2251 wgmc->wgmc_type = htole32(WG_MSG_TYPE_COOKIE);
2252 wgmc->wgmc_receiver = sender;
2253 cprng_fast(wgmc->wgmc_salt, sizeof(wgmc->wgmc_salt));
2254
2255 /*
2256 * [W] 5.4.7: Under Load: Cookie Reply Message
2257 * "The secret variable, Rm, changes every two minutes to a
2258 * random value"
2259 */
2260 if ((time_uptime - wgp->wgp_last_cookiesecret_time) >
2261 WG_COOKIESECRET_TIME) {
2262 cprng_strong(kern_cprng, wgp->wgp_cookiesecret,
2263 sizeof(wgp->wgp_cookiesecret), 0);
2264 wgp->wgp_last_cookiesecret_time = time_uptime;
2265 }
2266
2267 switch (src->sa_family) {
2268 case AF_INET: {
2269 const struct sockaddr_in *sin = satocsin(src);
2270 addrlen = sizeof(sin->sin_addr);
2271 memcpy(addr, &sin->sin_addr, addrlen);
2272 uh_sport = sin->sin_port;
2273 break;
2274 }
2275 #ifdef INET6
2276 case AF_INET6: {
2277 const struct sockaddr_in6 *sin6 = satocsin6(src);
2278 addrlen = sizeof(sin6->sin6_addr);
2279 memcpy(addr, &sin6->sin6_addr, addrlen);
2280 uh_sport = sin6->sin6_port;
2281 break;
2282 }
2283 #endif
2284 default:
2285 panic("invalid af=%d", src->sa_family);
2286 }
2287
2288 wg_algo_mac(cookie, sizeof(cookie),
2289 wgp->wgp_cookiesecret, sizeof(wgp->wgp_cookiesecret),
2290 addr, addrlen, (const uint8_t *)&uh_sport, sizeof(uh_sport));
2291 wg_algo_mac_cookie(key, sizeof(key), wg->wg_pubkey,
2292 sizeof(wg->wg_pubkey));
2293 wg_algo_xaead_enc(wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie), key,
2294 cookie, sizeof(cookie), mac1, WG_MAC_LEN, wgmc->wgmc_salt);
2295
2296 /* Need to store to calculate mac2 */
2297 memcpy(wgp->wgp_last_sent_cookie, cookie, sizeof(cookie));
2298 wgp->wgp_last_sent_cookie_valid = true;
2299 }
2300
2301 static int
2302 wg_send_cookie_msg(struct wg_softc *wg, struct wg_peer *wgp,
2303 const uint32_t sender, const uint8_t mac1[WG_MAC_LEN],
2304 const struct sockaddr *src)
2305 {
2306 int error;
2307 struct mbuf *m;
2308 struct wg_msg_cookie *wgmc;
2309
2310 KASSERT(mutex_owned(wgp->wgp_lock));
2311
2312 m = m_gethdr(M_WAIT, MT_DATA);
2313 if (sizeof(*wgmc) > MHLEN) {
2314 m_clget(m, M_WAIT);
2315 CTASSERT(sizeof(*wgmc) <= MCLBYTES);
2316 }
2317 m->m_pkthdr.len = m->m_len = sizeof(*wgmc);
2318 wgmc = mtod(m, struct wg_msg_cookie *);
2319 wg_fill_msg_cookie(wg, wgp, wgmc, sender, mac1, src);
2320
2321 error = wg->wg_ops->send_hs_msg(wgp, m);
2322 if (error == 0)
2323 WG_TRACE("cookie msg sent");
2324 return error;
2325 }
2326
2327 static bool
2328 wg_is_underload(struct wg_softc *wg, struct wg_peer *wgp, int msgtype)
2329 {
2330 #ifdef WG_DEBUG_PARAMS
2331 if (wg_force_underload)
2332 return true;
2333 #endif
2334
2335 /*
2336 * XXX we don't have a means of a load estimation. The purpose of
2337 * the mechanism is a DoS mitigation, so we consider frequent handshake
2338 * messages as (a kind of) load; if a message of the same type comes
2339 * to a peer within 1 second, we consider we are under load.
2340 */
2341 time_t last = wgp->wgp_last_msg_received_time[msgtype];
2342 wgp->wgp_last_msg_received_time[msgtype] = time_uptime;
2343 return (time_uptime - last) == 0;
2344 }
2345
2346 static void
2347 wg_calculate_keys(struct wg_session *wgs, const bool initiator)
2348 {
2349
2350 KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
2351
2352 /*
2353 * [W] 5.4.5: Ti^send = Tr^recv, Ti^recv = Tr^send := KDF2(Ci = Cr, e)
2354 */
2355 if (initiator) {
2356 wg_algo_kdf(wgs->wgs_tkey_send, wgs->wgs_tkey_recv, NULL,
2357 wgs->wgs_chaining_key, NULL, 0);
2358 } else {
2359 wg_algo_kdf(wgs->wgs_tkey_recv, wgs->wgs_tkey_send, NULL,
2360 wgs->wgs_chaining_key, NULL, 0);
2361 }
2362 WG_DUMP_HASH("wgs_tkey_send", wgs->wgs_tkey_send);
2363 WG_DUMP_HASH("wgs_tkey_recv", wgs->wgs_tkey_recv);
2364 }
2365
2366 static uint64_t
2367 wg_session_get_send_counter(struct wg_session *wgs)
2368 {
2369 #ifdef __HAVE_ATOMIC64_LOADSTORE
2370 return atomic_load_relaxed(&wgs->wgs_send_counter);
2371 #else
2372 uint64_t send_counter;
2373
2374 mutex_enter(&wgs->wgs_send_counter_lock);
2375 send_counter = wgs->wgs_send_counter;
2376 mutex_exit(&wgs->wgs_send_counter_lock);
2377
2378 return send_counter;
2379 #endif
2380 }
2381
2382 static uint64_t
2383 wg_session_inc_send_counter(struct wg_session *wgs)
2384 {
2385 #ifdef __HAVE_ATOMIC64_LOADSTORE
2386 return atomic_inc_64_nv(&wgs->wgs_send_counter) - 1;
2387 #else
2388 uint64_t send_counter;
2389
2390 mutex_enter(&wgs->wgs_send_counter_lock);
2391 send_counter = wgs->wgs_send_counter++;
2392 mutex_exit(&wgs->wgs_send_counter_lock);
2393
2394 return send_counter;
2395 #endif
2396 }
2397
2398 static void
2399 wg_clear_states(struct wg_session *wgs)
2400 {
2401
2402 KASSERT(mutex_owned(wgs->wgs_peer->wgp_lock));
2403
2404 wgs->wgs_send_counter = 0;
2405 sliwin_reset(&wgs->wgs_recvwin->window);
2406
2407 #define wgs_clear(v) explicit_memset(wgs->wgs_##v, 0, sizeof(wgs->wgs_##v))
2408 wgs_clear(handshake_hash);
2409 wgs_clear(chaining_key);
2410 wgs_clear(ephemeral_key_pub);
2411 wgs_clear(ephemeral_key_priv);
2412 wgs_clear(ephemeral_key_peer);
2413 #undef wgs_clear
2414 }
2415
2416 static struct wg_session *
2417 wg_lookup_session_by_index(struct wg_softc *wg, const uint32_t index,
2418 struct psref *psref)
2419 {
2420 struct wg_session *wgs;
2421
2422 int s = pserialize_read_enter();
2423 wgs = thmap_get(wg->wg_sessions_byindex, &index, sizeof index);
2424 if (wgs != NULL) {
2425 uint32_t oindex __diagused =
2426 atomic_load_relaxed(&wgs->wgs_local_index);
2427 KASSERTMSG(index == oindex,
2428 "index=%"PRIx32" wgs->wgs_local_index=%"PRIx32,
2429 index, oindex);
2430 psref_acquire(psref, &wgs->wgs_psref, wg_psref_class);
2431 }
2432 pserialize_read_exit(s);
2433
2434 return wgs;
2435 }
2436
2437 static void
2438 wg_send_keepalive_msg(struct wg_peer *wgp, struct wg_session *wgs)
2439 {
2440 struct mbuf *m;
2441
2442 /*
2443 * [W] 6.5 Passive Keepalive
2444 * "A keepalive message is simply a transport data message with
2445 * a zero-length encapsulated encrypted inner-packet."
2446 */
2447 WG_TRACE("");
2448 m = m_gethdr(M_WAIT, MT_DATA);
2449 wg_send_data_msg(wgp, wgs, m);
2450 }
2451
2452 static bool
2453 wg_need_to_send_init_message(struct wg_session *wgs)
2454 {
2455 /*
2456 * [W] 6.2 Transport Message Limits
2457 * "if a peer is the initiator of a current secure session,
2458 * WireGuard will send a handshake initiation message to begin
2459 * a new secure session ... if after receiving a transport data
2460 * message, the current secure session is (REJECT-AFTER-TIME
2461 * KEEPALIVE-TIMEOUT REKEY-TIMEOUT) seconds old and it has
2462 * not yet acted upon this event."
2463 */
2464 return wgs->wgs_is_initiator && wgs->wgs_time_last_data_sent == 0 &&
2465 (time_uptime - wgs->wgs_time_established) >=
2466 (wg_reject_after_time - wg_keepalive_timeout - wg_rekey_timeout);
2467 }
2468
2469 static void
2470 wg_schedule_peer_task(struct wg_peer *wgp, unsigned int task)
2471 {
2472
2473 mutex_enter(wgp->wgp_intr_lock);
2474 WG_DLOG("tasks=%d, task=%d\n", wgp->wgp_tasks, task);
2475 if (wgp->wgp_tasks == 0)
2476 /*
2477 * XXX If the current CPU is already loaded -- e.g., if
2478 * there's already a bunch of handshakes queued up --
2479 * consider tossing this over to another CPU to
2480 * distribute the load.
2481 */
2482 workqueue_enqueue(wg_wq, &wgp->wgp_work, NULL);
2483 wgp->wgp_tasks |= task;
2484 mutex_exit(wgp->wgp_intr_lock);
2485 }
2486
2487 static void
2488 wg_change_endpoint(struct wg_peer *wgp, const struct sockaddr *new)
2489 {
2490 struct wg_sockaddr *wgsa_prev;
2491
2492 WG_TRACE("Changing endpoint");
2493
2494 memcpy(wgp->wgp_endpoint0, new, new->sa_len);
2495 wgsa_prev = wgp->wgp_endpoint;
2496 atomic_store_release(&wgp->wgp_endpoint, wgp->wgp_endpoint0);
2497 wgp->wgp_endpoint0 = wgsa_prev;
2498 atomic_store_release(&wgp->wgp_endpoint_available, true);
2499
2500 wg_schedule_peer_task(wgp, WGP_TASK_ENDPOINT_CHANGED);
2501 }
2502
2503 static bool
2504 wg_validate_inner_packet(const char *packet, size_t decrypted_len, int *af)
2505 {
2506 uint16_t packet_len;
2507 const struct ip *ip;
2508
2509 if (__predict_false(decrypted_len < sizeof(*ip))) {
2510 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2511 sizeof(*ip));
2512 return false;
2513 }
2514
2515 ip = (const struct ip *)packet;
2516 if (ip->ip_v == 4)
2517 *af = AF_INET;
2518 else if (ip->ip_v == 6)
2519 *af = AF_INET6;
2520 else {
2521 WG_DLOG("ip_v=%d\n", ip->ip_v);
2522 return false;
2523 }
2524
2525 WG_DLOG("af=%d\n", *af);
2526
2527 switch (*af) {
2528 #ifdef INET
2529 case AF_INET:
2530 packet_len = ntohs(ip->ip_len);
2531 break;
2532 #endif
2533 #ifdef INET6
2534 case AF_INET6: {
2535 const struct ip6_hdr *ip6;
2536
2537 if (__predict_false(decrypted_len < sizeof(*ip6))) {
2538 WG_DLOG("decrypted_len=%zu < %zu\n", decrypted_len,
2539 sizeof(*ip6));
2540 return false;
2541 }
2542
2543 ip6 = (const struct ip6_hdr *)packet;
2544 packet_len = sizeof(*ip6) + ntohs(ip6->ip6_plen);
2545 break;
2546 }
2547 #endif
2548 default:
2549 return false;
2550 }
2551
2552 if (packet_len > decrypted_len) {
2553 WG_DLOG("packet_len %u > decrypted_len %zu\n", packet_len,
2554 decrypted_len);
2555 return false;
2556 }
2557
2558 return true;
2559 }
2560
2561 static bool
2562 wg_validate_route(struct wg_softc *wg, struct wg_peer *wgp_expected,
2563 int af, char *packet)
2564 {
2565 struct sockaddr_storage ss;
2566 struct sockaddr *sa;
2567 struct psref psref;
2568 struct wg_peer *wgp;
2569 bool ok;
2570
2571 /*
2572 * II CRYPTOKEY ROUTING
2573 * "it will only accept it if its source IP resolves in the
2574 * table to the public key used in the secure session for
2575 * decrypting it."
2576 */
2577
2578 if (af == AF_INET) {
2579 const struct ip *ip = (const struct ip *)packet;
2580 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
2581 sockaddr_in_init(sin, &ip->ip_src, 0);
2582 sa = sintosa(sin);
2583 #ifdef INET6
2584 } else {
2585 const struct ip6_hdr *ip6 = (const struct ip6_hdr *)packet;
2586 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
2587 sockaddr_in6_init(sin6, &ip6->ip6_src, 0, 0, 0);
2588 sa = sin6tosa(sin6);
2589 #endif
2590 }
2591
2592 wgp = wg_pick_peer_by_sa(wg, sa, &psref);
2593 ok = (wgp == wgp_expected);
2594 if (wgp != NULL)
2595 wg_put_peer(wgp, &psref);
2596
2597 return ok;
2598 }
2599
2600 static void
2601 wg_session_dtor_timer(void *arg)
2602 {
2603 struct wg_peer *wgp = arg;
2604
2605 WG_TRACE("enter");
2606
2607 wg_schedule_peer_task(wgp, WGP_TASK_DESTROY_PREV_SESSION);
2608 }
2609
2610 static void
2611 wg_schedule_session_dtor_timer(struct wg_peer *wgp)
2612 {
2613
2614 /* 1 second grace period */
2615 callout_schedule(&wgp->wgp_session_dtor_timer, hz);
2616 }
2617
2618 static bool
2619 sockaddr_port_match(const struct sockaddr *sa1, const struct sockaddr *sa2)
2620 {
2621 if (sa1->sa_family != sa2->sa_family)
2622 return false;
2623
2624 switch (sa1->sa_family) {
2625 #ifdef INET
2626 case AF_INET:
2627 return satocsin(sa1)->sin_port == satocsin(sa2)->sin_port;
2628 #endif
2629 #ifdef INET6
2630 case AF_INET6:
2631 return satocsin6(sa1)->sin6_port == satocsin6(sa2)->sin6_port;
2632 #endif
2633 default:
2634 return false;
2635 }
2636 }
2637
2638 static void
2639 wg_update_endpoint_if_necessary(struct wg_peer *wgp,
2640 const struct sockaddr *src)
2641 {
2642 struct wg_sockaddr *wgsa;
2643 struct psref psref;
2644
2645 wgsa = wg_get_endpoint_sa(wgp, &psref);
2646
2647 #ifdef WG_DEBUG_LOG
2648 char oldaddr[128], newaddr[128];
2649 sockaddr_format(wgsatosa(wgsa), oldaddr, sizeof(oldaddr));
2650 sockaddr_format(src, newaddr, sizeof(newaddr));
2651 WG_DLOG("old=%s, new=%s\n", oldaddr, newaddr);
2652 #endif
2653
2654 /*
2655 * III: "Since the packet has authenticated correctly, the source IP of
2656 * the outer UDP/IP packet is used to update the endpoint for peer..."
2657 */
2658 if (__predict_false(sockaddr_cmp(src, wgsatosa(wgsa)) != 0 ||
2659 !sockaddr_port_match(src, wgsatosa(wgsa)))) {
2660 /* XXX We can't change the endpoint twice in a short period */
2661 if (atomic_swap_uint(&wgp->wgp_endpoint_changing, 1) == 0) {
2662 wg_change_endpoint(wgp, src);
2663 }
2664 }
2665
2666 wg_put_sa(wgp, wgsa, &psref);
2667 }
2668
2669 static void __noinline
2670 wg_handle_msg_data(struct wg_softc *wg, struct mbuf *m,
2671 const struct sockaddr *src)
2672 {
2673 struct wg_msg_data *wgmd;
2674 char *encrypted_buf = NULL, *decrypted_buf;
2675 size_t encrypted_len, decrypted_len;
2676 struct wg_session *wgs;
2677 struct wg_peer *wgp;
2678 int state;
2679 size_t mlen;
2680 struct psref psref;
2681 int error, af;
2682 bool success, free_encrypted_buf = false, ok;
2683 struct mbuf *n;
2684
2685 KASSERT(m->m_len >= sizeof(struct wg_msg_data));
2686 wgmd = mtod(m, struct wg_msg_data *);
2687
2688 KASSERT(wgmd->wgmd_type == htole32(WG_MSG_TYPE_DATA));
2689 WG_TRACE("data");
2690
2691 /* Find the putative session, or drop. */
2692 wgs = wg_lookup_session_by_index(wg, wgmd->wgmd_receiver, &psref);
2693 if (wgs == NULL) {
2694 WG_TRACE("No session found");
2695 m_freem(m);
2696 return;
2697 }
2698
2699 /*
2700 * We are only ready to handle data when in INIT_PASSIVE,
2701 * ESTABLISHED, or DESTROYING. All transitions out of that
2702 * state dissociate the session index and drain psrefs.
2703 *
2704 * atomic_load_acquire matches atomic_store_release in either
2705 * wg_handle_msg_init or wg_handle_msg_resp. (The transition
2706 * INIT_PASSIVE to ESTABLISHED in wg_task_establish_session
2707 * doesn't make a difference for this rx path.)
2708 */
2709 state = atomic_load_acquire(&wgs->wgs_state);
2710 switch (state) {
2711 case WGS_STATE_UNKNOWN:
2712 case WGS_STATE_INIT_ACTIVE:
2713 WG_TRACE("not yet ready for data");
2714 goto out;
2715 case WGS_STATE_INIT_PASSIVE:
2716 case WGS_STATE_ESTABLISHED:
2717 case WGS_STATE_DESTROYING:
2718 break;
2719 }
2720
2721 /*
2722 * Get the peer, for rate-limited logs (XXX MPSAFE, dtrace) and
2723 * to update the endpoint if authentication succeeds.
2724 */
2725 wgp = wgs->wgs_peer;
2726
2727 /*
2728 * Reject outrageously wrong sequence numbers before doing any
2729 * crypto work or taking any locks.
2730 */
2731 error = sliwin_check_fast(&wgs->wgs_recvwin->window,
2732 le64toh(wgmd->wgmd_counter));
2733 if (error) {
2734 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2735 "%s: peer %s: out-of-window packet: %"PRIu64"\n",
2736 if_name(&wg->wg_if), wgp->wgp_name,
2737 le64toh(wgmd->wgmd_counter));
2738 goto out;
2739 }
2740
2741 /* Ensure the payload and authenticator are contiguous. */
2742 mlen = m_length(m);
2743 encrypted_len = mlen - sizeof(*wgmd);
2744 if (encrypted_len < WG_AUTHTAG_LEN) {
2745 WG_DLOG("Short encrypted_len: %zu\n", encrypted_len);
2746 goto out;
2747 }
2748 success = m_ensure_contig(&m, sizeof(*wgmd) + encrypted_len);
2749 if (success) {
2750 encrypted_buf = mtod(m, char *) + sizeof(*wgmd);
2751 } else {
2752 encrypted_buf = kmem_intr_alloc(encrypted_len, KM_NOSLEEP);
2753 if (encrypted_buf == NULL) {
2754 WG_DLOG("failed to allocate encrypted_buf\n");
2755 goto out;
2756 }
2757 m_copydata(m, sizeof(*wgmd), encrypted_len, encrypted_buf);
2758 free_encrypted_buf = true;
2759 }
2760 /* m_ensure_contig may change m regardless of its result */
2761 KASSERT(m->m_len >= sizeof(*wgmd));
2762 wgmd = mtod(m, struct wg_msg_data *);
2763
2764 #ifdef WG_DEBUG_PACKET
2765 if (wg_debug & WG_DEBUG_FLAGS_PACKET) {
2766 hexdump(printf, "incoming packet", encrypted_buf,
2767 encrypted_len);
2768 }
2769 #endif
2770 /*
2771 * Get a buffer for the plaintext. Add WG_AUTHTAG_LEN to avoid
2772 * a zero-length buffer (XXX). Drop if plaintext is longer
2773 * than MCLBYTES (XXX).
2774 */
2775 decrypted_len = encrypted_len - WG_AUTHTAG_LEN;
2776 if (decrypted_len > MCLBYTES) {
2777 /* FIXME handle larger data than MCLBYTES */
2778 WG_DLOG("couldn't handle larger data than MCLBYTES\n");
2779 goto out;
2780 }
2781 n = wg_get_mbuf(0, decrypted_len + WG_AUTHTAG_LEN);
2782 if (n == NULL) {
2783 WG_DLOG("wg_get_mbuf failed\n");
2784 goto out;
2785 }
2786 decrypted_buf = mtod(n, char *);
2787
2788 /* Decrypt and verify the packet. */
2789 WG_DLOG("mlen=%zu, encrypted_len=%zu\n", mlen, encrypted_len);
2790 error = wg_algo_aead_dec(decrypted_buf,
2791 encrypted_len - WG_AUTHTAG_LEN /* can be 0 */,
2792 wgs->wgs_tkey_recv, le64toh(wgmd->wgmd_counter), encrypted_buf,
2793 encrypted_len, NULL, 0);
2794 if (error != 0) {
2795 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2796 "%s: peer %s: failed to wg_algo_aead_dec\n",
2797 if_name(&wg->wg_if), wgp->wgp_name);
2798 m_freem(n);
2799 goto out;
2800 }
2801 WG_DLOG("outsize=%u\n", (u_int)decrypted_len);
2802
2803 /* Packet is genuine. Reject it if a replay or just too old. */
2804 mutex_enter(&wgs->wgs_recvwin->lock);
2805 error = sliwin_update(&wgs->wgs_recvwin->window,
2806 le64toh(wgmd->wgmd_counter));
2807 mutex_exit(&wgs->wgs_recvwin->lock);
2808 if (error) {
2809 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2810 "%s: peer %s: replay or out-of-window packet: %"PRIu64"\n",
2811 if_name(&wg->wg_if), wgp->wgp_name,
2812 le64toh(wgmd->wgmd_counter));
2813 m_freem(n);
2814 goto out;
2815 }
2816
2817 #ifdef WG_DEBUG_PACKET
2818 if (wg_debug & WG_DEBUG_FLAGS_PACKET) {
2819 hexdump(printf, "tkey_recv", wgs->wgs_tkey_recv,
2820 sizeof(wgs->wgs_tkey_recv));
2821 hexdump(printf, "wgmd", wgmd, sizeof(*wgmd));
2822 hexdump(printf, "decrypted_buf", decrypted_buf,
2823 decrypted_len);
2824 }
2825 #endif
2826 /* We're done with m now; free it and chuck the pointers. */
2827 m_freem(m);
2828 m = NULL;
2829 wgmd = NULL;
2830
2831 /*
2832 * Validate the encapsulated packet header and get the address
2833 * family, or drop.
2834 */
2835 ok = wg_validate_inner_packet(decrypted_buf, decrypted_len, &af);
2836 if (!ok) {
2837 m_freem(n);
2838 goto out;
2839 }
2840
2841 /*
2842 * The packet is genuine. Update the peer's endpoint if the
2843 * source address changed.
2844 *
2845 * XXX How to prevent DoS by replaying genuine packets from the
2846 * wrong source address?
2847 */
2848 wg_update_endpoint_if_necessary(wgp, src);
2849
2850 /* Submit it into our network stack if routable. */
2851 ok = wg_validate_route(wg, wgp, af, decrypted_buf);
2852 if (ok) {
2853 wg->wg_ops->input(&wg->wg_if, n, af);
2854 } else {
2855 char addrstr[INET6_ADDRSTRLEN];
2856 memset(addrstr, 0, sizeof(addrstr));
2857 if (af == AF_INET) {
2858 const struct ip *ip = (const struct ip *)decrypted_buf;
2859 IN_PRINT(addrstr, &ip->ip_src);
2860 #ifdef INET6
2861 } else if (af == AF_INET6) {
2862 const struct ip6_hdr *ip6 =
2863 (const struct ip6_hdr *)decrypted_buf;
2864 IN6_PRINT(addrstr, &ip6->ip6_src);
2865 #endif
2866 }
2867 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2868 "%s: peer %s: invalid source address (%s)\n",
2869 if_name(&wg->wg_if), wgp->wgp_name, addrstr);
2870 m_freem(n);
2871 /*
2872 * The inner address is invalid however the session is valid
2873 * so continue the session processing below.
2874 */
2875 }
2876 n = NULL;
2877
2878 /* Update the state machine if necessary. */
2879 if (__predict_false(state == WGS_STATE_INIT_PASSIVE)) {
2880 /*
2881 * We were waiting for the initiator to send their
2882 * first data transport message, and that has happened.
2883 * Schedule a task to establish this session.
2884 */
2885 wg_schedule_peer_task(wgp, WGP_TASK_ESTABLISH_SESSION);
2886 } else {
2887 if (__predict_false(wg_need_to_send_init_message(wgs))) {
2888 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
2889 }
2890 /*
2891 * [W] 6.5 Passive Keepalive
2892 * "If a peer has received a validly-authenticated transport
2893 * data message (section 5.4.6), but does not have any packets
2894 * itself to send back for KEEPALIVE-TIMEOUT seconds, it sends
2895 * a keepalive message."
2896 */
2897 WG_DLOG("time_uptime=%ju wgs_time_last_data_sent=%ju\n",
2898 (uintmax_t)time_uptime,
2899 (uintmax_t)wgs->wgs_time_last_data_sent);
2900 if ((time_uptime - wgs->wgs_time_last_data_sent) >=
2901 wg_keepalive_timeout) {
2902 WG_TRACE("Schedule sending keepalive message");
2903 /*
2904 * We can't send a keepalive message here to avoid
2905 * a deadlock; we already hold the solock of a socket
2906 * that is used to send the message.
2907 */
2908 wg_schedule_peer_task(wgp,
2909 WGP_TASK_SEND_KEEPALIVE_MESSAGE);
2910 }
2911 }
2912 out:
2913 wg_put_session(wgs, &psref);
2914 m_freem(m);
2915 if (free_encrypted_buf)
2916 kmem_intr_free(encrypted_buf, encrypted_len);
2917 }
2918
2919 static void __noinline
2920 wg_handle_msg_cookie(struct wg_softc *wg, const struct wg_msg_cookie *wgmc)
2921 {
2922 struct wg_session *wgs;
2923 struct wg_peer *wgp;
2924 struct psref psref;
2925 int error;
2926 uint8_t key[WG_HASH_LEN];
2927 uint8_t cookie[WG_COOKIE_LEN];
2928
2929 WG_TRACE("cookie msg received");
2930
2931 /* Find the putative session. */
2932 wgs = wg_lookup_session_by_index(wg, wgmc->wgmc_receiver, &psref);
2933 if (wgs == NULL) {
2934 WG_TRACE("No session found");
2935 return;
2936 }
2937
2938 /* Lock the peer so we can update the cookie state. */
2939 wgp = wgs->wgs_peer;
2940 mutex_enter(wgp->wgp_lock);
2941
2942 if (!wgp->wgp_last_sent_mac1_valid) {
2943 WG_TRACE("No valid mac1 sent (or expired)");
2944 goto out;
2945 }
2946
2947 /*
2948 * wgp_last_sent_mac1_valid is only set to true when we are
2949 * transitioning to INIT_ACTIVE or INIT_PASSIVE, and always
2950 * cleared on transition out of them.
2951 */
2952 KASSERTMSG((wgs->wgs_state == WGS_STATE_INIT_ACTIVE ||
2953 wgs->wgs_state == WGS_STATE_INIT_PASSIVE),
2954 "state=%d", wgs->wgs_state);
2955
2956 /* Decrypt the cookie and store it for later handshake retry. */
2957 wg_algo_mac_cookie(key, sizeof(key), wgp->wgp_pubkey,
2958 sizeof(wgp->wgp_pubkey));
2959 error = wg_algo_xaead_dec(cookie, sizeof(cookie), key,
2960 wgmc->wgmc_cookie, sizeof(wgmc->wgmc_cookie),
2961 wgp->wgp_last_sent_mac1, sizeof(wgp->wgp_last_sent_mac1),
2962 wgmc->wgmc_salt);
2963 if (error != 0) {
2964 WG_LOG_RATECHECK(&wgp->wgp_ppsratecheck, LOG_DEBUG,
2965 "%s: peer %s: wg_algo_aead_dec for cookie failed: "
2966 "error=%d\n", if_name(&wg->wg_if), wgp->wgp_name, error);
2967 goto out;
2968 }
2969 /*
2970 * [W] 6.6: Interaction with Cookie Reply System
2971 * "it should simply store the decrypted cookie value from the cookie
2972 * reply message, and wait for the expiration of the REKEY-TIMEOUT
2973 * timer for retrying a handshake initiation message."
2974 */
2975 wgp->wgp_latest_cookie_time = time_uptime;
2976 memcpy(wgp->wgp_latest_cookie, cookie, sizeof(wgp->wgp_latest_cookie));
2977 out:
2978 mutex_exit(wgp->wgp_lock);
2979 wg_put_session(wgs, &psref);
2980 }
2981
2982 static struct mbuf *
2983 wg_validate_msg_header(struct wg_softc *wg, struct mbuf *m)
2984 {
2985 struct wg_msg wgm;
2986 size_t mbuflen;
2987 size_t msglen;
2988
2989 /*
2990 * Get the mbuf chain length. It is already guaranteed, by
2991 * wg_overudp_cb, to be large enough for a struct wg_msg.
2992 */
2993 mbuflen = m_length(m);
2994 KASSERT(mbuflen >= sizeof(struct wg_msg));
2995
2996 /*
2997 * Copy the message header (32-bit message type) out -- we'll
2998 * worry about contiguity and alignment later.
2999 */
3000 m_copydata(m, 0, sizeof(wgm), &wgm);
3001 switch (le32toh(wgm.wgm_type)) {
3002 case WG_MSG_TYPE_INIT:
3003 msglen = sizeof(struct wg_msg_init);
3004 break;
3005 case WG_MSG_TYPE_RESP:
3006 msglen = sizeof(struct wg_msg_resp);
3007 break;
3008 case WG_MSG_TYPE_COOKIE:
3009 msglen = sizeof(struct wg_msg_cookie);
3010 break;
3011 case WG_MSG_TYPE_DATA:
3012 msglen = sizeof(struct wg_msg_data);
3013 break;
3014 default:
3015 WG_LOG_RATECHECK(&wg->wg_ppsratecheck, LOG_DEBUG,
3016 "%s: Unexpected msg type: %u\n", if_name(&wg->wg_if),
3017 le32toh(wgm.wgm_type));
3018 goto error;
3019 }
3020
3021 /* Verify the mbuf chain is long enough for this type of message. */
3022 if (__predict_false(mbuflen < msglen)) {
3023 WG_DLOG("Invalid msg size: mbuflen=%zu type=%u\n", mbuflen,
3024 le32toh(wgm.wgm_type));
3025 goto error;
3026 }
3027
3028 /* Make the message header contiguous if necessary. */
3029 if (__predict_false(m->m_len < msglen)) {
3030 m = m_pullup(m, msglen);
3031 if (m == NULL)
3032 return NULL;
3033 }
3034
3035 return m;
3036
3037 error:
3038 m_freem(m);
3039 return NULL;
3040 }
3041
3042 static void
3043 wg_handle_packet(struct wg_softc *wg, struct mbuf *m,
3044 const struct sockaddr *src)
3045 {
3046 struct wg_msg *wgm;
3047
3048 KASSERT(curlwp->l_pflag & LP_BOUND);
3049
3050 m = wg_validate_msg_header(wg, m);
3051 if (__predict_false(m == NULL))
3052 return;
3053
3054 KASSERT(m->m_len >= sizeof(struct wg_msg));
3055 wgm = mtod(m, struct wg_msg *);
3056 switch (le32toh(wgm->wgm_type)) {
3057 case WG_MSG_TYPE_INIT:
3058 wg_handle_msg_init(wg, (struct wg_msg_init *)wgm, src);
3059 break;
3060 case WG_MSG_TYPE_RESP:
3061 wg_handle_msg_resp(wg, (struct wg_msg_resp *)wgm, src);
3062 break;
3063 case WG_MSG_TYPE_COOKIE:
3064 wg_handle_msg_cookie(wg, (struct wg_msg_cookie *)wgm);
3065 break;
3066 case WG_MSG_TYPE_DATA:
3067 wg_handle_msg_data(wg, m, src);
3068 /* wg_handle_msg_data frees m for us */
3069 return;
3070 default:
3071 panic("invalid message type: %d", le32toh(wgm->wgm_type));
3072 }
3073
3074 m_freem(m);
3075 }
3076
3077 static void
3078 wg_receive_packets(struct wg_softc *wg, const int af)
3079 {
3080
3081 for (;;) {
3082 int error, flags;
3083 struct socket *so;
3084 struct mbuf *m = NULL;
3085 struct uio dummy_uio;
3086 struct mbuf *paddr = NULL;
3087 struct sockaddr *src;
3088
3089 so = wg_get_so_by_af(wg, af);
3090 flags = MSG_DONTWAIT;
3091 dummy_uio.uio_resid = 1000000000;
3092
3093 error = so->so_receive(so, &paddr, &dummy_uio, &m, NULL,
3094 &flags);
3095 if (error || m == NULL) {
3096 //if (error == EWOULDBLOCK)
3097 return;
3098 }
3099
3100 KASSERT(paddr != NULL);
3101 KASSERT(paddr->m_len >= sizeof(struct sockaddr));
3102 src = mtod(paddr, struct sockaddr *);
3103
3104 wg_handle_packet(wg, m, src);
3105 }
3106 }
3107
3108 static void
3109 wg_get_peer(struct wg_peer *wgp, struct psref *psref)
3110 {
3111
3112 psref_acquire(psref, &wgp->wgp_psref, wg_psref_class);
3113 }
3114
3115 static void
3116 wg_put_peer(struct wg_peer *wgp, struct psref *psref)
3117 {
3118
3119 psref_release(psref, &wgp->wgp_psref, wg_psref_class);
3120 }
3121
3122 static void
3123 wg_task_send_init_message(struct wg_softc *wg, struct wg_peer *wgp)
3124 {
3125 struct wg_session *wgs;
3126
3127 WG_TRACE("WGP_TASK_SEND_INIT_MESSAGE");
3128
3129 KASSERT(mutex_owned(wgp->wgp_lock));
3130
3131 if (!atomic_load_acquire(&wgp->wgp_endpoint_available)) {
3132 WGLOG(LOG_DEBUG, "%s: No endpoint available\n",
3133 if_name(&wg->wg_if));
3134 /* XXX should do something? */
3135 return;
3136 }
3137
3138 /*
3139 * If we already have an established session, there's no need
3140 * to initiate a new one -- unless the rekey-after-time or
3141 * rekey-after-messages limits have passed.
3142 */
3143 wgs = wgp->wgp_session_stable;
3144 if (wgs->wgs_state == WGS_STATE_ESTABLISHED &&
3145 !atomic_swap_uint(&wgp->wgp_force_rekey, 0))
3146 return;
3147
3148 /*
3149 * Ensure we're initiating a new session. If the unstable
3150 * session is already INIT_ACTIVE or INIT_PASSIVE, this does
3151 * nothing.
3152 */
3153 wg_send_handshake_msg_init(wg, wgp);
3154 }
3155
3156 static void
3157 wg_task_retry_handshake(struct wg_softc *wg, struct wg_peer *wgp)
3158 {
3159 struct wg_session *wgs;
3160
3161 WG_TRACE("WGP_TASK_RETRY_HANDSHAKE");
3162
3163 KASSERT(mutex_owned(wgp->wgp_lock));
3164 KASSERT(wgp->wgp_handshake_start_time != 0);
3165
3166 wgs = wgp->wgp_session_unstable;
3167 if (wgs->wgs_state != WGS_STATE_INIT_ACTIVE)
3168 return;
3169
3170 /*
3171 * XXX no real need to assign a new index here, but we do need
3172 * to transition to UNKNOWN temporarily
3173 */
3174 wg_put_session_index(wg, wgs);
3175
3176 /* [W] 6.4 Handshake Initiation Retransmission */
3177 if ((time_uptime - wgp->wgp_handshake_start_time) >
3178 wg_rekey_attempt_time) {
3179 /* Give up handshaking */
3180 wgp->wgp_handshake_start_time = 0;
3181 WG_TRACE("give up");
3182
3183 /*
3184 * If a new data packet comes, handshaking will be retried
3185 * and a new session would be established at that time,
3186 * however we don't want to send pending packets then.
3187 */
3188 wg_purge_pending_packets(wgp);
3189 return;
3190 }
3191
3192 wg_task_send_init_message(wg, wgp);
3193 }
3194
3195 static void
3196 wg_task_establish_session(struct wg_softc *wg, struct wg_peer *wgp)
3197 {
3198 struct wg_session *wgs, *wgs_prev;
3199 struct mbuf *m;
3200
3201 KASSERT(mutex_owned(wgp->wgp_lock));
3202
3203 wgs = wgp->wgp_session_unstable;
3204 if (wgs->wgs_state != WGS_STATE_INIT_PASSIVE)
3205 /* XXX Can this happen? */
3206 return;
3207
3208 wgs->wgs_time_established = time_uptime;
3209 wgs->wgs_time_last_data_sent = 0;
3210 wgs->wgs_is_initiator = false;
3211
3212 /*
3213 * Session was already ready to receive data. Transition from
3214 * INIT_PASSIVE to ESTABLISHED just so we can swap the
3215 * sessions.
3216 *
3217 * atomic_store_relaxed because this doesn't affect the data rx
3218 * path, wg_handle_msg_data -- changing from INIT_PASSIVE to
3219 * ESTABLISHED makes no difference to the data rx path, and the
3220 * transition to INIT_PASSIVE with store-release already
3221 * published the state needed by the data rx path.
3222 */
3223 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"] -> WGS_STATE_ESTABLISHED\n",
3224 wgs->wgs_local_index, wgs->wgs_remote_index);
3225 atomic_store_relaxed(&wgs->wgs_state, WGS_STATE_ESTABLISHED);
3226 WG_TRACE("WGS_STATE_ESTABLISHED");
3227
3228 /*
3229 * Session is ready to send data too now that we have received
3230 * the peer initiator's first data packet.
3231 *
3232 * Swap the sessions to publish the new one as the stable
3233 * session for the data tx path, wg_output.
3234 */
3235 wg_swap_sessions(wgp);
3236 KASSERT(wgs == wgp->wgp_session_stable);
3237 wgs_prev = wgp->wgp_session_unstable;
3238 getnanotime(&wgp->wgp_last_handshake_time);
3239 wgp->wgp_handshake_start_time = 0;
3240 wgp->wgp_last_sent_mac1_valid = false;
3241 wgp->wgp_last_sent_cookie_valid = false;
3242
3243 /* If we had a data packet queued up, send it. */
3244 if ((m = atomic_swap_ptr(&wgp->wgp_pending, NULL)) != NULL) {
3245 kpreempt_disable();
3246 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
3247 M_SETCTX(m, wgp);
3248 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
3249 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
3250 if_name(&wg->wg_if));
3251 m_freem(m);
3252 }
3253 kpreempt_enable();
3254 }
3255
3256 if (wgs_prev->wgs_state == WGS_STATE_ESTABLISHED) {
3257 /*
3258 * Transition ESTABLISHED->DESTROYING. The session
3259 * will remain usable for the data rx path to process
3260 * packets still in flight to us, but we won't use it
3261 * for data tx.
3262 */
3263 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
3264 " -> WGS_STATE_DESTROYING\n",
3265 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
3266 atomic_store_relaxed(&wgs_prev->wgs_state,
3267 WGS_STATE_DESTROYING);
3268
3269 /* We can't destroy the old session immediately */
3270 wg_schedule_session_dtor_timer(wgp);
3271 } else {
3272 KASSERTMSG(wgs_prev->wgs_state == WGS_STATE_UNKNOWN,
3273 "state=%d", wgs_prev->wgs_state);
3274 WG_DLOG("session[L=%"PRIx32" R=%"PRIx32"]"
3275 " -> WGS_STATE_UNKNOWN\n",
3276 wgs_prev->wgs_local_index, wgs_prev->wgs_remote_index);
3277 wgs_prev->wgs_local_index = 0; /* paranoia */
3278 wgs_prev->wgs_remote_index = 0; /* paranoia */
3279 wg_clear_states(wgs_prev); /* paranoia */
3280 wgs_prev->wgs_state = WGS_STATE_UNKNOWN;
3281 }
3282 }
3283
3284 static void
3285 wg_task_endpoint_changed(struct wg_softc *wg, struct wg_peer *wgp)
3286 {
3287
3288 WG_TRACE("WGP_TASK_ENDPOINT_CHANGED");
3289
3290 KASSERT(mutex_owned(wgp->wgp_lock));
3291
3292 if (atomic_load_relaxed(&wgp->wgp_endpoint_changing)) {
3293 pserialize_perform(wgp->wgp_psz);
3294 mutex_exit(wgp->wgp_lock);
3295 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref,
3296 wg_psref_class);
3297 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref,
3298 wg_psref_class);
3299 mutex_enter(wgp->wgp_lock);
3300 atomic_store_release(&wgp->wgp_endpoint_changing, 0);
3301 }
3302 }
3303
3304 static void
3305 wg_task_send_keepalive_message(struct wg_softc *wg, struct wg_peer *wgp)
3306 {
3307 struct wg_session *wgs;
3308
3309 WG_TRACE("WGP_TASK_SEND_KEEPALIVE_MESSAGE");
3310
3311 KASSERT(mutex_owned(wgp->wgp_lock));
3312
3313 wgs = wgp->wgp_session_stable;
3314 if (wgs->wgs_state != WGS_STATE_ESTABLISHED)
3315 return;
3316
3317 wg_send_keepalive_msg(wgp, wgs);
3318 }
3319
3320 static void
3321 wg_task_destroy_prev_session(struct wg_softc *wg, struct wg_peer *wgp)
3322 {
3323 struct wg_session *wgs;
3324
3325 WG_TRACE("WGP_TASK_DESTROY_PREV_SESSION");
3326
3327 KASSERT(mutex_owned(wgp->wgp_lock));
3328
3329 wgs = wgp->wgp_session_unstable;
3330 if (wgs->wgs_state == WGS_STATE_DESTROYING) {
3331 wg_put_session_index(wg, wgs);
3332 }
3333 }
3334
3335 static void
3336 wg_peer_work(struct work *wk, void *cookie)
3337 {
3338 struct wg_peer *wgp = container_of(wk, struct wg_peer, wgp_work);
3339 struct wg_softc *wg = wgp->wgp_sc;
3340 unsigned int tasks;
3341
3342 mutex_enter(wgp->wgp_intr_lock);
3343 while ((tasks = wgp->wgp_tasks) != 0) {
3344 wgp->wgp_tasks = 0;
3345 mutex_exit(wgp->wgp_intr_lock);
3346
3347 mutex_enter(wgp->wgp_lock);
3348 if (ISSET(tasks, WGP_TASK_SEND_INIT_MESSAGE))
3349 wg_task_send_init_message(wg, wgp);
3350 if (ISSET(tasks, WGP_TASK_RETRY_HANDSHAKE))
3351 wg_task_retry_handshake(wg, wgp);
3352 if (ISSET(tasks, WGP_TASK_ESTABLISH_SESSION))
3353 wg_task_establish_session(wg, wgp);
3354 if (ISSET(tasks, WGP_TASK_ENDPOINT_CHANGED))
3355 wg_task_endpoint_changed(wg, wgp);
3356 if (ISSET(tasks, WGP_TASK_SEND_KEEPALIVE_MESSAGE))
3357 wg_task_send_keepalive_message(wg, wgp);
3358 if (ISSET(tasks, WGP_TASK_DESTROY_PREV_SESSION))
3359 wg_task_destroy_prev_session(wg, wgp);
3360 mutex_exit(wgp->wgp_lock);
3361
3362 mutex_enter(wgp->wgp_intr_lock);
3363 }
3364 mutex_exit(wgp->wgp_intr_lock);
3365 }
3366
3367 static void
3368 wg_job(struct threadpool_job *job)
3369 {
3370 struct wg_softc *wg = container_of(job, struct wg_softc, wg_job);
3371 int bound, upcalls;
3372
3373 mutex_enter(wg->wg_intr_lock);
3374 while ((upcalls = wg->wg_upcalls) != 0) {
3375 wg->wg_upcalls = 0;
3376 mutex_exit(wg->wg_intr_lock);
3377 bound = curlwp_bind();
3378 if (ISSET(upcalls, WG_UPCALL_INET))
3379 wg_receive_packets(wg, AF_INET);
3380 if (ISSET(upcalls, WG_UPCALL_INET6))
3381 wg_receive_packets(wg, AF_INET6);
3382 curlwp_bindx(bound);
3383 mutex_enter(wg->wg_intr_lock);
3384 }
3385 threadpool_job_done(job);
3386 mutex_exit(wg->wg_intr_lock);
3387 }
3388
3389 static int
3390 wg_bind_port(struct wg_softc *wg, const uint16_t port)
3391 {
3392 int error;
3393 uint16_t old_port = wg->wg_listen_port;
3394
3395 if (port != 0 && old_port == port)
3396 return 0;
3397
3398 struct sockaddr_in _sin, *sin = &_sin;
3399 sin->sin_len = sizeof(*sin);
3400 sin->sin_family = AF_INET;
3401 sin->sin_addr.s_addr = INADDR_ANY;
3402 sin->sin_port = htons(port);
3403
3404 error = sobind(wg->wg_so4, sintosa(sin), curlwp);
3405 if (error != 0)
3406 return error;
3407
3408 #ifdef INET6
3409 struct sockaddr_in6 _sin6, *sin6 = &_sin6;
3410 sin6->sin6_len = sizeof(*sin6);
3411 sin6->sin6_family = AF_INET6;
3412 sin6->sin6_addr = in6addr_any;
3413 sin6->sin6_port = htons(port);
3414
3415 error = sobind(wg->wg_so6, sin6tosa(sin6), curlwp);
3416 if (error != 0)
3417 return error;
3418 #endif
3419
3420 wg->wg_listen_port = port;
3421
3422 return 0;
3423 }
3424
3425 static void
3426 wg_so_upcall(struct socket *so, void *cookie, int events, int waitflag)
3427 {
3428 struct wg_softc *wg = cookie;
3429 int reason;
3430
3431 reason = (so->so_proto->pr_domain->dom_family == AF_INET) ?
3432 WG_UPCALL_INET :
3433 WG_UPCALL_INET6;
3434
3435 mutex_enter(wg->wg_intr_lock);
3436 wg->wg_upcalls |= reason;
3437 threadpool_schedule_job(wg->wg_threadpool, &wg->wg_job);
3438 mutex_exit(wg->wg_intr_lock);
3439 }
3440
3441 static int
3442 wg_overudp_cb(struct mbuf **mp, int offset, struct socket *so,
3443 struct sockaddr *src, void *arg)
3444 {
3445 struct wg_softc *wg = arg;
3446 struct wg_msg wgm;
3447 struct mbuf *m = *mp;
3448
3449 WG_TRACE("enter");
3450
3451 /* Verify the mbuf chain is long enough to have a wg msg header. */
3452 KASSERT(offset <= m_length(m));
3453 if (__predict_false(m_length(m) - offset < sizeof(struct wg_msg))) {
3454 /* drop on the floor */
3455 m_freem(m);
3456 return -1;
3457 }
3458
3459 /*
3460 * Copy the message header (32-bit message type) out -- we'll
3461 * worry about contiguity and alignment later.
3462 */
3463 m_copydata(m, offset, sizeof(struct wg_msg), &wgm);
3464 WG_DLOG("type=%d\n", le32toh(wgm.wgm_type));
3465
3466 /*
3467 * Handle DATA packets promptly as they arrive, if they are in
3468 * an active session. Other packets may require expensive
3469 * public-key crypto and are not as sensitive to latency, so
3470 * defer them to the worker thread.
3471 */
3472 switch (le32toh(wgm.wgm_type)) {
3473 case WG_MSG_TYPE_DATA:
3474 /* handle immediately */
3475 m_adj(m, offset);
3476 if (__predict_false(m->m_len < sizeof(struct wg_msg_data))) {
3477 m = m_pullup(m, sizeof(struct wg_msg_data));
3478 if (m == NULL)
3479 return -1;
3480 }
3481 wg_handle_msg_data(wg, m, src);
3482 *mp = NULL;
3483 return 1;
3484 case WG_MSG_TYPE_INIT:
3485 case WG_MSG_TYPE_RESP:
3486 case WG_MSG_TYPE_COOKIE:
3487 /* pass through to so_receive in wg_receive_packets */
3488 return 0;
3489 default:
3490 /* drop on the floor */
3491 m_freem(m);
3492 return -1;
3493 }
3494 }
3495
3496 static int
3497 wg_socreate(struct wg_softc *wg, int af, struct socket **sop)
3498 {
3499 int error;
3500 struct socket *so;
3501
3502 error = socreate(af, &so, SOCK_DGRAM, 0, curlwp, NULL);
3503 if (error != 0)
3504 return error;
3505
3506 solock(so);
3507 so->so_upcallarg = wg;
3508 so->so_upcall = wg_so_upcall;
3509 so->so_rcv.sb_flags |= SB_UPCALL;
3510 inpcb_register_overudp_cb(sotoinpcb(so), wg_overudp_cb, wg);
3511 sounlock(so);
3512
3513 *sop = so;
3514
3515 return 0;
3516 }
3517
3518 static bool
3519 wg_session_hit_limits(struct wg_session *wgs)
3520 {
3521
3522 /*
3523 * [W] 6.2: Transport Message Limits
3524 * "After REJECT-AFTER-MESSAGES transport data messages or after the
3525 * current secure session is REJECT-AFTER-TIME seconds old, whichever
3526 * comes first, WireGuard will refuse to send any more transport data
3527 * messages using the current secure session, ..."
3528 */
3529 KASSERT(wgs->wgs_time_established != 0);
3530 if ((time_uptime - wgs->wgs_time_established) > wg_reject_after_time) {
3531 WG_DLOG("The session hits REJECT_AFTER_TIME\n");
3532 return true;
3533 } else if (wg_session_get_send_counter(wgs) >
3534 wg_reject_after_messages) {
3535 WG_DLOG("The session hits REJECT_AFTER_MESSAGES\n");
3536 return true;
3537 }
3538
3539 return false;
3540 }
3541
3542 static void
3543 wgintr(void *cookie)
3544 {
3545 struct wg_peer *wgp;
3546 struct wg_session *wgs;
3547 struct mbuf *m;
3548 struct psref psref;
3549
3550 while ((m = pktq_dequeue(wg_pktq)) != NULL) {
3551 wgp = M_GETCTX(m, struct wg_peer *);
3552 if ((wgs = wg_get_stable_session(wgp, &psref)) == NULL) {
3553 WG_TRACE("no stable session");
3554 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3555 goto next0;
3556 }
3557 if (__predict_false(wg_session_hit_limits(wgs))) {
3558 WG_TRACE("stable session hit limits");
3559 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
3560 goto next1;
3561 }
3562 wg_send_data_msg(wgp, wgs, m);
3563 m = NULL; /* consumed */
3564 next1: wg_put_session(wgs, &psref);
3565 next0: m_freem(m);
3566 /* XXX Yield to avoid userland starvation? */
3567 }
3568 }
3569
3570 static void
3571 wg_purge_pending_packets(struct wg_peer *wgp)
3572 {
3573 struct mbuf *m;
3574
3575 m = atomic_swap_ptr(&wgp->wgp_pending, NULL);
3576 m_freem(m);
3577 pktq_barrier(wg_pktq);
3578 }
3579
3580 static void
3581 wg_handshake_timeout_timer(void *arg)
3582 {
3583 struct wg_peer *wgp = arg;
3584
3585 WG_TRACE("enter");
3586
3587 wg_schedule_peer_task(wgp, WGP_TASK_RETRY_HANDSHAKE);
3588 }
3589
3590 static struct wg_peer *
3591 wg_alloc_peer(struct wg_softc *wg)
3592 {
3593 struct wg_peer *wgp;
3594
3595 wgp = kmem_zalloc(sizeof(*wgp), KM_SLEEP);
3596
3597 wgp->wgp_sc = wg;
3598 callout_init(&wgp->wgp_handshake_timeout_timer, CALLOUT_MPSAFE);
3599 callout_setfunc(&wgp->wgp_handshake_timeout_timer,
3600 wg_handshake_timeout_timer, wgp);
3601 callout_init(&wgp->wgp_session_dtor_timer, CALLOUT_MPSAFE);
3602 callout_setfunc(&wgp->wgp_session_dtor_timer,
3603 wg_session_dtor_timer, wgp);
3604 PSLIST_ENTRY_INIT(wgp, wgp_peerlist_entry);
3605 wgp->wgp_endpoint_changing = false;
3606 wgp->wgp_endpoint_available = false;
3607 wgp->wgp_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
3608 wgp->wgp_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
3609 wgp->wgp_psz = pserialize_create();
3610 psref_target_init(&wgp->wgp_psref, wg_psref_class);
3611
3612 wgp->wgp_endpoint = kmem_zalloc(sizeof(*wgp->wgp_endpoint), KM_SLEEP);
3613 wgp->wgp_endpoint0 = kmem_zalloc(sizeof(*wgp->wgp_endpoint0), KM_SLEEP);
3614 psref_target_init(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
3615 psref_target_init(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
3616
3617 struct wg_session *wgs;
3618 wgp->wgp_session_stable =
3619 kmem_zalloc(sizeof(*wgp->wgp_session_stable), KM_SLEEP);
3620 wgp->wgp_session_unstable =
3621 kmem_zalloc(sizeof(*wgp->wgp_session_unstable), KM_SLEEP);
3622 wgs = wgp->wgp_session_stable;
3623 wgs->wgs_peer = wgp;
3624 wgs->wgs_state = WGS_STATE_UNKNOWN;
3625 psref_target_init(&wgs->wgs_psref, wg_psref_class);
3626 #ifndef __HAVE_ATOMIC64_LOADSTORE
3627 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
3628 #endif
3629 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
3630 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
3631
3632 wgs = wgp->wgp_session_unstable;
3633 wgs->wgs_peer = wgp;
3634 wgs->wgs_state = WGS_STATE_UNKNOWN;
3635 psref_target_init(&wgs->wgs_psref, wg_psref_class);
3636 #ifndef __HAVE_ATOMIC64_LOADSTORE
3637 mutex_init(&wgs->wgs_send_counter_lock, MUTEX_DEFAULT, IPL_SOFTNET);
3638 #endif
3639 wgs->wgs_recvwin = kmem_zalloc(sizeof(*wgs->wgs_recvwin), KM_SLEEP);
3640 mutex_init(&wgs->wgs_recvwin->lock, MUTEX_DEFAULT, IPL_SOFTNET);
3641
3642 return wgp;
3643 }
3644
3645 static void
3646 wg_destroy_peer(struct wg_peer *wgp)
3647 {
3648 struct wg_session *wgs;
3649 struct wg_softc *wg = wgp->wgp_sc;
3650
3651 /* Prevent new packets from this peer on any source address. */
3652 rw_enter(wg->wg_rwlock, RW_WRITER);
3653 for (int i = 0; i < wgp->wgp_n_allowedips; i++) {
3654 struct wg_allowedip *wga = &wgp->wgp_allowedips[i];
3655 struct radix_node_head *rnh = wg_rnh(wg, wga->wga_family);
3656 struct radix_node *rn;
3657
3658 KASSERT(rnh != NULL);
3659 rn = rnh->rnh_deladdr(&wga->wga_sa_addr,
3660 &wga->wga_sa_mask, rnh);
3661 if (rn == NULL) {
3662 char addrstr[128];
3663 sockaddr_format(&wga->wga_sa_addr, addrstr,
3664 sizeof(addrstr));
3665 WGLOG(LOG_WARNING, "%s: Couldn't delete %s",
3666 if_name(&wg->wg_if), addrstr);
3667 }
3668 }
3669 rw_exit(wg->wg_rwlock);
3670
3671 /* Purge pending packets. */
3672 wg_purge_pending_packets(wgp);
3673
3674 /* Halt all packet processing and timeouts. */
3675 callout_halt(&wgp->wgp_handshake_timeout_timer, NULL);
3676 callout_halt(&wgp->wgp_session_dtor_timer, NULL);
3677
3678 /* Wait for any queued work to complete. */
3679 workqueue_wait(wg_wq, &wgp->wgp_work);
3680
3681 wgs = wgp->wgp_session_unstable;
3682 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
3683 mutex_enter(wgp->wgp_lock);
3684 wg_destroy_session(wg, wgs);
3685 mutex_exit(wgp->wgp_lock);
3686 }
3687 mutex_destroy(&wgs->wgs_recvwin->lock);
3688 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
3689 #ifndef __HAVE_ATOMIC64_LOADSTORE
3690 mutex_destroy(&wgs->wgs_send_counter_lock);
3691 #endif
3692 kmem_free(wgs, sizeof(*wgs));
3693
3694 wgs = wgp->wgp_session_stable;
3695 if (wgs->wgs_state != WGS_STATE_UNKNOWN) {
3696 mutex_enter(wgp->wgp_lock);
3697 wg_destroy_session(wg, wgs);
3698 mutex_exit(wgp->wgp_lock);
3699 }
3700 mutex_destroy(&wgs->wgs_recvwin->lock);
3701 kmem_free(wgs->wgs_recvwin, sizeof(*wgs->wgs_recvwin));
3702 #ifndef __HAVE_ATOMIC64_LOADSTORE
3703 mutex_destroy(&wgs->wgs_send_counter_lock);
3704 #endif
3705 kmem_free(wgs, sizeof(*wgs));
3706
3707 psref_target_destroy(&wgp->wgp_endpoint->wgsa_psref, wg_psref_class);
3708 psref_target_destroy(&wgp->wgp_endpoint0->wgsa_psref, wg_psref_class);
3709 kmem_free(wgp->wgp_endpoint, sizeof(*wgp->wgp_endpoint));
3710 kmem_free(wgp->wgp_endpoint0, sizeof(*wgp->wgp_endpoint0));
3711
3712 pserialize_destroy(wgp->wgp_psz);
3713 mutex_obj_free(wgp->wgp_intr_lock);
3714 mutex_obj_free(wgp->wgp_lock);
3715
3716 kmem_free(wgp, sizeof(*wgp));
3717 }
3718
3719 static void
3720 wg_destroy_all_peers(struct wg_softc *wg)
3721 {
3722 struct wg_peer *wgp, *wgp0 __diagused;
3723 void *garbage_byname, *garbage_bypubkey;
3724
3725 restart:
3726 garbage_byname = garbage_bypubkey = NULL;
3727 mutex_enter(wg->wg_lock);
3728 WG_PEER_WRITER_FOREACH(wgp, wg) {
3729 if (wgp->wgp_name[0]) {
3730 wgp0 = thmap_del(wg->wg_peers_byname, wgp->wgp_name,
3731 strlen(wgp->wgp_name));
3732 KASSERT(wgp0 == wgp);
3733 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
3734 }
3735 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
3736 sizeof(wgp->wgp_pubkey));
3737 KASSERT(wgp0 == wgp);
3738 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
3739 WG_PEER_WRITER_REMOVE(wgp);
3740 wg->wg_npeers--;
3741 mutex_enter(wgp->wgp_lock);
3742 pserialize_perform(wgp->wgp_psz);
3743 mutex_exit(wgp->wgp_lock);
3744 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
3745 break;
3746 }
3747 mutex_exit(wg->wg_lock);
3748
3749 if (wgp == NULL)
3750 return;
3751
3752 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
3753
3754 wg_destroy_peer(wgp);
3755 thmap_gc(wg->wg_peers_byname, garbage_byname);
3756 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
3757
3758 goto restart;
3759 }
3760
3761 static int
3762 wg_destroy_peer_name(struct wg_softc *wg, const char *name)
3763 {
3764 struct wg_peer *wgp, *wgp0 __diagused;
3765 void *garbage_byname, *garbage_bypubkey;
3766
3767 mutex_enter(wg->wg_lock);
3768 wgp = thmap_del(wg->wg_peers_byname, name, strlen(name));
3769 if (wgp != NULL) {
3770 wgp0 = thmap_del(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
3771 sizeof(wgp->wgp_pubkey));
3772 KASSERT(wgp0 == wgp);
3773 garbage_byname = thmap_stage_gc(wg->wg_peers_byname);
3774 garbage_bypubkey = thmap_stage_gc(wg->wg_peers_bypubkey);
3775 WG_PEER_WRITER_REMOVE(wgp);
3776 wg->wg_npeers--;
3777 if (wg->wg_npeers == 0)
3778 if_link_state_change(&wg->wg_if, LINK_STATE_DOWN);
3779 mutex_enter(wgp->wgp_lock);
3780 pserialize_perform(wgp->wgp_psz);
3781 mutex_exit(wgp->wgp_lock);
3782 PSLIST_ENTRY_DESTROY(wgp, wgp_peerlist_entry);
3783 }
3784 mutex_exit(wg->wg_lock);
3785
3786 if (wgp == NULL)
3787 return ENOENT;
3788
3789 psref_target_destroy(&wgp->wgp_psref, wg_psref_class);
3790
3791 wg_destroy_peer(wgp);
3792 thmap_gc(wg->wg_peers_byname, garbage_byname);
3793 thmap_gc(wg->wg_peers_bypubkey, garbage_bypubkey);
3794
3795 return 0;
3796 }
3797
3798 static int
3799 wg_if_attach(struct wg_softc *wg)
3800 {
3801
3802 wg->wg_if.if_addrlen = 0;
3803 wg->wg_if.if_mtu = WG_MTU;
3804 wg->wg_if.if_flags = IFF_MULTICAST;
3805 wg->wg_if.if_extflags = IFEF_MPSAFE;
3806 wg->wg_if.if_ioctl = wg_ioctl;
3807 wg->wg_if.if_output = wg_output;
3808 wg->wg_if.if_init = wg_init;
3809 #ifdef ALTQ
3810 wg->wg_if.if_start = wg_start;
3811 #endif
3812 wg->wg_if.if_stop = wg_stop;
3813 wg->wg_if.if_type = IFT_OTHER;
3814 wg->wg_if.if_dlt = DLT_NULL;
3815 wg->wg_if.if_softc = wg;
3816 #ifdef ALTQ
3817 IFQ_SET_READY(&wg->wg_if.if_snd);
3818 #endif
3819 if_initialize(&wg->wg_if);
3820
3821 wg->wg_if.if_link_state = LINK_STATE_DOWN;
3822 if_alloc_sadl(&wg->wg_if);
3823 if_register(&wg->wg_if);
3824
3825 bpf_attach(&wg->wg_if, DLT_NULL, sizeof(uint32_t));
3826
3827 return 0;
3828 }
3829
3830 static void
3831 wg_if_detach(struct wg_softc *wg)
3832 {
3833 struct ifnet *ifp = &wg->wg_if;
3834
3835 bpf_detach(ifp);
3836 if_detach(ifp);
3837 }
3838
3839 static int
3840 wg_clone_create(struct if_clone *ifc, int unit)
3841 {
3842 struct wg_softc *wg;
3843 int error;
3844
3845 wg_guarantee_initialized();
3846
3847 error = wg_count_inc();
3848 if (error)
3849 return error;
3850
3851 wg = kmem_zalloc(sizeof(*wg), KM_SLEEP);
3852
3853 if_initname(&wg->wg_if, ifc->ifc_name, unit);
3854
3855 PSLIST_INIT(&wg->wg_peers);
3856 wg->wg_peers_bypubkey = thmap_create(0, NULL, THMAP_NOCOPY);
3857 wg->wg_peers_byname = thmap_create(0, NULL, THMAP_NOCOPY);
3858 wg->wg_sessions_byindex = thmap_create(0, NULL, THMAP_NOCOPY);
3859 wg->wg_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
3860 wg->wg_intr_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SOFTNET);
3861 wg->wg_rwlock = rw_obj_alloc();
3862 threadpool_job_init(&wg->wg_job, wg_job, wg->wg_intr_lock,
3863 "%s", if_name(&wg->wg_if));
3864 wg->wg_ops = &wg_ops_rumpkernel;
3865
3866 error = threadpool_get(&wg->wg_threadpool, PRI_NONE);
3867 if (error)
3868 goto fail0;
3869
3870 #ifdef INET
3871 error = wg_socreate(wg, AF_INET, &wg->wg_so4);
3872 if (error)
3873 goto fail1;
3874 rn_inithead((void **)&wg->wg_rtable_ipv4,
3875 offsetof(struct sockaddr_in, sin_addr) * NBBY);
3876 #endif
3877 #ifdef INET6
3878 error = wg_socreate(wg, AF_INET6, &wg->wg_so6);
3879 if (error)
3880 goto fail2;
3881 rn_inithead((void **)&wg->wg_rtable_ipv6,
3882 offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
3883 #endif
3884
3885 error = wg_if_attach(wg);
3886 if (error)
3887 goto fail3;
3888
3889 return 0;
3890
3891 fail4: __unused
3892 wg_if_detach(wg);
3893 fail3: wg_destroy_all_peers(wg);
3894 #ifdef INET6
3895 solock(wg->wg_so6);
3896 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
3897 sounlock(wg->wg_so6);
3898 #endif
3899 #ifdef INET
3900 solock(wg->wg_so4);
3901 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
3902 sounlock(wg->wg_so4);
3903 #endif
3904 mutex_enter(wg->wg_intr_lock);
3905 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
3906 mutex_exit(wg->wg_intr_lock);
3907 #ifdef INET6
3908 if (wg->wg_rtable_ipv6 != NULL)
3909 free(wg->wg_rtable_ipv6, M_RTABLE);
3910 soclose(wg->wg_so6);
3911 fail2:
3912 #endif
3913 #ifdef INET
3914 if (wg->wg_rtable_ipv4 != NULL)
3915 free(wg->wg_rtable_ipv4, M_RTABLE);
3916 soclose(wg->wg_so4);
3917 fail1:
3918 #endif
3919 threadpool_put(wg->wg_threadpool, PRI_NONE);
3920 fail0: threadpool_job_destroy(&wg->wg_job);
3921 rw_obj_free(wg->wg_rwlock);
3922 mutex_obj_free(wg->wg_intr_lock);
3923 mutex_obj_free(wg->wg_lock);
3924 thmap_destroy(wg->wg_sessions_byindex);
3925 thmap_destroy(wg->wg_peers_byname);
3926 thmap_destroy(wg->wg_peers_bypubkey);
3927 PSLIST_DESTROY(&wg->wg_peers);
3928 kmem_free(wg, sizeof(*wg));
3929 wg_count_dec();
3930 return error;
3931 }
3932
3933 static int
3934 wg_clone_destroy(struct ifnet *ifp)
3935 {
3936 struct wg_softc *wg = container_of(ifp, struct wg_softc, wg_if);
3937
3938 #ifdef WG_RUMPKERNEL
3939 if (wg_user_mode(wg)) {
3940 rumpuser_wg_destroy(wg->wg_user);
3941 wg->wg_user = NULL;
3942 }
3943 #endif
3944
3945 wg_if_detach(wg);
3946 wg_destroy_all_peers(wg);
3947 #ifdef INET6
3948 solock(wg->wg_so6);
3949 wg->wg_so6->so_rcv.sb_flags &= ~SB_UPCALL;
3950 sounlock(wg->wg_so6);
3951 #endif
3952 #ifdef INET
3953 solock(wg->wg_so4);
3954 wg->wg_so4->so_rcv.sb_flags &= ~SB_UPCALL;
3955 sounlock(wg->wg_so4);
3956 #endif
3957 mutex_enter(wg->wg_intr_lock);
3958 threadpool_cancel_job(wg->wg_threadpool, &wg->wg_job);
3959 mutex_exit(wg->wg_intr_lock);
3960 #ifdef INET6
3961 if (wg->wg_rtable_ipv6 != NULL)
3962 free(wg->wg_rtable_ipv6, M_RTABLE);
3963 soclose(wg->wg_so6);
3964 #endif
3965 #ifdef INET
3966 if (wg->wg_rtable_ipv4 != NULL)
3967 free(wg->wg_rtable_ipv4, M_RTABLE);
3968 soclose(wg->wg_so4);
3969 #endif
3970 threadpool_put(wg->wg_threadpool, PRI_NONE);
3971 threadpool_job_destroy(&wg->wg_job);
3972 rw_obj_free(wg->wg_rwlock);
3973 mutex_obj_free(wg->wg_intr_lock);
3974 mutex_obj_free(wg->wg_lock);
3975 thmap_destroy(wg->wg_sessions_byindex);
3976 thmap_destroy(wg->wg_peers_byname);
3977 thmap_destroy(wg->wg_peers_bypubkey);
3978 PSLIST_DESTROY(&wg->wg_peers);
3979 kmem_free(wg, sizeof(*wg));
3980 wg_count_dec();
3981
3982 return 0;
3983 }
3984
3985 static struct wg_peer *
3986 wg_pick_peer_by_sa(struct wg_softc *wg, const struct sockaddr *sa,
3987 struct psref *psref)
3988 {
3989 struct radix_node_head *rnh;
3990 struct radix_node *rn;
3991 struct wg_peer *wgp = NULL;
3992 struct wg_allowedip *wga;
3993
3994 #ifdef WG_DEBUG_LOG
3995 char addrstr[128];
3996 sockaddr_format(sa, addrstr, sizeof(addrstr));
3997 WG_DLOG("sa=%s\n", addrstr);
3998 #endif
3999
4000 rw_enter(wg->wg_rwlock, RW_READER);
4001
4002 rnh = wg_rnh(wg, sa->sa_family);
4003 if (rnh == NULL)
4004 goto out;
4005
4006 rn = rnh->rnh_matchaddr(sa, rnh);
4007 if (rn == NULL || (rn->rn_flags & RNF_ROOT) != 0)
4008 goto out;
4009
4010 WG_TRACE("success");
4011
4012 wga = container_of(rn, struct wg_allowedip, wga_nodes[0]);
4013 wgp = wga->wga_peer;
4014 wg_get_peer(wgp, psref);
4015
4016 out:
4017 rw_exit(wg->wg_rwlock);
4018 return wgp;
4019 }
4020
4021 static void
4022 wg_fill_msg_data(struct wg_softc *wg, struct wg_peer *wgp,
4023 struct wg_session *wgs, struct wg_msg_data *wgmd)
4024 {
4025
4026 memset(wgmd, 0, sizeof(*wgmd));
4027 wgmd->wgmd_type = htole32(WG_MSG_TYPE_DATA);
4028 wgmd->wgmd_receiver = wgs->wgs_remote_index;
4029 /* [W] 5.4.6: msg.counter := Nm^send */
4030 /* [W] 5.4.6: Nm^send := Nm^send + 1 */
4031 wgmd->wgmd_counter = htole64(wg_session_inc_send_counter(wgs));
4032 WG_DLOG("counter=%"PRIu64"\n", le64toh(wgmd->wgmd_counter));
4033 }
4034
4035 static int
4036 wg_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
4037 const struct rtentry *rt)
4038 {
4039 struct wg_softc *wg = ifp->if_softc;
4040 struct wg_peer *wgp = NULL;
4041 struct wg_session *wgs = NULL;
4042 struct psref wgp_psref, wgs_psref;
4043 int bound;
4044 int error;
4045
4046 bound = curlwp_bind();
4047
4048 /* TODO make the nest limit configurable via sysctl */
4049 error = if_tunnel_check_nesting(ifp, m, 1);
4050 if (error) {
4051 WGLOG(LOG_ERR,
4052 "%s: tunneling loop detected and packet dropped\n",
4053 if_name(&wg->wg_if));
4054 goto out0;
4055 }
4056
4057 #ifdef ALTQ
4058 bool altq = atomic_load_relaxed(&ifp->if_snd.altq_flags)
4059 & ALTQF_ENABLED;
4060 if (altq)
4061 IFQ_CLASSIFY(&ifp->if_snd, m, dst->sa_family);
4062 #endif
4063
4064 bpf_mtap_af(ifp, dst->sa_family, m, BPF_D_OUT);
4065
4066 m->m_flags &= ~(M_BCAST|M_MCAST);
4067
4068 wgp = wg_pick_peer_by_sa(wg, dst, &wgp_psref);
4069 if (wgp == NULL) {
4070 WG_TRACE("peer not found");
4071 error = EHOSTUNREACH;
4072 goto out0;
4073 }
4074
4075 /* Clear checksum-offload flags. */
4076 m->m_pkthdr.csum_flags = 0;
4077 m->m_pkthdr.csum_data = 0;
4078
4079 /* Check whether there's an established session. */
4080 wgs = wg_get_stable_session(wgp, &wgs_psref);
4081 if (wgs == NULL) {
4082 /*
4083 * No established session. If we're the first to try
4084 * sending data, schedule a handshake and queue the
4085 * packet for when the handshake is done; otherwise
4086 * just drop the packet and let the ongoing handshake
4087 * attempt continue. We could queue more data packets
4088 * but it's not clear that's worthwhile.
4089 */
4090 if (atomic_cas_ptr(&wgp->wgp_pending, NULL, m) == NULL) {
4091 m = NULL; /* consume */
4092 WG_TRACE("queued first packet; init handshake");
4093 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4094 } else {
4095 WG_TRACE("first packet already queued, dropping");
4096 }
4097 goto out1;
4098 }
4099
4100 /* There's an established session. Toss it in the queue. */
4101 #ifdef ALTQ
4102 if (altq) {
4103 mutex_enter(ifp->if_snd.ifq_lock);
4104 if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
4105 M_SETCTX(m, wgp);
4106 ALTQ_ENQUEUE(&ifp->if_snd, m, error);
4107 m = NULL; /* consume */
4108 }
4109 mutex_exit(ifp->if_snd.ifq_lock);
4110 if (m == NULL) {
4111 wg_start(ifp);
4112 goto out2;
4113 }
4114 }
4115 #endif
4116 kpreempt_disable();
4117 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
4118 M_SETCTX(m, wgp);
4119 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
4120 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
4121 if_name(&wg->wg_if));
4122 error = ENOBUFS;
4123 goto out3;
4124 }
4125 m = NULL; /* consumed */
4126 error = 0;
4127 out3: kpreempt_enable();
4128
4129 #ifdef ALTQ
4130 out2:
4131 #endif
4132 wg_put_session(wgs, &wgs_psref);
4133 out1: wg_put_peer(wgp, &wgp_psref);
4134 out0: m_freem(m);
4135 curlwp_bindx(bound);
4136 return error;
4137 }
4138
4139 static int
4140 wg_send_udp(struct wg_peer *wgp, struct mbuf *m)
4141 {
4142 struct psref psref;
4143 struct wg_sockaddr *wgsa;
4144 int error;
4145 struct socket *so;
4146
4147 wgsa = wg_get_endpoint_sa(wgp, &psref);
4148 so = wg_get_so_by_peer(wgp, wgsa);
4149 solock(so);
4150 if (wgsatosa(wgsa)->sa_family == AF_INET) {
4151 error = udp_send(so, m, wgsatosa(wgsa), NULL, curlwp);
4152 } else {
4153 #ifdef INET6
4154 error = udp6_output(sotoinpcb(so), m, wgsatosin6(wgsa),
4155 NULL, curlwp);
4156 #else
4157 m_freem(m);
4158 error = EPFNOSUPPORT;
4159 #endif
4160 }
4161 sounlock(so);
4162 wg_put_sa(wgp, wgsa, &psref);
4163
4164 return error;
4165 }
4166
4167 /* Inspired by pppoe_get_mbuf */
4168 static struct mbuf *
4169 wg_get_mbuf(size_t leading_len, size_t len)
4170 {
4171 struct mbuf *m;
4172
4173 KASSERT(leading_len <= MCLBYTES);
4174 KASSERT(len <= MCLBYTES - leading_len);
4175
4176 m = m_gethdr(M_DONTWAIT, MT_DATA);
4177 if (m == NULL)
4178 return NULL;
4179 if (len + leading_len > MHLEN) {
4180 m_clget(m, M_DONTWAIT);
4181 if ((m->m_flags & M_EXT) == 0) {
4182 m_free(m);
4183 return NULL;
4184 }
4185 }
4186 m->m_data += leading_len;
4187 m->m_pkthdr.len = m->m_len = len;
4188
4189 return m;
4190 }
4191
4192 static int
4193 wg_send_data_msg(struct wg_peer *wgp, struct wg_session *wgs,
4194 struct mbuf *m)
4195 {
4196 struct wg_softc *wg = wgp->wgp_sc;
4197 int error;
4198 size_t inner_len, padded_len, encrypted_len;
4199 char *padded_buf = NULL;
4200 size_t mlen;
4201 struct wg_msg_data *wgmd;
4202 bool free_padded_buf = false;
4203 struct mbuf *n;
4204 size_t leading_len = max_hdr + sizeof(struct udphdr);
4205
4206 mlen = m_length(m);
4207 inner_len = mlen;
4208 padded_len = roundup(mlen, 16);
4209 encrypted_len = padded_len + WG_AUTHTAG_LEN;
4210 WG_DLOG("inner=%zu, padded=%zu, encrypted_len=%zu\n",
4211 inner_len, padded_len, encrypted_len);
4212 if (mlen != 0) {
4213 bool success;
4214 success = m_ensure_contig(&m, padded_len);
4215 if (success) {
4216 padded_buf = mtod(m, char *);
4217 } else {
4218 padded_buf = kmem_intr_alloc(padded_len, KM_NOSLEEP);
4219 if (padded_buf == NULL) {
4220 error = ENOBUFS;
4221 goto end;
4222 }
4223 free_padded_buf = true;
4224 m_copydata(m, 0, mlen, padded_buf);
4225 }
4226 memset(padded_buf + mlen, 0, padded_len - inner_len);
4227 }
4228
4229 n = wg_get_mbuf(leading_len, sizeof(*wgmd) + encrypted_len);
4230 if (n == NULL) {
4231 error = ENOBUFS;
4232 goto end;
4233 }
4234 KASSERT(n->m_len >= sizeof(*wgmd));
4235 wgmd = mtod(n, struct wg_msg_data *);
4236 wg_fill_msg_data(wg, wgp, wgs, wgmd);
4237 #ifdef WG_DEBUG_PACKET
4238 if (wg_debug & WG_DEBUG_FLAGS_PACKET) {
4239 hexdump(printf, "padded_buf", padded_buf,
4240 padded_len);
4241 }
4242 #endif
4243 /* [W] 5.4.6: AEAD(Tm^send, Nm^send, P, e) */
4244 wg_algo_aead_enc((char *)wgmd + sizeof(*wgmd), encrypted_len,
4245 wgs->wgs_tkey_send, le64toh(wgmd->wgmd_counter),
4246 padded_buf, padded_len,
4247 NULL, 0);
4248 #ifdef WG_DEBUG_PACKET
4249 if (wg_debug & WG_DEBUG_FLAGS_PACKET) {
4250 hexdump(printf, "tkey_send", wgs->wgs_tkey_send,
4251 sizeof(wgs->wgs_tkey_send));
4252 hexdump(printf, "wgmd", wgmd, sizeof(*wgmd));
4253 hexdump(printf, "outgoing packet",
4254 (char *)wgmd + sizeof(*wgmd), encrypted_len);
4255 size_t decrypted_len = encrypted_len - WG_AUTHTAG_LEN;
4256 char *decrypted_buf = kmem_intr_alloc((decrypted_len +
4257 WG_AUTHTAG_LEN/*XXX*/), KM_NOSLEEP);
4258 if (decrypted_buf != NULL) {
4259 error = wg_algo_aead_dec(
4260 1 + decrypted_buf /* force misalignment */,
4261 encrypted_len - WG_AUTHTAG_LEN /* XXX */,
4262 wgs->wgs_tkey_send, le64toh(wgmd->wgmd_counter),
4263 (char *)wgmd + sizeof(*wgmd), encrypted_len,
4264 NULL, 0);
4265 if (error) {
4266 WG_DLOG("wg_algo_aead_dec failed: %d\n",
4267 error);
4268 }
4269 if (!consttime_memequal(1 + decrypted_buf,
4270 (char *)wgmd + sizeof(*wgmd),
4271 decrypted_len)) {
4272 WG_DLOG("wg_algo_aead_dec returned garbage\n");
4273 }
4274 kmem_intr_free(decrypted_buf, (decrypted_len +
4275 WG_AUTHTAG_LEN/*XXX*/));
4276 }
4277 }
4278 #endif
4279
4280 error = wg->wg_ops->send_data_msg(wgp, n);
4281 if (error == 0) {
4282 struct ifnet *ifp = &wg->wg_if;
4283 if_statadd(ifp, if_obytes, mlen);
4284 if_statinc(ifp, if_opackets);
4285 if (wgs->wgs_is_initiator &&
4286 ((time_uptime - wgs->wgs_time_established) >=
4287 wg_rekey_after_time)) {
4288 /*
4289 * [W] 6.2 Transport Message Limits
4290 * "if a peer is the initiator of a current secure
4291 * session, WireGuard will send a handshake initiation
4292 * message to begin a new secure session if, after
4293 * transmitting a transport data message, the current
4294 * secure session is REKEY-AFTER-TIME seconds old,"
4295 */
4296 WG_TRACE("rekey after time");
4297 atomic_store_relaxed(&wgp->wgp_force_rekey, 1);
4298 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4299 }
4300 wgs->wgs_time_last_data_sent = time_uptime;
4301 if (wg_session_get_send_counter(wgs) >=
4302 wg_rekey_after_messages) {
4303 /*
4304 * [W] 6.2 Transport Message Limits
4305 * "WireGuard will try to create a new session, by
4306 * sending a handshake initiation message (section
4307 * 5.4.2), after it has sent REKEY-AFTER-MESSAGES
4308 * transport data messages..."
4309 */
4310 WG_TRACE("rekey after messages");
4311 atomic_store_relaxed(&wgp->wgp_force_rekey, 1);
4312 wg_schedule_peer_task(wgp, WGP_TASK_SEND_INIT_MESSAGE);
4313 }
4314 }
4315 end:
4316 m_freem(m);
4317 if (free_padded_buf)
4318 kmem_intr_free(padded_buf, padded_len);
4319 return error;
4320 }
4321
4322 static void
4323 wg_input(struct ifnet *ifp, struct mbuf *m, const int af)
4324 {
4325 pktqueue_t *pktq;
4326 size_t pktlen;
4327
4328 KASSERT(af == AF_INET || af == AF_INET6);
4329
4330 WG_TRACE("");
4331
4332 m_set_rcvif(m, ifp);
4333 pktlen = m->m_pkthdr.len;
4334
4335 bpf_mtap_af(ifp, af, m, BPF_D_IN);
4336
4337 switch (af) {
4338 case AF_INET:
4339 pktq = ip_pktq;
4340 break;
4341 #ifdef INET6
4342 case AF_INET6:
4343 pktq = ip6_pktq;
4344 break;
4345 #endif
4346 default:
4347 panic("invalid af=%d", af);
4348 }
4349
4350 kpreempt_disable();
4351 const u_int h = curcpu()->ci_index;
4352 if (__predict_true(pktq_enqueue(pktq, m, h))) {
4353 if_statadd(ifp, if_ibytes, pktlen);
4354 if_statinc(ifp, if_ipackets);
4355 } else {
4356 m_freem(m);
4357 }
4358 kpreempt_enable();
4359 }
4360
4361 static void
4362 wg_calc_pubkey(uint8_t pubkey[WG_STATIC_KEY_LEN],
4363 const uint8_t privkey[WG_STATIC_KEY_LEN])
4364 {
4365
4366 crypto_scalarmult_base(pubkey, privkey);
4367 }
4368
4369 static int
4370 wg_rtable_add_route(struct wg_softc *wg, struct wg_allowedip *wga)
4371 {
4372 struct radix_node_head *rnh;
4373 struct radix_node *rn;
4374 int error = 0;
4375
4376 rw_enter(wg->wg_rwlock, RW_WRITER);
4377 rnh = wg_rnh(wg, wga->wga_family);
4378 KASSERT(rnh != NULL);
4379 rn = rnh->rnh_addaddr(&wga->wga_sa_addr, &wga->wga_sa_mask, rnh,
4380 wga->wga_nodes);
4381 rw_exit(wg->wg_rwlock);
4382
4383 if (rn == NULL)
4384 error = EEXIST;
4385
4386 return error;
4387 }
4388
4389 static int
4390 wg_handle_prop_peer(struct wg_softc *wg, prop_dictionary_t peer,
4391 struct wg_peer **wgpp)
4392 {
4393 int error = 0;
4394 const void *pubkey;
4395 size_t pubkey_len;
4396 const void *psk;
4397 size_t psk_len;
4398 const char *name = NULL;
4399
4400 if (prop_dictionary_get_string(peer, "name", &name)) {
4401 if (strlen(name) > WG_PEER_NAME_MAXLEN) {
4402 error = EINVAL;
4403 goto out;
4404 }
4405 }
4406
4407 if (!prop_dictionary_get_data(peer, "public_key",
4408 &pubkey, &pubkey_len)) {
4409 error = EINVAL;
4410 goto out;
4411 }
4412 #ifdef WG_DEBUG_DUMP
4413 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4414 char *hex = gethexdump(pubkey, pubkey_len);
4415 log(LOG_DEBUG, "pubkey=%p, pubkey_len=%zu\n%s\n",
4416 pubkey, pubkey_len, hex);
4417 puthexdump(hex, pubkey, pubkey_len);
4418 }
4419 #endif
4420
4421 struct wg_peer *wgp = wg_alloc_peer(wg);
4422 memcpy(wgp->wgp_pubkey, pubkey, sizeof(wgp->wgp_pubkey));
4423 if (name != NULL)
4424 strncpy(wgp->wgp_name, name, sizeof(wgp->wgp_name));
4425
4426 if (prop_dictionary_get_data(peer, "preshared_key", &psk, &psk_len)) {
4427 if (psk_len != sizeof(wgp->wgp_psk)) {
4428 error = EINVAL;
4429 goto out;
4430 }
4431 memcpy(wgp->wgp_psk, psk, sizeof(wgp->wgp_psk));
4432 }
4433
4434 const void *addr;
4435 size_t addr_len;
4436 struct wg_sockaddr *wgsa = wgp->wgp_endpoint;
4437
4438 if (!prop_dictionary_get_data(peer, "endpoint", &addr, &addr_len))
4439 goto skip_endpoint;
4440 if (addr_len < sizeof(*wgsatosa(wgsa)) ||
4441 addr_len > sizeof(*wgsatoss(wgsa))) {
4442 error = EINVAL;
4443 goto out;
4444 }
4445 memcpy(wgsatoss(wgsa), addr, addr_len);
4446 switch (wgsa_family(wgsa)) {
4447 case AF_INET:
4448 #ifdef INET6
4449 case AF_INET6:
4450 #endif
4451 break;
4452 default:
4453 error = EPFNOSUPPORT;
4454 goto out;
4455 }
4456 if (addr_len != sockaddr_getsize_by_family(wgsa_family(wgsa))) {
4457 error = EINVAL;
4458 goto out;
4459 }
4460 {
4461 char addrstr[128];
4462 sockaddr_format(wgsatosa(wgsa), addrstr, sizeof(addrstr));
4463 WG_DLOG("addr=%s\n", addrstr);
4464 }
4465 wgp->wgp_endpoint_available = true;
4466
4467 prop_array_t allowedips;
4468 skip_endpoint:
4469 allowedips = prop_dictionary_get(peer, "allowedips");
4470 if (allowedips == NULL)
4471 goto skip;
4472
4473 prop_object_iterator_t _it = prop_array_iterator(allowedips);
4474 prop_dictionary_t prop_allowedip;
4475 int j = 0;
4476 while ((prop_allowedip = prop_object_iterator_next(_it)) != NULL) {
4477 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
4478
4479 if (!prop_dictionary_get_int(prop_allowedip, "family",
4480 &wga->wga_family))
4481 continue;
4482 if (!prop_dictionary_get_data(prop_allowedip, "ip",
4483 &addr, &addr_len))
4484 continue;
4485 if (!prop_dictionary_get_uint8(prop_allowedip, "cidr",
4486 &wga->wga_cidr))
4487 continue;
4488
4489 switch (wga->wga_family) {
4490 case AF_INET: {
4491 struct sockaddr_in sin;
4492 char addrstr[128];
4493 struct in_addr mask;
4494 struct sockaddr_in sin_mask;
4495
4496 if (addr_len != sizeof(struct in_addr))
4497 return EINVAL;
4498 memcpy(&wga->wga_addr4, addr, addr_len);
4499
4500 sockaddr_in_init(&sin, (const struct in_addr *)addr,
4501 0);
4502 sockaddr_copy(&wga->wga_sa_addr,
4503 sizeof(sin), sintosa(&sin));
4504
4505 sockaddr_format(sintosa(&sin),
4506 addrstr, sizeof(addrstr));
4507 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4508
4509 in_len2mask(&mask, wga->wga_cidr);
4510 sockaddr_in_init(&sin_mask, &mask, 0);
4511 sockaddr_copy(&wga->wga_sa_mask,
4512 sizeof(sin_mask), sintosa(&sin_mask));
4513
4514 break;
4515 }
4516 #ifdef INET6
4517 case AF_INET6: {
4518 struct sockaddr_in6 sin6;
4519 char addrstr[128];
4520 struct in6_addr mask;
4521 struct sockaddr_in6 sin6_mask;
4522
4523 if (addr_len != sizeof(struct in6_addr))
4524 return EINVAL;
4525 memcpy(&wga->wga_addr6, addr, addr_len);
4526
4527 sockaddr_in6_init(&sin6, (const struct in6_addr *)addr,
4528 0, 0, 0);
4529 sockaddr_copy(&wga->wga_sa_addr,
4530 sizeof(sin6), sin6tosa(&sin6));
4531
4532 sockaddr_format(sin6tosa(&sin6),
4533 addrstr, sizeof(addrstr));
4534 WG_DLOG("addr=%s/%d\n", addrstr, wga->wga_cidr);
4535
4536 in6_prefixlen2mask(&mask, wga->wga_cidr);
4537 sockaddr_in6_init(&sin6_mask, &mask, 0, 0, 0);
4538 sockaddr_copy(&wga->wga_sa_mask,
4539 sizeof(sin6_mask), sin6tosa(&sin6_mask));
4540
4541 break;
4542 }
4543 #endif
4544 default:
4545 error = EINVAL;
4546 goto out;
4547 }
4548 wga->wga_peer = wgp;
4549
4550 error = wg_rtable_add_route(wg, wga);
4551 if (error != 0)
4552 goto out;
4553
4554 j++;
4555 }
4556 wgp->wgp_n_allowedips = j;
4557 skip:
4558 *wgpp = wgp;
4559 out:
4560 return error;
4561 }
4562
4563 static int
4564 wg_alloc_prop_buf(char **_buf, struct ifdrv *ifd)
4565 {
4566 int error;
4567 char *buf;
4568
4569 WG_DLOG("buf=%p, len=%zu\n", ifd->ifd_data, ifd->ifd_len);
4570 if (ifd->ifd_len >= WG_MAX_PROPLEN)
4571 return E2BIG;
4572 buf = kmem_alloc(ifd->ifd_len + 1, KM_SLEEP);
4573 error = copyin(ifd->ifd_data, buf, ifd->ifd_len);
4574 if (error != 0)
4575 return error;
4576 buf[ifd->ifd_len] = '\0';
4577 #ifdef WG_DEBUG_DUMP
4578 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4579 log(LOG_DEBUG, "%.*s\n", (int)MIN(INT_MAX, ifd->ifd_len),
4580 (const char *)buf);
4581 }
4582 #endif
4583 *_buf = buf;
4584 return 0;
4585 }
4586
4587 static int
4588 wg_ioctl_set_private_key(struct wg_softc *wg, struct ifdrv *ifd)
4589 {
4590 int error;
4591 prop_dictionary_t prop_dict;
4592 char *buf = NULL;
4593 const void *privkey;
4594 size_t privkey_len;
4595
4596 error = wg_alloc_prop_buf(&buf, ifd);
4597 if (error != 0)
4598 return error;
4599 error = EINVAL;
4600 prop_dict = prop_dictionary_internalize(buf);
4601 if (prop_dict == NULL)
4602 goto out;
4603 if (!prop_dictionary_get_data(prop_dict, "private_key",
4604 &privkey, &privkey_len))
4605 goto out;
4606 #ifdef WG_DEBUG_DUMP
4607 if (wg_debug & WG_DEBUG_FLAGS_DUMP) {
4608 char *hex = gethexdump(privkey, privkey_len);
4609 log(LOG_DEBUG, "privkey=%p, privkey_len=%zu\n%s\n",
4610 privkey, privkey_len, hex);
4611 puthexdump(hex, privkey, privkey_len);
4612 }
4613 #endif
4614 if (privkey_len != WG_STATIC_KEY_LEN)
4615 goto out;
4616 memcpy(wg->wg_privkey, privkey, WG_STATIC_KEY_LEN);
4617 wg_calc_pubkey(wg->wg_pubkey, wg->wg_privkey);
4618 error = 0;
4619
4620 out:
4621 kmem_free(buf, ifd->ifd_len + 1);
4622 return error;
4623 }
4624
4625 static int
4626 wg_ioctl_set_listen_port(struct wg_softc *wg, struct ifdrv *ifd)
4627 {
4628 int error;
4629 prop_dictionary_t prop_dict;
4630 char *buf = NULL;
4631 uint16_t port;
4632
4633 error = wg_alloc_prop_buf(&buf, ifd);
4634 if (error != 0)
4635 return error;
4636 error = EINVAL;
4637 prop_dict = prop_dictionary_internalize(buf);
4638 if (prop_dict == NULL)
4639 goto out;
4640 if (!prop_dictionary_get_uint16(prop_dict, "listen_port", &port))
4641 goto out;
4642
4643 error = wg->wg_ops->bind_port(wg, (uint16_t)port);
4644
4645 out:
4646 kmem_free(buf, ifd->ifd_len + 1);
4647 return error;
4648 }
4649
4650 static int
4651 wg_ioctl_add_peer(struct wg_softc *wg, struct ifdrv *ifd)
4652 {
4653 int error;
4654 prop_dictionary_t prop_dict;
4655 char *buf = NULL;
4656 struct wg_peer *wgp = NULL, *wgp0 __diagused;
4657
4658 error = wg_alloc_prop_buf(&buf, ifd);
4659 if (error != 0)
4660 return error;
4661 error = EINVAL;
4662 prop_dict = prop_dictionary_internalize(buf);
4663 if (prop_dict == NULL)
4664 goto out;
4665
4666 error = wg_handle_prop_peer(wg, prop_dict, &wgp);
4667 if (error != 0)
4668 goto out;
4669
4670 mutex_enter(wg->wg_lock);
4671 if (thmap_get(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4672 sizeof(wgp->wgp_pubkey)) != NULL ||
4673 (wgp->wgp_name[0] &&
4674 thmap_get(wg->wg_peers_byname, wgp->wgp_name,
4675 strlen(wgp->wgp_name)) != NULL)) {
4676 mutex_exit(wg->wg_lock);
4677 wg_destroy_peer(wgp);
4678 error = EEXIST;
4679 goto out;
4680 }
4681 wgp0 = thmap_put(wg->wg_peers_bypubkey, wgp->wgp_pubkey,
4682 sizeof(wgp->wgp_pubkey), wgp);
4683 KASSERT(wgp0 == wgp);
4684 if (wgp->wgp_name[0]) {
4685 wgp0 = thmap_put(wg->wg_peers_byname, wgp->wgp_name,
4686 strlen(wgp->wgp_name), wgp);
4687 KASSERT(wgp0 == wgp);
4688 }
4689 WG_PEER_WRITER_INSERT_HEAD(wgp, wg);
4690 wg->wg_npeers++;
4691 mutex_exit(wg->wg_lock);
4692
4693 if_link_state_change(&wg->wg_if, LINK_STATE_UP);
4694
4695 out:
4696 kmem_free(buf, ifd->ifd_len + 1);
4697 return error;
4698 }
4699
4700 static int
4701 wg_ioctl_delete_peer(struct wg_softc *wg, struct ifdrv *ifd)
4702 {
4703 int error;
4704 prop_dictionary_t prop_dict;
4705 char *buf = NULL;
4706 const char *name;
4707
4708 error = wg_alloc_prop_buf(&buf, ifd);
4709 if (error != 0)
4710 return error;
4711 error = EINVAL;
4712 prop_dict = prop_dictionary_internalize(buf);
4713 if (prop_dict == NULL)
4714 goto out;
4715
4716 if (!prop_dictionary_get_string(prop_dict, "name", &name))
4717 goto out;
4718 if (strlen(name) > WG_PEER_NAME_MAXLEN)
4719 goto out;
4720
4721 error = wg_destroy_peer_name(wg, name);
4722 out:
4723 kmem_free(buf, ifd->ifd_len + 1);
4724 return error;
4725 }
4726
4727 static bool
4728 wg_is_authorized(struct wg_softc *wg, u_long cmd)
4729 {
4730 int au = cmd == SIOCGDRVSPEC ?
4731 KAUTH_REQ_NETWORK_INTERFACE_WG_GETPRIV :
4732 KAUTH_REQ_NETWORK_INTERFACE_WG_SETPRIV;
4733 return kauth_authorize_network(kauth_cred_get(),
4734 KAUTH_NETWORK_INTERFACE_WG, au, &wg->wg_if,
4735 (void *)cmd, NULL) == 0;
4736 }
4737
4738 static int
4739 wg_ioctl_get(struct wg_softc *wg, struct ifdrv *ifd)
4740 {
4741 int error = ENOMEM;
4742 prop_dictionary_t prop_dict;
4743 prop_array_t peers = NULL;
4744 char *buf;
4745 struct wg_peer *wgp;
4746 int s, i;
4747
4748 prop_dict = prop_dictionary_create();
4749 if (prop_dict == NULL)
4750 goto error;
4751
4752 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
4753 if (!prop_dictionary_set_data(prop_dict, "private_key",
4754 wg->wg_privkey, WG_STATIC_KEY_LEN))
4755 goto error;
4756 }
4757
4758 if (wg->wg_listen_port != 0) {
4759 if (!prop_dictionary_set_uint16(prop_dict, "listen_port",
4760 wg->wg_listen_port))
4761 goto error;
4762 }
4763
4764 if (wg->wg_npeers == 0)
4765 goto skip_peers;
4766
4767 peers = prop_array_create();
4768 if (peers == NULL)
4769 goto error;
4770
4771 s = pserialize_read_enter();
4772 i = 0;
4773 WG_PEER_READER_FOREACH(wgp, wg) {
4774 struct wg_sockaddr *wgsa;
4775 struct psref wgp_psref, wgsa_psref;
4776 prop_dictionary_t prop_peer;
4777
4778 wg_get_peer(wgp, &wgp_psref);
4779 pserialize_read_exit(s);
4780
4781 prop_peer = prop_dictionary_create();
4782 if (prop_peer == NULL)
4783 goto next;
4784
4785 if (strlen(wgp->wgp_name) > 0) {
4786 if (!prop_dictionary_set_string(prop_peer, "name",
4787 wgp->wgp_name))
4788 goto next;
4789 }
4790
4791 if (!prop_dictionary_set_data(prop_peer, "public_key",
4792 wgp->wgp_pubkey, sizeof(wgp->wgp_pubkey)))
4793 goto next;
4794
4795 uint8_t psk_zero[WG_PRESHARED_KEY_LEN] = {0};
4796 if (!consttime_memequal(wgp->wgp_psk, psk_zero,
4797 sizeof(wgp->wgp_psk))) {
4798 if (wg_is_authorized(wg, SIOCGDRVSPEC)) {
4799 if (!prop_dictionary_set_data(prop_peer,
4800 "preshared_key",
4801 wgp->wgp_psk, sizeof(wgp->wgp_psk)))
4802 goto next;
4803 }
4804 }
4805
4806 wgsa = wg_get_endpoint_sa(wgp, &wgsa_psref);
4807 CTASSERT(AF_UNSPEC == 0);
4808 if (wgsa_family(wgsa) != 0 /*AF_UNSPEC*/ &&
4809 !prop_dictionary_set_data(prop_peer, "endpoint",
4810 wgsatoss(wgsa),
4811 sockaddr_getsize_by_family(wgsa_family(wgsa)))) {
4812 wg_put_sa(wgp, wgsa, &wgsa_psref);
4813 goto next;
4814 }
4815 wg_put_sa(wgp, wgsa, &wgsa_psref);
4816
4817 const struct timespec *t = &wgp->wgp_last_handshake_time;
4818
4819 if (!prop_dictionary_set_uint64(prop_peer,
4820 "last_handshake_time_sec", (uint64_t)t->tv_sec))
4821 goto next;
4822 if (!prop_dictionary_set_uint32(prop_peer,
4823 "last_handshake_time_nsec", (uint32_t)t->tv_nsec))
4824 goto next;
4825
4826 if (wgp->wgp_n_allowedips == 0)
4827 goto skip_allowedips;
4828
4829 prop_array_t allowedips = prop_array_create();
4830 if (allowedips == NULL)
4831 goto next;
4832 for (int j = 0; j < wgp->wgp_n_allowedips; j++) {
4833 struct wg_allowedip *wga = &wgp->wgp_allowedips[j];
4834 prop_dictionary_t prop_allowedip;
4835
4836 prop_allowedip = prop_dictionary_create();
4837 if (prop_allowedip == NULL)
4838 break;
4839
4840 if (!prop_dictionary_set_int(prop_allowedip, "family",
4841 wga->wga_family))
4842 goto _next;
4843 if (!prop_dictionary_set_uint8(prop_allowedip, "cidr",
4844 wga->wga_cidr))
4845 goto _next;
4846
4847 switch (wga->wga_family) {
4848 case AF_INET:
4849 if (!prop_dictionary_set_data(prop_allowedip,
4850 "ip", &wga->wga_addr4,
4851 sizeof(wga->wga_addr4)))
4852 goto _next;
4853 break;
4854 #ifdef INET6
4855 case AF_INET6:
4856 if (!prop_dictionary_set_data(prop_allowedip,
4857 "ip", &wga->wga_addr6,
4858 sizeof(wga->wga_addr6)))
4859 goto _next;
4860 break;
4861 #endif
4862 default:
4863 break;
4864 }
4865 prop_array_set(allowedips, j, prop_allowedip);
4866 _next:
4867 prop_object_release(prop_allowedip);
4868 }
4869 prop_dictionary_set(prop_peer, "allowedips", allowedips);
4870 prop_object_release(allowedips);
4871
4872 skip_allowedips:
4873
4874 prop_array_set(peers, i, prop_peer);
4875 next:
4876 if (prop_peer)
4877 prop_object_release(prop_peer);
4878 i++;
4879
4880 s = pserialize_read_enter();
4881 wg_put_peer(wgp, &wgp_psref);
4882 }
4883 pserialize_read_exit(s);
4884
4885 prop_dictionary_set(prop_dict, "peers", peers);
4886 prop_object_release(peers);
4887 peers = NULL;
4888
4889 skip_peers:
4890 buf = prop_dictionary_externalize(prop_dict);
4891 if (buf == NULL)
4892 goto error;
4893 if (ifd->ifd_len < (strlen(buf) + 1)) {
4894 error = EINVAL;
4895 goto error;
4896 }
4897 error = copyout(buf, ifd->ifd_data, strlen(buf) + 1);
4898
4899 free(buf, 0);
4900 error:
4901 if (peers != NULL)
4902 prop_object_release(peers);
4903 if (prop_dict != NULL)
4904 prop_object_release(prop_dict);
4905
4906 return error;
4907 }
4908
4909 static int
4910 wg_ioctl(struct ifnet *ifp, u_long cmd, void *data)
4911 {
4912 struct wg_softc *wg = ifp->if_softc;
4913 struct ifreq *ifr = data;
4914 struct ifaddr *ifa = data;
4915 struct ifdrv *ifd = data;
4916 int error = 0;
4917
4918 switch (cmd) {
4919 case SIOCINITIFADDR:
4920 if (ifa->ifa_addr->sa_family != AF_LINK &&
4921 (ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
4922 (IFF_UP | IFF_RUNNING)) {
4923 ifp->if_flags |= IFF_UP;
4924 error = if_init(ifp);
4925 }
4926 return error;
4927 case SIOCADDMULTI:
4928 case SIOCDELMULTI:
4929 switch (ifr->ifr_addr.sa_family) {
4930 case AF_INET: /* IP supports Multicast */
4931 break;
4932 #ifdef INET6
4933 case AF_INET6: /* IP6 supports Multicast */
4934 break;
4935 #endif
4936 default: /* Other protocols doesn't support Multicast */
4937 error = EAFNOSUPPORT;
4938 break;
4939 }
4940 return error;
4941 case SIOCSDRVSPEC:
4942 if (!wg_is_authorized(wg, cmd)) {
4943 return EPERM;
4944 }
4945 switch (ifd->ifd_cmd) {
4946 case WG_IOCTL_SET_PRIVATE_KEY:
4947 error = wg_ioctl_set_private_key(wg, ifd);
4948 break;
4949 case WG_IOCTL_SET_LISTEN_PORT:
4950 error = wg_ioctl_set_listen_port(wg, ifd);
4951 break;
4952 case WG_IOCTL_ADD_PEER:
4953 error = wg_ioctl_add_peer(wg, ifd);
4954 break;
4955 case WG_IOCTL_DELETE_PEER:
4956 error = wg_ioctl_delete_peer(wg, ifd);
4957 break;
4958 default:
4959 error = EINVAL;
4960 break;
4961 }
4962 return error;
4963 case SIOCGDRVSPEC:
4964 return wg_ioctl_get(wg, ifd);
4965 case SIOCSIFFLAGS:
4966 if ((error = ifioctl_common(ifp, cmd, data)) != 0)
4967 break;
4968 switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
4969 case IFF_RUNNING:
4970 /*
4971 * If interface is marked down and it is running,
4972 * then stop and disable it.
4973 */
4974 if_stop(ifp, 1);
4975 break;
4976 case IFF_UP:
4977 /*
4978 * If interface is marked up and it is stopped, then
4979 * start it.
4980 */
4981 error = if_init(ifp);
4982 break;
4983 default:
4984 break;
4985 }
4986 return error;
4987 #ifdef WG_RUMPKERNEL
4988 case SIOCSLINKSTR:
4989 error = wg_ioctl_linkstr(wg, ifd);
4990 if (error == 0)
4991 wg->wg_ops = &wg_ops_rumpuser;
4992 return error;
4993 #endif
4994 default:
4995 break;
4996 }
4997
4998 error = ifioctl_common(ifp, cmd, data);
4999
5000 #ifdef WG_RUMPKERNEL
5001 if (!wg_user_mode(wg))
5002 return error;
5003
5004 /* Do the same to the corresponding tun device on the host */
5005 /*
5006 * XXX Actually the command has not been handled yet. It
5007 * will be handled via pr_ioctl form doifioctl later.
5008 */
5009 switch (cmd) {
5010 case SIOCAIFADDR:
5011 case SIOCDIFADDR: {
5012 struct in_aliasreq _ifra = *(const struct in_aliasreq *)data;
5013 struct in_aliasreq *ifra = &_ifra;
5014 KASSERT(error == ENOTTY);
5015 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5016 IFNAMSIZ);
5017 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET);
5018 if (error == 0)
5019 error = ENOTTY;
5020 break;
5021 }
5022 #ifdef INET6
5023 case SIOCAIFADDR_IN6:
5024 case SIOCDIFADDR_IN6: {
5025 struct in6_aliasreq _ifra = *(const struct in6_aliasreq *)data;
5026 struct in6_aliasreq *ifra = &_ifra;
5027 KASSERT(error == ENOTTY);
5028 strncpy(ifra->ifra_name, rumpuser_wg_get_tunname(wg->wg_user),
5029 IFNAMSIZ);
5030 error = rumpuser_wg_ioctl(wg->wg_user, cmd, ifra, AF_INET6);
5031 if (error == 0)
5032 error = ENOTTY;
5033 break;
5034 }
5035 #endif
5036 }
5037 #endif /* WG_RUMPKERNEL */
5038
5039 return error;
5040 }
5041
5042 static int
5043 wg_init(struct ifnet *ifp)
5044 {
5045
5046 ifp->if_flags |= IFF_RUNNING;
5047
5048 /* TODO flush pending packets. */
5049 return 0;
5050 }
5051
5052 #ifdef ALTQ
5053 static void
5054 wg_start(struct ifnet *ifp)
5055 {
5056 struct mbuf *m;
5057
5058 for (;;) {
5059 IFQ_DEQUEUE(&ifp->if_snd, m);
5060 if (m == NULL)
5061 break;
5062
5063 kpreempt_disable();
5064 const uint32_t h = curcpu()->ci_index; // pktq_rps_hash(m)
5065 if (__predict_false(!pktq_enqueue(wg_pktq, m, h))) {
5066 WGLOG(LOG_ERR, "%s: pktq full, dropping\n",
5067 if_name(ifp));
5068 m_freem(m);
5069 }
5070 kpreempt_enable();
5071 }
5072 }
5073 #endif
5074
5075 static void
5076 wg_stop(struct ifnet *ifp, int disable)
5077 {
5078
5079 KASSERT((ifp->if_flags & IFF_RUNNING) != 0);
5080 ifp->if_flags &= ~IFF_RUNNING;
5081
5082 /* Need to do something? */
5083 }
5084
5085 #ifdef WG_DEBUG_PARAMS
5086 SYSCTL_SETUP(sysctl_net_wg_setup, "sysctl net.wg setup")
5087 {
5088 const struct sysctlnode *node = NULL;
5089
5090 sysctl_createv(clog, 0, NULL, &node,
5091 CTLFLAG_PERMANENT,
5092 CTLTYPE_NODE, "wg",
5093 SYSCTL_DESCR("wg(4)"),
5094 NULL, 0, NULL, 0,
5095 CTL_NET, CTL_CREATE, CTL_EOL);
5096 sysctl_createv(clog, 0, &node, NULL,
5097 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5098 CTLTYPE_QUAD, "rekey_after_messages",
5099 SYSCTL_DESCR("session liftime by messages"),
5100 NULL, 0, &wg_rekey_after_messages, 0, CTL_CREATE, CTL_EOL);
5101 sysctl_createv(clog, 0, &node, NULL,
5102 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5103 CTLTYPE_INT, "rekey_after_time",
5104 SYSCTL_DESCR("session liftime"),
5105 NULL, 0, &wg_rekey_after_time, 0, CTL_CREATE, CTL_EOL);
5106 sysctl_createv(clog, 0, &node, NULL,
5107 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5108 CTLTYPE_INT, "rekey_timeout",
5109 SYSCTL_DESCR("session handshake retry time"),
5110 NULL, 0, &wg_rekey_timeout, 0, CTL_CREATE, CTL_EOL);
5111 sysctl_createv(clog, 0, &node, NULL,
5112 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5113 CTLTYPE_INT, "rekey_attempt_time",
5114 SYSCTL_DESCR("session handshake timeout"),
5115 NULL, 0, &wg_rekey_attempt_time, 0, CTL_CREATE, CTL_EOL);
5116 sysctl_createv(clog, 0, &node, NULL,
5117 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5118 CTLTYPE_INT, "keepalive_timeout",
5119 SYSCTL_DESCR("keepalive timeout"),
5120 NULL, 0, &wg_keepalive_timeout, 0, CTL_CREATE, CTL_EOL);
5121 sysctl_createv(clog, 0, &node, NULL,
5122 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5123 CTLTYPE_BOOL, "force_underload",
5124 SYSCTL_DESCR("force to detemine under load"),
5125 NULL, 0, &wg_force_underload, 0, CTL_CREATE, CTL_EOL);
5126 sysctl_createv(clog, 0, &node, NULL,
5127 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
5128 CTLTYPE_INT, "debug",
5129 SYSCTL_DESCR("set debug flags 1=log 2=trace 4=dump 8=packet"),
5130 NULL, 0, &wg_debug, 0, CTL_CREATE, CTL_EOL);
5131 }
5132 #endif
5133
5134 #ifdef WG_RUMPKERNEL
5135 static bool
5136 wg_user_mode(struct wg_softc *wg)
5137 {
5138
5139 return wg->wg_user != NULL;
5140 }
5141
5142 static int
5143 wg_ioctl_linkstr(struct wg_softc *wg, struct ifdrv *ifd)
5144 {
5145 struct ifnet *ifp = &wg->wg_if;
5146 int error;
5147
5148 if (ifp->if_flags & IFF_UP)
5149 return EBUSY;
5150
5151 if (ifd->ifd_cmd == IFLINKSTR_UNSET) {
5152 /* XXX do nothing */
5153 return 0;
5154 } else if (ifd->ifd_cmd != 0) {
5155 return EINVAL;
5156 } else if (wg->wg_user != NULL) {
5157 return EBUSY;
5158 }
5159
5160 /* Assume \0 included */
5161 if (ifd->ifd_len > IFNAMSIZ) {
5162 return E2BIG;
5163 } else if (ifd->ifd_len < 1) {
5164 return EINVAL;
5165 }
5166
5167 char tun_name[IFNAMSIZ];
5168 error = copyinstr(ifd->ifd_data, tun_name, ifd->ifd_len, NULL);
5169 if (error != 0)
5170 return error;
5171
5172 if (strncmp(tun_name, "tun", 3) != 0)
5173 return EINVAL;
5174
5175 error = rumpuser_wg_create(tun_name, wg, &wg->wg_user);
5176
5177 return error;
5178 }
5179
5180 static int
5181 wg_send_user(struct wg_peer *wgp, struct mbuf *m)
5182 {
5183 int error;
5184 struct psref psref;
5185 struct wg_sockaddr *wgsa;
5186 struct wg_softc *wg = wgp->wgp_sc;
5187 struct iovec iov[1];
5188
5189 wgsa = wg_get_endpoint_sa(wgp, &psref);
5190
5191 iov[0].iov_base = mtod(m, void *);
5192 iov[0].iov_len = m->m_len;
5193
5194 /* Send messages to a peer via an ordinary socket. */
5195 error = rumpuser_wg_send_peer(wg->wg_user, wgsatosa(wgsa), iov, 1);
5196
5197 wg_put_sa(wgp, wgsa, &psref);
5198
5199 m_freem(m);
5200
5201 return error;
5202 }
5203
5204 static void
5205 wg_input_user(struct ifnet *ifp, struct mbuf *m, const int af)
5206 {
5207 struct wg_softc *wg = ifp->if_softc;
5208 struct iovec iov[2];
5209 struct sockaddr_storage ss;
5210
5211 KASSERT(af == AF_INET || af == AF_INET6);
5212
5213 WG_TRACE("");
5214
5215 if (af == AF_INET) {
5216 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
5217 struct ip *ip;
5218
5219 KASSERT(m->m_len >= sizeof(struct ip));
5220 ip = mtod(m, struct ip *);
5221 sockaddr_in_init(sin, &ip->ip_dst, 0);
5222 } else {
5223 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
5224 struct ip6_hdr *ip6;
5225
5226 KASSERT(m->m_len >= sizeof(struct ip6_hdr));
5227 ip6 = mtod(m, struct ip6_hdr *);
5228 sockaddr_in6_init(sin6, &ip6->ip6_dst, 0, 0, 0);
5229 }
5230
5231 iov[0].iov_base = &ss;
5232 iov[0].iov_len = ss.ss_len;
5233 iov[1].iov_base = mtod(m, void *);
5234 iov[1].iov_len = m->m_len;
5235
5236 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5237
5238 /* Send decrypted packets to users via a tun. */
5239 rumpuser_wg_send_user(wg->wg_user, iov, 2);
5240
5241 m_freem(m);
5242 }
5243
5244 static int
5245 wg_bind_port_user(struct wg_softc *wg, const uint16_t port)
5246 {
5247 int error;
5248 uint16_t old_port = wg->wg_listen_port;
5249
5250 if (port != 0 && old_port == port)
5251 return 0;
5252
5253 error = rumpuser_wg_sock_bind(wg->wg_user, port);
5254 if (error == 0)
5255 wg->wg_listen_port = port;
5256 return error;
5257 }
5258
5259 /*
5260 * Receive user packets.
5261 */
5262 void
5263 rumpkern_wg_recv_user(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
5264 {
5265 struct ifnet *ifp = &wg->wg_if;
5266 struct mbuf *m;
5267 const struct sockaddr *dst;
5268
5269 WG_TRACE("");
5270
5271 dst = iov[0].iov_base;
5272
5273 m = m_gethdr(M_DONTWAIT, MT_DATA);
5274 if (m == NULL)
5275 return;
5276 m->m_len = m->m_pkthdr.len = 0;
5277 m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
5278
5279 WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
5280 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5281
5282 (void)wg_output(ifp, m, dst, NULL);
5283 }
5284
5285 /*
5286 * Receive packets from a peer.
5287 */
5288 void
5289 rumpkern_wg_recv_peer(struct wg_softc *wg, struct iovec *iov, size_t iovlen)
5290 {
5291 struct mbuf *m;
5292 const struct sockaddr *src;
5293 int bound;
5294
5295 WG_TRACE("");
5296
5297 src = iov[0].iov_base;
5298
5299 m = m_gethdr(M_DONTWAIT, MT_DATA);
5300 if (m == NULL)
5301 return;
5302 m->m_len = m->m_pkthdr.len = 0;
5303 m_copyback(m, 0, iov[1].iov_len, iov[1].iov_base);
5304
5305 WG_DLOG("iov_len=%zu\n", iov[1].iov_len);
5306 WG_DUMP_BUF(iov[1].iov_base, iov[1].iov_len);
5307
5308 bound = curlwp_bind();
5309 wg_handle_packet(wg, m, src);
5310 curlwp_bindx(bound);
5311 }
5312 #endif /* WG_RUMPKERNEL */
5313
5314 /*
5315 * Module infrastructure
5316 */
5317 #include "if_module.h"
5318
5319 IF_MODULE(MODULE_CLASS_DRIVER, wg, "sodium,blake2s")
5320