Repository navigation
Expand file tree
/
Copy pathif_wg.c
More file actions
5876 lines (5099 loc) · 156 KB
/
Copy pathif_wg.c
File metadata and controls
5876 lines (5099 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $NetBSD: if_wg.c,v 1.145 2026/09/16 13:54:37 riastradh Exp $ */
/*
* Copyright (C) Ryota Ozaki <ozaki.ryota@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This network interface aims to implement the WireGuard protocol.
* The implementation is based on the paper of WireGuard as of
* 2018-06-30 [1]. The paper is referred in the source code with label
* [W]. Also the specification of the Noise protocol framework as of
* 2018-07-11 [2] is referred with label [N].
*
* [1] https://www.wireguard.com/papers/wireguard.pdf
* https://web.archive.org/web/20180805103233/https://www.wireguard.com/papers/wireguard.pdf
* [2] http://noiseprotocol.org/noise.pdf
* https://web.archive.org/web/20180727193154/https://noiseprotocol.org/noise.pdf
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: if_wg.c,v 1.145 2026/09/16 13:54:37 riastradh Exp $");
#ifdef _KERNEL_OPT
#include "opt_altq_enabled.h"
#include "opt_inet.h"
#endif
#include <sys/param.h>
#include <sys/types.h>
#include <sys/atomic.h>
#include <sys/callout.h>
#include <sys/cprng.h>
#include <sys/cpu.h>
#include <sys/device.h>
#include <sys/domain.h>
#include <sys/errno.h>
#include <sys/intr.h>
#include <sys/ioctl.h>
#include <sys/kernel.h>
#include <sys/kmem.h>
#include <sys/mbuf.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/once.h>
#include <sys/percpu.h>
#include <sys/pserialize.h>
#include <sys/psref.h>
#include <sys/queue.h>
#include <sys/rwlock.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/systm.h>
#include <sys/thmap.h>
#include <sys/threadpool.h>
#include <sys/time.h>
#include <sys/timespec.h>
#include <sys/workqueue.h>
#include <lib/libkern/libkern.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_wg.h>
#include <net/pktqueue.h>
#include <net/route.h>
#ifdef INET
#include <netinet/in.h>
#include <netinet/in_pcb.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/udp.h>
#include <netinet/udp_var.h>
#endif /* INET */
#ifdef INET6
#include <netinet/ip6.h>
#include <netinet6/in6_pcb.h>
#include <netinet6/in6_var.h>
#include <netinet6/ip6_var.h>
#include <netinet6/udp6_var.h>
#endif /* INET6 */
#include <prop/proplib.h>
#include <crypto/blake2/blake2s.h>
#include <crypto/sodium/crypto_aead_chacha20poly1305.h>
#include <crypto/sodium/crypto_aead_xchacha20poly1305.h>
#include <crypto/sodium/crypto_scalarmult.h>
#include "ioconf.h"
#ifdef WG_RUMPKERNEL
#include "wg_user.h"
#endif
#ifndef time_uptime32
#define time_uptime32 ((uint32_t)time_uptime)
#endif
/*
* Data structures
* - struct wg_softc is an instance of wg interfaces
* - It has a list of peers (struct wg_peer)
* - It has a threadpool job that sends/receives handshake messages and
* runs event handlers
* - It has its own two routing tables: one is for IPv4 and the other IPv6
* - struct wg_peer is a representative of a peer
* - It has a struct work to handle handshakes and timer tasks
* - It has a pair of session instances (struct wg_session)
* - It has a pair of endpoint instances (struct wg_sockaddr)
* - Normally one endpoint is used and the second one is used only on
* a peer migration (a change of peer's IP address)
* - It has a list of IP addresses and sub networks called allowedips
* (struct wg_allowedip)
* - A packets sent over a session is allowed if its destination matches
* any IP addresses or sub networks of the list
* - struct wg_session represents a session of a secure tunnel with a peer
* - Two instances of sessions belong to a peer; a stable session and a
* unstable session
* - A handshake process of a session always starts with a unstable instance
* - Once a session is established, its instance becomes stable and the
* other becomes unstable instead
* - Data messages are always sent via a stable session
*
* Locking notes:
* - Each wg has a mutex(9) wg_lock, and a rwlock(9) wg_rwlock
* - Changes to the peer list are serialized by wg_lock
* - The peer list may be read with pserialize(9) and psref(9)
* - The rwlock (wg_rwlock) protects the routing tables (wg_rtable_ipv[46])
* => XXX replace by pserialize when routing table is psz-safe
* - Each peer (struct wg_peer, wgp) has a mutex wgp_lock, which can be taken
* only in thread context and serializes:
* - the stable and unstable session pointers
* - all unstable session state
* - Packet processing may be done in softint context:
* - The stable session can be read under pserialize(9) or psref(9)
* - The stable session is always ESTABLISHED
* - On a session swap, we must wait for all readers to release a
* reference to a stable session before changing wgs_state and
* session states
* - Lock order: wg_lock -> wgp_lock
*/
#define WGLOG(level, fmt, args...) \
log(level, "%s: " fmt, __func__, ##args)
#define WG_DEBUG
/* Debug options */
#ifdef WG_DEBUG
/* Output debug logs */
#ifndef WG_DEBUG_LOG
#define WG_DEBUG_LOG
#endif
/* Output trace logs */
#ifndef WG_DEBUG_TRACE
#define WG_DEBUG_TRACE
#endif
/* Output hash values, etc. */
#ifndef WG_DEBUG_DUMP
#define WG_DEBUG_DUMP
#endif
/* Make some internal parameters configurable for testing and debugging */
#ifndef WG_DEBUG_PARAMS
#define WG_DEBUG_PARAMS
#endif
#endif /* WG_DEBUG */
#ifndef WG_DEBUG
# if defined(WG_DEBUG_LOG) || defined(WG_DEBUG_TRACE) || \
defined(WG_DEBUG_DUMP) || defined(WG_DEBUG_PARAMS)
# define WG_DEBUG
# endif
#endif
#ifdef WG_DEBUG
int wg_debug;
#define WG_DEBUG_FLAGS_LOG 1
#define WG_DEBUG_FLAGS_TRACE 2
#define WG_DEBUG_FLAGS_DUMP 4
#endif
#ifdef WG_DEBUG_TRACE
#define WG_TRACE(msg) do { \
if (wg_debug & WG_DEBUG_FLAGS_TRACE) \
log(LOG_DEBUG, "%s:%d: %s\n", __func__, __LINE__, (msg)); \
} while (0)
#else
#define WG_TRACE(msg) __nothing
#endif
#ifdef WG_DEBUG_LOG
#define WG_DLOG(fmt, args...) do { \
if (wg_debug & WG_DEBUG_FLAGS_LOG) \
log(LOG_DEBUG, "%s: " fmt, __func__, ##args); \
} while (0)
#else
#define WG_DLOG(fmt, args...) __nothing
#endif
#define WG_LOG_RATECHECK(wgprc, level, fmt, args...) do { \
if (ppsratecheck(&(wgprc)->wgprc_lasttime, \
&(wgprc)->wgprc_curpps, 1)) { \
log(level, fmt, ##args); \
} \
} while (0)
#ifdef WG_DEBUG_PARAMS
static bool wg_force_underload = false;
#endif
#ifdef WG_DEBUG_DUMP
static char enomem[10] = "[enomem]";
#define MAX_HDUMP_LEN 10000 /* large enough */
/*
* gethexdump(p, n)
*
* Allocate a string returning a hexdump of bytes p[0..n),
* truncated to MAX_HDUMP_LEN. Must be freed with puthexdump.
*
* We use this instead of libkern hexdump() because the result is
* logged with log(LOG_DEBUG, ...), which puts a priority tag on
* every message, so it can't be done incrementally.
*/
static char *
gethexdump(const void *vp, size_t n)
{
char *buf;
const uint8_t *p = vp;
size_t i, alloc;
alloc = n;
if (n > MAX_HDUMP_LEN)
alloc = MAX_HDUMP_LEN;
buf = kmem_alloc(3*alloc + 5, KM_NOSLEEP);
if (buf == NULL)
return enomem;
for (i = 0; i < alloc; i++)
snprintf(buf + 3*i, 3 + 1, " %02hhx", p[i]);
if (alloc != n)
snprintf(buf + 3*i, 4 + 1, " ...");
return buf;
}
static void
puthexdump(char *buf, const void *p, size_t n)
{
if (buf == NULL || buf == enomem)
return;
if (n > MAX_HDUMP_LEN)
n = MAX_HDUMP_LEN;
kmem_free(buf, 3*n + 5);
}
#ifdef WG_RUMPKERNEL
static void
wg_dump_buf(const char *func, const char *buf, const size_t size)
{
if ((wg_debug & WG_DEBUG_FLAGS_DUMP) == 0)
return;
char *hex = gethexdump(buf, size);
log(LOG_DEBUG, "%s: %s\n", func, hex);
puthexdump(hex, buf, size);
}
#endif
static void
wg_dump_hash(const uint8_t *func, const uint8_t *name, const uint8_t *hash,
const size_t size)
{
if ((wg_debug & WG_DEBUG_FLAGS_DUMP) == 0)
return;
char *hex = gethexdump(hash, size);
log(LOG_DEBUG, "%s: %s: %s\n", func, name, hex);
puthexdump(hex, hash, size);
}
#define WG_DUMP_HASH(name, hash) \
wg_dump_hash(__func__, name, hash, WG_HASH_LEN)
#define WG_DUMP_HASH48(name, hash) \
wg_dump_hash(__func__, name, hash, 48)
#define WG_DUMP_BUF(buf, size) \
wg_dump_buf(__func__, buf, size)
#else
#define WG_DUMP_HASH(name, hash) __nothing
#define WG_DUMP_HASH48(name, hash) __nothing
#define WG_DUMP_BUF(buf, size) __nothing
#endif /* WG_DEBUG_DUMP */
/* chosen somewhat arbitrarily -- fits in signed 16 bits NUL-terminated */
#define WG_MAX_PROPLEN 32766
#define WG_MTU 1420
#define WG_ALLOWEDIPS 16
#define CURVE25519_KEY_LEN 32
#define TAI64N_LEN (sizeof(uint32_t) * 3)
#define POLY1305_AUTHTAG_LEN 16
#define HMAC_BLOCK_LEN 64
/* [N] 4.1: "DHLEN must be 32 or greater." WireGuard chooses 32. */
/* [N] 4.3: Hash functions */
#define NOISE_DHLEN 32
/* [N] 4.3: "Must be 32 or 64." WireGuard chooses 32. */
#define NOISE_HASHLEN 32
#define NOISE_BLOCKLEN 64
#define NOISE_HKDF_OUTPUT_LEN NOISE_HASHLEN
/* [N] 5.1: "k" */
#define NOISE_CIPHER_KEY_LEN 32
/*
* [N] 9.2: "psk"
* "... psk is a 32-byte secret value provided by the application."
*/
#define NOISE_PRESHARED_KEY_LEN 32
#define WG_STATIC_KEY_LEN CURVE25519_KEY_LEN
#define WG_TIMESTAMP_LEN TAI64N_LEN
#define WG_PRESHARED_KEY_LEN NOISE_PRESHARED_KEY_LEN
#define WG_COOKIE_LEN 16
#define WG_MAC_LEN 16
#define WG_COOKIESECRET_LEN 32
#define WG_EPHEMERAL_KEY_LEN CURVE25519_KEY_LEN
/* [N] 5.2: "ck: A chaining key of HASHLEN bytes" */
#define WG_CHAINING_KEY_LEN NOISE_HASHLEN
/* [N] 5.2: "h: A hash output of HASHLEN bytes" */
#define WG_HASH_LEN NOISE_HASHLEN
#define WG_CIPHER_KEY_LEN NOISE_CIPHER_KEY_LEN
#define WG_DH_OUTPUT_LEN NOISE_DHLEN
#define WG_KDF_OUTPUT_LEN NOISE_HKDF_OUTPUT_LEN
#define WG_AUTHTAG_LEN POLY1305_AUTHTAG_LEN
#define WG_DATA_KEY_LEN 32
#define WG_SALT_LEN 24
/*
* The protocol messages
*/
struct wg_msg {
uint32_t wgm_type;
} __packed;
/* [W] 5.4.2 First Message: Initiator to Responder */
struct wg_msg_init {
uint32_t wgmi_type;
uint32_t wgmi_sender;
uint8_t wgmi_ephemeral[WG_EPHEMERAL_KEY_LEN];
uint8_t wgmi_static[WG_STATIC_KEY_LEN + WG_AUTHTAG_LEN];
uint8_t wgmi_timestamp[WG_TIMESTAMP_LEN + WG_AUTHTAG_LEN];
uint8_t wgmi_mac1[WG_MAC_LEN];
uint8_t wgmi_mac2[WG_MAC_LEN];
} __packed;
/* [W] 5.4.3 Second Message: Responder to Initiator */
struct wg_msg_resp {
uint32_t wgmr_type;
uint32_t wgmr_sender;
uint32_t wgmr_receiver;
uint8_t wgmr_ephemeral[WG_EPHEMERAL_KEY_LEN];
uint8_t wgmr_empty[0 + WG_AUTHTAG_LEN];
uint8_t wgmr_mac1[WG_MAC_LEN];
uint8_t wgmr_mac2[WG_MAC_LEN];
} __packed;
/* [W] 5.4.6 Subsequent Messages: Transport Data Messages */
struct wg_msg_data {
uint32_t wgmd_type;
uint32_t wgmd_receiver;
uint64_t wgmd_counter;
uint32_t wgmd_packet[];
} __packed;
/* [W] 5.4.7 Under Load: Cookie Reply Message */
struct wg_msg_cookie {
uint32_t wgmc_type;
uint32_t wgmc_receiver;
uint8_t wgmc_salt[WG_SALT_LEN];
uint8_t wgmc_cookie[WG_COOKIE_LEN + WG_AUTHTAG_LEN];
} __packed;
#define WG_MSG_TYPE_INIT 1
#define WG_MSG_TYPE_RESP 2
#define WG_MSG_TYPE_COOKIE 3
#define WG_MSG_TYPE_DATA 4
#define WG_MSG_TYPE_MAX WG_MSG_TYPE_DATA
/* Sliding windows */
#define SLIWIN_BITS 2048u
#define SLIWIN_TYPE uint32_t
#define SLIWIN_BPW (NBBY*sizeof(SLIWIN_TYPE))
#define SLIWIN_WORDS howmany(SLIWIN_BITS, SLIWIN_BPW)
#define SLIWIN_NPKT (SLIWIN_BITS - NBBY*sizeof(SLIWIN_TYPE))
struct sliwin {
SLIWIN_TYPE B[SLIWIN_WORDS];
uint64_t T;
};
/*
* sliwin_reset(W)
*
* Reset sliding window state to a blank history with no observed
* sequence numbers.
*
* Caller must have exclusive access to W.
*/
static void
sliwin_reset(struct sliwin *W)
{
memset(W, 0, sizeof(*W));
}
/*
* sliwin_check_fast(W, S)
*
* Do a fast check of the sliding window W to validate sequence
* number S. No state is recorded. Return 0 on accept, nonzero
* error code on reject.
*
* May be called concurrently with other calls to
* sliwin_check_fast and sliwin_update.
*/
static int
sliwin_check_fast(const volatile struct sliwin *W, uint64_t S)
{
/*
* If it's more than one window older than the highest sequence
* number we've seen, reject.
*/
#ifdef __HAVE_ATOMIC64_LOADSTORE
if (S + SLIWIN_NPKT < atomic_load_relaxed(&W->T))
return EAUTH;
#endif
/*
* Otherwise, we need to take the lock to decide, so don't
* reject just yet. Caller must serialize a call to
* sliwin_update in this case.
*/
return 0;
}
/*
* sliwin_update(W, S)
*
* Check the sliding window W to validate sequence number S, and
* if accepted, update it to reflect having observed S. Return 0
* on accept, nonzero error code on reject.
*
* May be called concurrently with other calls to
* sliwin_check_fast, but caller must exclude other calls to
* sliwin_update.
*/
static int
sliwin_update(struct sliwin *W, uint64_t S)
{
unsigned word, bit;
/*
* If it's more than one window older than the highest sequence
* number we've seen, reject.
*/
if (S + SLIWIN_NPKT < W->T)
return EAUTH;
/*
* If it's higher than the highest sequence number we've seen,
* advance the window.
*/
if (S > W->T) {
uint64_t i = W->T / SLIWIN_BPW;
uint64_t j = S / SLIWIN_BPW;
unsigned k;
for (k = 0; k < MIN(j - i, SLIWIN_WORDS); k++)
W->B[(i + k + 1) % SLIWIN_WORDS] = 0;
#ifdef __HAVE_ATOMIC64_LOADSTORE
atomic_store_relaxed(&W->T, S);
#else
W->T = S;
#endif
}
/* Test and set the bit -- if already set, reject. */
word = (S / SLIWIN_BPW) % SLIWIN_WORDS;
bit = S % SLIWIN_BPW;
if (W->B[word] & (1UL << bit))
return EAUTH;
W->B[word] |= 1U << bit;
/* Accept! */
return 0;
}
struct wg_session {
struct wg_peer *wgs_peer;
struct psref_target
wgs_psref;
volatile int wgs_state;
#define WGS_STATE_UNKNOWN 0
#define WGS_STATE_INIT_ACTIVE 1
#define WGS_STATE_INIT_PASSIVE 2
#define WGS_STATE_ESTABLISHED 3
#define WGS_STATE_DESTROYING 4
uint32_t wgs_time_established;
volatile uint32_t
wgs_time_last_data_sent;
volatile bool wgs_force_rekey;
bool wgs_is_initiator;
uint32_t wgs_local_index;
uint32_t wgs_remote_index;
#ifdef __HAVE_ATOMIC64_LOADSTORE
volatile uint64_t
wgs_send_counter;
#else
kmutex_t wgs_send_counter_lock;
uint64_t wgs_send_counter;
#endif
struct {
kmutex_t lock;
struct sliwin window;
} *wgs_recvwin;
uint8_t wgs_handshake_hash[WG_HASH_LEN];
uint8_t wgs_chaining_key[WG_CHAINING_KEY_LEN];
uint8_t wgs_ephemeral_key_pub[WG_EPHEMERAL_KEY_LEN];
uint8_t wgs_ephemeral_key_priv[WG_EPHEMERAL_KEY_LEN];
uint8_t wgs_ephemeral_key_peer[WG_EPHEMERAL_KEY_LEN];
uint8_t wgs_tkey_send[WG_DATA_KEY_LEN];
uint8_t wgs_tkey_recv[WG_DATA_KEY_LEN];
};
struct wg_sockaddr {
union {
struct sockaddr_storage _ss;
struct sockaddr _sa;
struct sockaddr_in _sin;
struct sockaddr_in6 _sin6;
};
struct psref_target wgsa_psref;
};
#define wgsatoss(wgsa) (&(wgsa)->_ss)
#define wgsatosa(wgsa) (&(wgsa)->_sa)
#define wgsatosin(wgsa) (&(wgsa)->_sin)
#define wgsatosin6(wgsa) (&(wgsa)->_sin6)
#define wgsa_family(wgsa) (wgsatosa(wgsa)->sa_family)
struct wg_peer;
struct wg_allowedip {
struct radix_node wga_nodes[2];
struct wg_sockaddr _wga_sa_addr;
struct wg_sockaddr _wga_sa_mask;
#define wga_sa_addr _wga_sa_addr._sa
#define wga_sa_mask _wga_sa_mask._sa
int wga_family;
uint8_t wga_cidr;
union {
struct in_addr _ip4;
struct in6_addr _ip6;
} wga_addr;
#define wga_addr4 wga_addr._ip4
#define wga_addr6 wga_addr._ip6
struct wg_peer *wga_peer;
};
typedef uint8_t wg_timestamp_t[WG_TIMESTAMP_LEN];
struct wg_ppsratecheck {
struct timeval wgprc_lasttime;
int wgprc_curpps;
};
struct wg_softc;
struct wg_peer {
struct wg_softc *wgp_sc;
char wgp_name[WG_PEER_NAME_MAXLEN + 1];
struct pslist_entry wgp_peerlist_entry;
pserialize_t wgp_psz;
struct psref_target wgp_psref;
kmutex_t *wgp_lock;
kmutex_t *wgp_intr_lock;
uint8_t wgp_pubkey[WG_STATIC_KEY_LEN];
struct wg_sockaddr *volatile wgp_endpoint;
struct wg_sockaddr *wgp_endpoint0;
volatile unsigned wgp_endpoint_changing;
volatile bool wgp_endpoint_available;
/* The preshared key (optional) */
uint8_t wgp_psk[WG_PRESHARED_KEY_LEN];
struct wg_session *volatile wgp_session_stable;
struct wg_session *wgp_session_unstable;
/* first outgoing packet awaiting session initiation */
struct mbuf *volatile wgp_pending;
/* timestamp in big-endian */
wg_timestamp_t wgp_timestamp_latest_init;
struct timespec wgp_last_handshake_time;
callout_t wgp_handshake_timeout_timer;
callout_t wgp_session_dtor_timer;
time_t wgp_handshake_start_time;
int wgp_n_allowedips;
struct wg_allowedip wgp_allowedips[WG_ALLOWEDIPS];
time_t wgp_latest_cookie_time;
uint8_t wgp_latest_cookie[WG_COOKIE_LEN];
uint8_t wgp_last_sent_mac1[WG_MAC_LEN];
bool wgp_last_sent_mac1_valid;
struct wg_ppsratecheck wgp_ppsratecheck;
struct work wgp_work;
unsigned int wgp_tasks;
#define WGP_TASK_SEND_INIT_MESSAGE __BIT(0)
#define WGP_TASK_RETRY_HANDSHAKE __BIT(1)
#define WGP_TASK_ESTABLISH_SESSION __BIT(2)
#define WGP_TASK_ENDPOINT_CHANGED __BIT(3)
#define WGP_TASK_SEND_KEEPALIVE_MESSAGE __BIT(4)
#define WGP_TASK_DESTROY_PREV_SESSION __BIT(5)
};
struct wg_ops;
struct wg_softc {
struct ifnet wg_if;
LIST_ENTRY(wg_softc) wg_list;
kmutex_t *wg_lock;
kmutex_t *wg_intr_lock;
krwlock_t *wg_rwlock;
uint8_t wg_privkey[WG_STATIC_KEY_LEN];
uint8_t wg_pubkey[WG_STATIC_KEY_LEN];
uint8_t wg_cookiesecret[WG_COOKIESECRET_LEN];
int wg_npeers;
struct pslist_head wg_peers;
struct thmap *wg_peers_bypubkey;
struct thmap *wg_peers_byname;
struct thmap *wg_sessions_byindex;
uint16_t wg_listen_port;
struct threadpool *wg_threadpool;
struct threadpool_job wg_job;
int wg_upcalls;
#define WG_UPCALL_INET __BIT(0)
#define WG_UPCALL_INET6 __BIT(1)
#ifdef INET
struct socket *wg_so4;
struct radix_node_head *wg_rtable_ipv4;
#endif
#ifdef INET6
struct socket *wg_so6;
struct radix_node_head *wg_rtable_ipv6;
#endif
struct wg_ppsratecheck wg_ppsratecheck;
struct wg_ops *wg_ops;
#ifdef WG_RUMPKERNEL
struct wg_user *wg_user;
#endif
};
/* [W] 6.1 Preliminaries */
#define WG_REKEY_AFTER_MESSAGES (1ULL << 60)
#define WG_REJECT_AFTER_MESSAGES (UINT64_MAX - (1 << 13))
#define WG_REKEY_AFTER_TIME 120
#define WG_REJECT_AFTER_TIME 180
#define WG_REKEY_ATTEMPT_TIME 90
#define WG_REKEY_TIMEOUT 5
#define WG_KEEPALIVE_TIMEOUT 10
#define WG_COOKIE_TIME 120
#define WG_COOKIESECRET_TIME (2 * 60)
static uint64_t wg_rekey_after_messages = WG_REKEY_AFTER_MESSAGES;
static uint64_t wg_reject_after_messages = WG_REJECT_AFTER_MESSAGES;
static unsigned wg_rekey_after_time = WG_REKEY_AFTER_TIME;
static unsigned wg_reject_after_time = WG_REJECT_AFTER_TIME;
static unsigned wg_rekey_attempt_time = WG_REKEY_ATTEMPT_TIME;
static unsigned wg_rekey_timeout = WG_REKEY_TIMEOUT;
static unsigned wg_keepalive_timeout = WG_KEEPALIVE_TIMEOUT;
static struct mbuf *
wg_get_mbuf(size_t, size_t);
static void wg_bake_cookie(struct wg_softc *,
uint8_t[static WG_COOKIE_LEN],
uint8_t[static WG_COOKIE_LEN],
const struct sockaddr *);
static void wg_send_data_msg(struct wg_peer *, struct wg_session *,
struct mbuf *);
static void wg_send_cookie_msg(struct wg_softc *,
const uint8_t[static WG_COOKIE_LEN],
const uint32_t, const uint8_t[static WG_MAC_LEN],
const struct sockaddr *);
static void wg_send_handshake_msg_resp(struct wg_softc *, struct wg_peer *,
struct wg_session *, const struct wg_msg_init *);
static void wg_send_keepalive_msg(struct wg_peer *, struct wg_session *);
static struct wg_peer *
wg_pick_peer_by_sa(struct wg_softc *, const struct sockaddr *,
struct psref *);
static struct wg_peer *
wg_lookup_peer_by_pubkey(struct wg_softc *,
const uint8_t[static WG_STATIC_KEY_LEN], struct psref *);
static struct wg_session *
wg_lookup_session_by_index(struct wg_softc *,
const uint32_t, struct psref *);
static void wg_update_endpoint_if_necessary(struct wg_peer *,
const struct sockaddr *);
static void wg_schedule_session_dtor_timer(struct wg_peer *);
static bool wg_is_underload(struct wg_softc *, int);
static void wg_calculate_keys(struct wg_session *, const bool);
static void wg_clear_states(struct wg_session *);
static void wg_get_peer(struct wg_peer *, struct psref *);
static void wg_put_peer(struct wg_peer *, struct psref *);
static int wg_send_cookie(struct wg_softc *, const struct sockaddr *,
struct mbuf *);
static int wg_send_hs(struct wg_peer *, struct mbuf *);
static int wg_send_data(struct wg_peer *, struct mbuf *);
static int wg_output(struct ifnet *, struct mbuf *,
const struct sockaddr *, const struct rtentry *);
static void wg_input(struct ifnet *, struct mbuf *, const int);
static int wg_ioctl(struct ifnet *, u_long, void *);
static int wg_bind_port(struct wg_softc *, const uint16_t);
static int wg_init(struct ifnet *);
#ifdef ALTQ
static void wg_start(struct ifnet *);
#endif
static void wg_stop(struct ifnet *, int);
static void wg_peer_work(struct work *, void *);
static void wg_job(struct threadpool_job *);
static void wgintr(void *);
static void wg_purge_pending_packets(struct wg_peer *);
static int wg_clone_create(struct if_clone *, int);
static int wg_clone_destroy(struct ifnet *);
struct wg_ops {
int (*send_cookie)(struct wg_softc *, const struct sockaddr *,
struct mbuf *);
int (*send_hs_msg)(struct wg_peer *, struct mbuf *);
int (*send_data_msg)(struct wg_peer *, struct mbuf *);
void (*input)(struct ifnet *, struct mbuf *, const int);
int (*bind_port)(struct wg_softc *, const uint16_t);
};
struct wg_ops wg_ops_rumpkernel = {
.send_cookie = wg_send_cookie,
.send_hs_msg = wg_send_hs,
.send_data_msg = wg_send_data,
.input = wg_input,
.bind_port = wg_bind_port,
};
#ifdef WG_RUMPKERNEL
static bool wg_user_mode(struct wg_softc *);
static int wg_ioctl_linkstr(struct wg_softc *, struct ifdrv *);
static int wg_send_cookie_user(struct wg_softc *, const struct sockaddr *,
struct mbuf *);
static int wg_send_hs_user(struct wg_peer *, struct mbuf *);
static int wg_send_data_user(struct wg_peer *, struct mbuf *);
static void wg_input_user(struct ifnet *, struct mbuf *, const int);
static int wg_bind_port_user(struct wg_softc *, const uint16_t);
struct wg_ops wg_ops_rumpuser = {
.send_cookie = wg_send_cookie_user,
.send_hs_msg = wg_send_hs_user,
.send_data_msg = wg_send_data_user,
.input = wg_input_user,
.bind_port = wg_bind_port_user,
};
#endif
#define WG_PEER_READER_FOREACH(wgp, wg) \
PSLIST_READER_FOREACH((wgp), &(wg)->wg_peers, struct wg_peer, \
wgp_peerlist_entry)
#define WG_PEER_WRITER_FOREACH(wgp, wg) \
PSLIST_WRITER_FOREACH((wgp), &(wg)->wg_peers, struct wg_peer, \
wgp_peerlist_entry)
#define WG_PEER_WRITER_INSERT_HEAD(wgp, wg) \
PSLIST_WRITER_INSERT_HEAD(&(wg)->wg_peers, (wgp), wgp_peerlist_entry)
#define WG_PEER_WRITER_REMOVE(wgp) \
PSLIST_WRITER_REMOVE((wgp), wgp_peerlist_entry)
struct wg_route {
struct radix_node wgr_nodes[2];
struct wg_peer *wgr_peer;
};
static struct radix_node_head *
wg_rnh(struct wg_softc *wg, const int family)
{
switch (family) {
#ifdef INET
case AF_INET:
return wg->wg_rtable_ipv4;
#endif
#ifdef INET6
case AF_INET6:
return wg->wg_rtable_ipv6;
#endif
default:
return NULL;
}
}
/*
* Global variables
*/
static volatile unsigned wg_count __cacheline_aligned;
struct psref_class *wg_psref_class __read_mostly;
static struct if_clone wg_cloner =
IF_CLONE_INITIALIZER("wg", wg_clone_create, wg_clone_destroy);
static struct pktqueue *wg_pktq __read_mostly;
static struct workqueue *wg_wq __read_mostly;
void wgattach(int);
/* ARGSUSED */
void
wgattach(int count)
{
/*
* Nothing to do here, initialization is handled by the
* module initialization code in wginit() below).
*/
}
static void
wginit(void)
{
wg_psref_class = psref_class_create("wg", IPL_SOFTNET);
if_clone_attach(&wg_cloner);
}
/*
* XXX Kludge: This should just happen in wginit, but workqueue_create
* cannot be run until after CPUs have been detected, and wginit runs
* before configure.
*/
static int
wginitqueues(void)
{
int error __diagused;
wg_pktq = pktq_create(IFQ_MAXLEN, wgintr, NULL);
KASSERT(wg_pktq != NULL);
error = workqueue_create(&wg_wq, "wgpeer", wg_peer_work, NULL,
PRI_NONE, IPL_SOFTNET, WQ_MPSAFE|WQ_PERCPU);
KASSERTMSG(error == 0, "error=%d", error);
return 0;
}
static void
wg_guarantee_initialized(void)
{
static ONCE_DECL(init);
int error __diagused;
error = RUN_ONCE(&init, wginitqueues);
KASSERTMSG(error == 0, "error=%d", error);
}
static int
wg_count_inc(void)
{
unsigned o, n;
do {
o = atomic_load_relaxed(&wg_count);
if (o == UINT_MAX)
return ENFILE;
n = o + 1;
} while (atomic_cas_uint(&wg_count, o, n) != o);
return 0;
}
static void
wg_count_dec(void)
{
unsigned c __diagused;
membar_release(); /* match atomic_load_acquire in wgdetach */
c = atomic_dec_uint_nv(&wg_count);
KASSERT(c != UINT_MAX);
}
static int
wgdetach(void)
{
/* Prevent new interface creation. */
if_clone_detach(&wg_cloner);
/*
* Check whether there are any existing interfaces. Matches
* membar_release and atomic_dec_uint_nv in wg_count_dec.
*/
if (atomic_load_acquire(&wg_count)) {
/* Back out -- reattach the cloner. */
if_clone_attach(&wg_cloner);
return EBUSY;
}
/* No interfaces left. Nuke it. */
if (wg_wq)
workqueue_destroy(wg_wq);
if (wg_pktq)
pktq_destroy(wg_pktq);
psref_class_destroy(wg_psref_class);
return 0;
}
static void
wg_init_key_and_hash(uint8_t ckey[static WG_CHAINING_KEY_LEN],
uint8_t hash[static WG_HASH_LEN])