if_wg_session.c 49.7 KB
Newer Older
Matt Macy's avatar
Matt Macy committed
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
/*
 * Copyright (C) 2015-2020 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
 * Copyright (C) 2019-2020 Matt Dunwoodie <ncon@noconroy.net>
 * Copyright (c) 2019-2020 Rubicon Communications, LLC (Netgate)
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */



#include "opt_inet.h"
#include "opt_inet6.h"

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/types.h>
#include <sys/systm.h>
#include <vm/uma.h>

#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/kernel.h>

#include <sys/sockio.h>
#include <sys/socketvar.h>
#include <sys/errno.h>
#include <sys/proc.h>
#include <sys/lock.h>
#include <sys/rwlock.h>
#include <sys/protosw.h>
#include <sys/endian.h>
#include <sys/kdb.h>
#include <sys/sysctl.h>

#include <net/bpf.h>


#include <sys/support.h>
#include <sys/if_wg_session.h>
#include <sys/if_wg_session_vars.h>
#include <sys/syslog.h>

#include <netinet/in.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet6/scope6_var.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <netinet/icmp6.h>
#include <netinet/in_pcb.h>
#include <netinet6/in6_pcb.h>
#include <netinet/udp_var.h>

#include <crypto/blake2s.h>
#include <crypto/curve25519.h>
#include <machine/in_cksum.h>

#define MAX_STAGED_PKT		128
#define MAX_QUEUED_PKT		512

#define	GROUPTASK_DRAIN(gtask)			\
	gtaskqueue_drain((gtask)->gt_taskqueue, &(gtask)->gt_task)
TASKQGROUP_DECLARE(if_io_tqg);

struct wg_pkt_initiation {
	uint32_t		t;
	struct noise_initiation init;
	struct cookie_macs	m;
} __packed;

struct wg_pkt_response {
	uint32_t		t;
	struct noise_response	resp;
	struct cookie_macs	m;
} __packed;

struct wg_pkt_cookie {
	uint32_t		t;
	uint32_t		r_idx;
	uint8_t			nonce[COOKIE_XNONCE_SIZE];
	uint8_t			ec[COOKIE_ENCRYPTED_SIZE];
} __packed;

struct wg_pkt_data {
	uint32_t		t;
	struct noise_data	data;
} __packed;

#define MTAG_WIREGUARD 0xBEAD
#define WG_PKT_WITH_PADDING(n)	(((n) + (16-1)) & (~(16-1)))

SYSCTL_NODE(_net, OID_AUTO, wg, CTLFLAG_RW, 0, "Wireguard");
static int wireguard_debug;
SYSCTL_INT(_net_wg, OID_AUTO, debug, CTLFLAG_RWTUN, &wireguard_debug, 0,
	"enable debug logging");


#define DPRINTF(sc,  ...) if (wireguard_debug) if_printf(sc->sc_ifp, ##__VA_ARGS__)

/* Socket */
static int	wg_socket_bind(struct wg_softc *sc, struct wg_socket *);
static int	wg_send(struct wg_softc *, struct wg_endpoint *, struct mbuf *);

/* Timers */
static int	wg_timers_expired_handshake_last_sent(struct wg_timers *);


static void	wg_timers_event_data_sent(struct wg_timers *);
static void	wg_timers_event_data_received(struct wg_timers *);
static void	wg_timers_event_any_authenticated_packet_sent(struct wg_timers *);
static void	wg_timers_event_any_authenticated_packet_received(struct wg_timers *);
static void	wg_timers_event_handshake_initiated(struct wg_timers *);
static void	wg_timers_event_handshake_responded(struct wg_timers *);
static void	wg_timers_event_handshake_complete(struct wg_timers *);
static void	wg_timers_event_session_derived(struct wg_timers *);
static void	wg_timers_event_any_authenticated_packet_traversal(struct wg_timers *);
static void	wg_timers_event_want_initiation(struct wg_timers *);

static void	wg_timers_run_send_initiation(struct wg_timers *, int);
static void	wg_timers_run_retry_handshake(struct wg_timers *);
static void	wg_timers_run_send_keepalive(struct wg_timers *);
static void	wg_timers_run_new_handshake(struct wg_timers *);
static void	wg_timers_run_zero_key_material(struct wg_timers *);
static void	wg_timers_run_persistent_keepalive(struct wg_timers *);

static void	wg_peer_timers_init(struct wg_peer *);
static void	wg_timers_disable(struct wg_timers *);

/* Queue */
static int	wg_queue_in(struct wg_peer *, struct mbuf *);
static struct mbuf *wg_queue_dequeue(struct wg_queue *, struct wg_tag **);

/* Cookie */

static int wg_cookie_validate_packet(struct cookie_checker *, struct mbuf *,
    int);

/* Peer */
static void	wg_send_initiation(struct wg_peer *);
static void	wg_send_cookie(struct wg_softc *, struct cookie_macs *, uint32_t, struct mbuf *);

static void	wg_peer_set_endpoint_from_tag(struct wg_peer *, struct wg_tag *);
static void	wg_peer_clear_src(struct wg_peer *);
static void	wg_peer_get_endpoint(struct wg_peer *, struct wg_endpoint *);

static void	wg_deliver_out(struct wg_peer *);
static void	wg_deliver_in(struct wg_peer *);
static void	wg_send_buf(struct wg_softc *, struct wg_endpoint *, uint8_t *, size_t);


static void	wg_send_keepalive(struct wg_peer *);

/* Packet */
static struct wg_endpoint *wg_mbuf_endpoint_get(struct mbuf *);

static void	wg_handshake(struct wg_softc *, struct mbuf *);
static void	wg_encap(struct wg_softc *, struct mbuf *);
static void	wg_decap(struct wg_softc *, struct mbuf *);

/* Interface */
static void wg_input(struct mbuf *m, int offset, struct inpcb *inpcb,
    const struct sockaddr *srcsa, void *_sc);

/* Globals */

#define UNDERLOAD_TIMEOUT	1

static volatile unsigned long peer_counter = 0;
static struct timeval	underload_interval = { UNDERLOAD_TIMEOUT, 0 };

#define M_ENQUEUED	M_PROTO1

static void
wg_m_freem(struct mbuf *m)
{
	MPASS((m->m_flags & M_ENQUEUED) == 0);
	m_freem(m);
}

static void
m_calchdrlen(struct mbuf *m)
{
	struct mbuf *n;
	int plen = 0;

	MPASS(m->m_flags & M_PKTHDR);
	for (n = m; n; n = n->m_next)
		plen += n->m_len;
	m->m_pkthdr.len = plen;
}

static inline int
callout_del(struct callout *c)
{
	return (callout_stop(c) > 0);
}

struct wg_tag *
wg_tag_get(struct mbuf *m)
{
	struct m_tag *tag;

	tag = m_tag_find(m, MTAG_WIREGUARD, NULL);
	if (tag == NULL) {
		tag = m_tag_get(MTAG_WIREGUARD, sizeof(struct wg_tag), M_NOWAIT|M_ZERO);
		m_tag_prepend(m, tag);
		MPASS(!SLIST_EMPTY(&m->m_pkthdr.tags));
		MPASS(m_tag_locate(m, MTAG_ABI_COMPAT, MTAG_WIREGUARD, NULL) == tag);
	}
	return (struct wg_tag *)tag;
}

static struct wg_endpoint *
wg_mbuf_endpoint_get(struct mbuf *m)
{
	struct wg_tag *hdr;

	if ((hdr = wg_tag_get(m)) == NULL)
		return (NULL);

	return (&hdr->t_endpoint);
}

/* Socket */

static int
wg_socket_reuse(struct wg_softc *sc, struct socket *so)
{
	struct sockopt sopt;
	int error, val = 1;
	struct ifnet *ifp;

	bzero(&sopt, sizeof(sopt));
	sopt.sopt_dir = SOPT_SET;
	sopt.sopt_level = SOL_SOCKET;
	sopt.sopt_name = SO_REUSEPORT;
	sopt.sopt_val = &val;
	sopt.sopt_valsize = sizeof(val);
	error = sosetopt(so, &sopt);
	if (error) {
		ifp = iflib_get_ifp(sc->wg_ctx);
Mark Johnston's avatar
Mark Johnston committed
257
		if_printf(ifp, "cannot set REUSEPORT socket opt: %d\n", error);
Matt Macy's avatar
Matt Macy committed
258
259
260
261
262
	}
	sopt.sopt_name = SO_REUSEADDR;
	error = sosetopt(so, &sopt);
	if (error) {
		ifp = iflib_get_ifp(sc->wg_ctx);
Mark Johnston's avatar
Mark Johnston committed
263
		if_printf(ifp, "cannot set REUSEADDDR socket opt: %d\n", error);
Matt Macy's avatar
Matt Macy committed
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
	}
	return (error);
}

int
wg_socket_init(struct wg_softc *sc)
{
	struct thread *td;
	struct wg_socket *so;
	struct ifnet *ifp;
	int rc;

	so = &sc->sc_socket;
	td = curthread;
	ifp = iflib_get_ifp(sc->wg_ctx);
	rc = socreate(AF_INET, &so->so_so4, SOCK_DGRAM, IPPROTO_UDP, td->td_ucred, td);
	if (rc) {
		if_printf(ifp, "can't create AF_INET socket\n");
		return (rc);
	}
	rc = wg_socket_reuse(sc, so->so_so4);
	if (rc)
		goto fail;
	rc = udp_set_kernel_tunneling(so->so_so4, wg_input, NULL, sc);
	if_printf(ifp, "sc=%p\n", sc);
	/*
	 * udp_set_kernel_tunneling can only fail if there is already a tunneling function set.
	 * This should never happen with a new socket.
	 */
	MPASS(rc == 0);
	
	rc = socreate(AF_INET6, &so->so_so6, SOCK_DGRAM, IPPROTO_UDP, td->td_ucred, td);
	if (rc) {
		if_printf(ifp, "can't create AF_INET6 socket\n");

		goto fail;
	}
	rc = wg_socket_reuse(sc, so->so_so6);
	if (rc) {
		SOCK_LOCK(so->so_so6);
		sofree(so->so_so6);
		goto fail;
	}
	rc = udp_set_kernel_tunneling(so->so_so6, wg_input, NULL, sc);
	MPASS(rc == 0);

	rc = wg_socket_bind(sc, so);
	return (rc);
fail:
	SOCK_LOCK(so->so_so4);
	sofree(so->so_so4);
	return (rc);
}

void
wg_socket_reinit(struct wg_softc *sc, struct socket *new4,
    struct socket *new6)
{
	struct wg_socket *so;

	so = &sc->sc_socket;

	if (so->so_so4)
		soclose(so->so_so4);
	so->so_so4 = new4;
	if (so->so_so6)
		soclose(so->so_so6);
	so->so_so6 = new6;
}

int
wg_socket_close(struct wg_socket *so)
{
	int ret = 0;
	if ((ret = soclose(so->so_so4)) != 0)
		goto leave;
	if ((ret = soclose(so->so_so6)) != 0)
		goto leave;
leave:
	return ret;
}

union wg_sockaddr {
	struct sockaddr sa;
	struct sockaddr_in in4;
	struct sockaddr_in6 in6;
};

int
wg_socket_bind(struct wg_softc *sc, struct wg_socket *so)
{
	int rc;
	struct thread *td;
	union wg_sockaddr laddr;
	struct sockaddr_in *sin;
	struct sockaddr_in6 *sin6;
	struct ifnet *ifp;

	if (so->so_port == 0)
		return (0);
	td = curthread;
	bzero(&laddr, sizeof(laddr));
	ifp = iflib_get_ifp(sc->wg_ctx);
	sin = &laddr.in4;
	sin->sin_len = sizeof(laddr.in4);
	sin->sin_family = AF_INET;
	sin->sin_port = htons(so->so_port);
	sin->sin_addr = (struct in_addr) { 0 };

	if ((rc = sobind(so->so_so4, &laddr.sa, td)) != 0) {
		if_printf(ifp, "can't bind AF_INET socket %d\n", rc);
		return (rc);
	}
	sin6 = &laddr.in6;
	sin6->sin6_len = sizeof(laddr.in6);
	sin6->sin6_family = AF_INET6;
	sin6->sin6_port = htons(so->so_port);
	sin6->sin6_addr = (struct in6_addr) { .s6_addr = { 0 } };

	rc = sobind(so->so_so6, &laddr.sa, td);
	if (rc)
		if_printf(ifp, "can't bind AF_INET6 socket %d\n", rc);
	return (rc);
}

static int
wg_send(struct wg_softc *sc, struct wg_endpoint *e, struct mbuf *m)
{
	struct epoch_tracker et;
	struct sockaddr *sa;
	struct wg_socket *so = &sc->sc_socket;
	struct mbuf	 *control = NULL;
	int		 ret = 0;

	/* Get local control address before locking */
	if (e->e_remote.r_sa.sa_family == AF_INET) {
		if (e->e_local.l_in.s_addr != INADDR_ANY)
			control = sbcreatecontrol((caddr_t)&e->e_local.l_in,
			    sizeof(struct in_addr), IP_SENDSRCADDR,
			    IPPROTO_IP);
	} else if (e->e_remote.r_sa.sa_family == AF_INET6) {
		if (!IN6_IS_ADDR_UNSPECIFIED(&e->e_local.l_in6))
			control = sbcreatecontrol((caddr_t)&e->e_local.l_pktinfo6,
			    sizeof(struct in6_pktinfo), IPV6_PKTINFO,
			    IPPROTO_IPV6);
	} else {
		return (EAFNOSUPPORT);
	}

	/* Get remote address */
	sa = &e->e_remote.r_sa;

	NET_EPOCH_ENTER(et);
	if (sc->sc_ifp->if_link_state == LINK_STATE_DOWN)
		goto done;
	if (e->e_remote.r_sa.sa_family == AF_INET && so->so_so4 != NULL)
		ret = sosend(so->so_so4, sa, NULL, m, control, 0, curthread);
	else if (e->e_remote.r_sa.sa_family == AF_INET6 && so->so_so6 != NULL)
		ret = sosend(so->so_so6, sa, NULL, m, control, 0, curthread);
	else {
		ret = ENOTCONN;
		wg_m_freem(control);
		wg_m_freem(m);
	}
done:
	NET_EPOCH_EXIT(et);
	return (ret);
}

/* Timers */
/* Should be called after an authenticated data packet is sent. */
static void
wg_timers_event_data_sent(struct wg_timers *t)
{
	struct epoch_tracker et;

	NET_EPOCH_ENTER(et);

	if (!t->t_disabled && !callout_pending(&t->t_new_handshake))
		callout_reset(&t->t_new_handshake,
		    NEW_HANDSHAKE_TIMEOUT * hz + (random() % REKEY_TIMEOUT_JITTER),
		    (timeout_t *)wg_timers_run_new_handshake, t);
	NET_EPOCH_EXIT(et);
}

/* Should be called after an authenticated data packet is received. */
static void
wg_timers_event_data_received(struct wg_timers *t)
{
	struct epoch_tracker et;

	if (t->t_disabled)
		return;
	NET_EPOCH_ENTER(et);
	if (!callout_pending(&t->t_send_keepalive)) {
		callout_reset(&t->t_send_keepalive, KEEPALIVE_TIMEOUT*hz,
		    (timeout_t *)wg_timers_run_send_keepalive, t);
	} else {
		t->t_need_another_keepalive = 1;
	}
	NET_EPOCH_EXIT(et);
}

/*
 * Should be called after any type of authenticated packet is sent, whether
 * keepalive, data, or handshake.
 */
static void
wg_timers_event_any_authenticated_packet_sent(struct wg_timers *t)
{
	callout_del(&t->t_send_keepalive);
}

/*
 * Should be called after any type of authenticated packet is received, whether
 * keepalive, data, or handshake.
 */
static void
wg_timers_event_any_authenticated_packet_received(struct wg_timers *t)
{
	callout_del(&t->t_new_handshake);
}

/*
 * Should be called before a packet with authentication, whether
 * keepalive, data, or handshake is sent, or after one is received.
 */
static void
wg_timers_event_any_authenticated_packet_traversal(struct wg_timers *t)
{
	struct epoch_tracker et;

	NET_EPOCH_ENTER(et);
	if (!t->t_disabled && t->t_persistent_keepalive_interval > 0)
		callout_reset(&t->t_persistent_keepalive,
		     t->t_persistent_keepalive_interval *hz,
		    (timeout_t *)wg_timers_run_persistent_keepalive, t);
	NET_EPOCH_EXIT(et);
}

/* Should be called after a handshake initiation message is sent. */
static void
wg_timers_event_handshake_initiated(struct wg_timers *t)
{

	if (t->t_disabled)
		return;
	callout_reset(&t->t_retry_handshake,
	    REKEY_TIMEOUT * hz + random() % REKEY_TIMEOUT_JITTER,
	    (timeout_t *)wg_timers_run_retry_handshake, t);
}

static void
wg_timers_event_handshake_responded(struct wg_timers *t)
{
	getnanouptime(&t->t_handshake_last_sent);
}

/*
 * Should be called after a handshake response message is received and processed
 * or when getting key confirmation via the first data message.
 */
static void
wg_timers_event_handshake_complete(struct wg_timers *t)
{
	if (t->t_disabled)
		return;

	callout_del(&t->t_retry_handshake);
	t->t_handshake_retries = 0;
	getnanotime(&t->t_handshake_complete);
	wg_timers_run_send_keepalive(t);
}

/*
 * Should be called after an ephemeral key is created, which is before sending a
 * handshake response or after receiving a handshake response.
 */
static void
wg_timers_event_session_derived(struct wg_timers *t)
{
	if (t->t_disabled)
		return;

	callout_reset(&t->t_zero_key_material,
	    REJECT_AFTER_TIME * 3 * hz,
	    (timeout_t *)wg_timers_run_zero_key_material, t);
}

static void
wg_timers_event_want_initiation(struct wg_timers *t)
{
	if (t->t_disabled)
		return;

	wg_timers_run_send_initiation(t, 0);
}

static void
wg_grouptask_enqueue(struct wg_peer *peer, struct grouptask *task)
{
	if (peer->p_sc->sc_ifp->if_link_state == LINK_STATE_UP)
		GROUPTASK_ENQUEUE(task);
}

static void
wg_timers_run_send_initiation(struct wg_timers *t, int is_retry)
{
	struct wg_peer	 *peer = CONTAINER_OF(t, struct wg_peer, p_timers);

	if (!is_retry)
		t->t_handshake_retries = 0;
	if (wg_timers_expired_handshake_last_sent(t) == ETIMEDOUT)
		wg_grouptask_enqueue(peer, &peer->p_send_initiation);
}

static void
wg_timers_run_retry_handshake(struct wg_timers *t)
{
	struct wg_peer	*peer = CONTAINER_OF(t, struct wg_peer, p_timers);
	int		 retries;

	retries = atomic_fetchadd_int(&t->t_handshake_retries, 1);

	if (retries <= MAX_TIMER_HANDSHAKES) {
		DPRINTF(peer->p_sc, "Handshake for peer %llu did not complete "
		    "after %d seconds, retrying (try %d)\n",
			(unsigned long long)peer->p_id,
		    REKEY_TIMEOUT, t->t_handshake_retries + 1);
		wg_peer_clear_src(peer);
		wg_timers_run_send_initiation(t, 1);
	} else {
		DPRINTF(peer->p_sc, "Handshake for peer %llu did not complete "
		    "after %d retries, giving up\n",
			(unsigned long long) peer->p_id, MAX_TIMER_HANDSHAKES + 2);

		callout_del(&t->t_send_keepalive);
		if (!callout_pending(&t->t_zero_key_material))
			callout_reset(&t->t_zero_key_material, REJECT_AFTER_TIME * 3 * hz,
			    (timeout_t *)wg_timers_run_zero_key_material, t);
	}
}

static void
wg_timers_run_send_keepalive(struct wg_timers *t)
{
	struct wg_peer	*peer = CONTAINER_OF(t, struct wg_peer, p_timers);

	wg_grouptask_enqueue(peer, &peer->p_send_keepalive);
	if (t->t_need_another_keepalive) {
		t->t_need_another_keepalive = 0;
		callout_reset(&t->t_send_keepalive,
		    KEEPALIVE_TIMEOUT*hz,
		     (timeout_t *)wg_timers_run_send_keepalive, t);
	}
}

static void
wg_timers_run_new_handshake(struct wg_timers *t)
{
	struct wg_peer	*peer = CONTAINER_OF(t, struct wg_peer, p_timers);

	DPRINTF(peer->p_sc, "Retrying handshake with peer %llu because we "
	    "stopped hearing back after %d seconds\n",
		(unsigned long long)peer->p_id, NEW_HANDSHAKE_TIMEOUT);
	wg_peer_clear_src(peer);

	wg_timers_run_send_initiation(t, 0);
}

static void
wg_timers_run_zero_key_material(struct wg_timers *t)
{
	struct wg_peer *peer = CONTAINER_OF(t, struct wg_peer, p_timers);

	DPRINTF(peer->p_sc, "Zeroing out all keys for peer %llu, since we "
	    "haven't received a new one in %d seconds\n",
		(unsigned long long)peer->p_id, REJECT_AFTER_TIME * 3);
	GROUPTASK_ENQUEUE(&peer->p_clear_secrets);
}

static void
wg_timers_run_persistent_keepalive(struct wg_timers *t)
{
	struct wg_peer	 *peer = CONTAINER_OF(t, struct wg_peer, p_timers);

	if (t->t_persistent_keepalive_interval != 0)
		wg_grouptask_enqueue(peer, &peer->p_send_keepalive);
}

static void
wg_peer_timers_init(struct wg_peer *peer)
{
	struct wg_timers *t = &peer->p_timers;

	bzero(t, sizeof(*t));

	rw_init(&peer->p_timers.t_lock, "wg_peer_timers");
	callout_init(&t->t_retry_handshake, true);
	callout_init(&t->t_send_keepalive, true);
	callout_init(&t->t_new_handshake, true);
	callout_init(&t->t_zero_key_material, true);
	callout_init(&t->t_persistent_keepalive, true);
}

static void
wg_timers_disable(struct wg_timers *t)
{
	rw_wlock(&t->t_lock);
	t->t_disabled = 1;
	t->t_need_another_keepalive = 0;
	rw_wunlock(&t->t_lock);

	callout_del(&t->t_retry_handshake);
	callout_del(&t->t_send_keepalive);
	callout_del(&t->t_new_handshake);
	callout_del(&t->t_zero_key_material);
	callout_del(&t->t_persistent_keepalive);
}

void
wg_timers_set_persistent_keepalive(struct wg_timers *t, uint16_t interval)
{
	if (t->t_disabled)
		return;
	t->t_persistent_keepalive_interval = interval;
	wg_timers_run_persistent_keepalive(t);
}

int
wg_timers_get_persistent_keepalive(struct wg_timers *t, uint16_t *interval)
{
	*interval = t->t_persistent_keepalive_interval;
	return *interval > 0 ? 0 : ENOENT;
}

void
wg_timers_get_last_handshake(struct wg_timers *t, struct timespec *time)
{
	time->tv_sec = t->t_handshake_complete.tv_sec;
	time->tv_nsec = t->t_handshake_complete.tv_nsec;
}

static int
wg_timers_expired_handshake_last_sent(struct wg_timers *t)
{
	struct timespec uptime;
	struct timespec expire = { .tv_sec = REKEY_TIMEOUT, .tv_nsec = 0 };

	getnanouptime(&uptime);
	timespecadd(&t->t_handshake_last_sent, &expire, &expire);
	return timespeccmp(&uptime, &expire, >) ? ETIMEDOUT : 0;
}

static int
wg_timers_check_handshake_last_sent(struct wg_timers *t)
{
	int ret;

	if ((ret = wg_timers_expired_handshake_last_sent(t)) == ETIMEDOUT)
		getnanouptime(&t->t_handshake_last_sent);
	return (ret);
}

/* Queue */
void
wg_queue_init(struct wg_queue *q, const char *name)
{
	mtx_init(&q->q_mtx, name, NULL, MTX_DEF);
	mbufq_init(&q->q, MAX_QUEUED_PKT);
}

void
wg_queue_deinit(struct wg_queue*q)
{
	mtx_lock(&q->q_mtx);
	mbufq_drain(&q->q);
	mtx_unlock(&q->q_mtx);
	mtx_destroy(&q->q_mtx);
}

static struct mbuf *
wg_queue_dequeue(struct wg_queue *q, struct wg_tag **t)
{
	struct mbuf *m_, *m;

	m = NULL;
	mtx_lock(&q->q_mtx);
	m_ = mbufq_first(&q->q);
	if (m_ != NULL && (*t = wg_tag_get(m_))->t_done) {
		m = mbufq_dequeue(&q->q);
		m->m_flags &= ~M_ENQUEUED;
	}
	mtx_unlock(&q->q_mtx);
	return (m);
}

static int
wg_queue_len(struct wg_queue *q)
{

	return (mbufq_len(&q->q));
}

static int
wg_queue_in(struct wg_peer *peer, struct mbuf *m)
{
	struct buf_ring *parallel = peer->p_sc->sc_decap_ring;
	struct wg_queue		*serial = &peer->p_decap_queue;
	struct wg_tag		*t;
	int rc;

	MPASS(wg_tag_get(m) != NULL);

	mtx_lock(&serial->q_mtx);
	if ((rc = mbufq_enqueue(&serial->q, m)) == ENOBUFS) {
		wg_m_freem(m);
		if_inc_counter(peer->p_sc->sc_ifp, IFCOUNTER_OQDROPS, 1);
	} else {
		m->m_flags |= M_ENQUEUED;
		rc = buf_ring_enqueue(parallel, m);
		if (rc == ENOBUFS) {
			t = wg_tag_get(m);
			t->t_done = 1;
		}
	}
	mtx_unlock(&serial->q_mtx);
	return (rc);
}

int
wg_queue_out(struct wg_peer *peer, struct mbuf *m)
{
	struct buf_ring *parallel = peer->p_sc->sc_encap_ring;
	struct wg_queue		*serial = &peer->p_encap_queue;
	struct wg_tag		*t;
	int rc;

	if ((t = wg_tag_get(m)) == NULL) {
		wg_m_freem(m);
		return (ENOMEM);
	}
	t->t_peer = peer;
	mtx_lock(&serial->q_mtx);
	if ((rc = mbufq_enqueue(&serial->q, m)) == ENOBUFS) {
		wg_m_freem(m);
		if_inc_counter(peer->p_sc->sc_ifp, IFCOUNTER_OQDROPS, 1);
	} else {
		m->m_flags |= M_ENQUEUED;
		rc = buf_ring_enqueue(parallel, m);
		if (rc == ENOBUFS) {
			t = wg_tag_get(m);
			t->t_done = 1;
		}
	}
	mtx_unlock(&serial->q_mtx);
	return (rc);
}

/* Route */
int
wg_route_init(struct wg_route_table *tbl)
{
	int rc;

	tbl->t_count = 0;
	rc = rn_inithead((void **)&tbl->t_ip,
	    offsetof(struct sockaddr_in, sin_addr) * NBBY);

	if (rc == 0)
		return (ENOMEM);
	RADIX_NODE_HEAD_LOCK_INIT(tbl->t_ip);
#ifdef INET6
	rc = rn_inithead((void **)&tbl->t_ip6,
	    offsetof(struct sockaddr_in6, sin6_addr) * NBBY);
	if (rc == 0) {
		free(tbl->t_ip, M_RTABLE);
		return (ENOMEM);
	}
	RADIX_NODE_HEAD_LOCK_INIT(tbl->t_ip6);
#endif
	return (0);
}

void
wg_route_destroy(struct wg_route_table *tbl)
{
	RADIX_NODE_HEAD_DESTROY(tbl->t_ip);
	free(tbl->t_ip, M_RTABLE);
#ifdef INET6
	RADIX_NODE_HEAD_DESTROY(tbl->t_ip6);
	free(tbl->t_ip6, M_RTABLE);
#endif
}

int
wg_route_add(struct wg_route_table *tbl, struct wg_peer *peer,
			 const struct wg_allowedip *cidr_)
{
	struct radix_node	*node;
	struct radix_node_head	*root;
	struct wg_route *route;
	sa_family_t family;
	struct wg_allowedip *cidr;
	bool needfree = false;

	family = cidr_->a_addr.ss_family;
	if (family == AF_INET) {
		root = tbl->t_ip;
	} else if (family == AF_INET6) {
		root = tbl->t_ip6;
	} else {
		printf("bad sa_family %d\n", cidr_->a_addr.ss_family);
		return (EINVAL);
	}
	route = malloc(sizeof(*route), M_WG, M_WAITOK|M_ZERO);
	route->r_cidr = *cidr_;
	route->r_peer = peer;
	cidr = &route->r_cidr;

	RADIX_NODE_HEAD_LOCK(root);
	node = root->rnh_addaddr(&cidr->a_addr, &cidr->a_mask, &root->rh,
							route->r_nodes);
	if (node == route->r_nodes) {
		tbl->t_count++;
		CK_LIST_INSERT_HEAD(&peer->p_routes, route, r_entry);
	} else {
		needfree = true;
	}
	RADIX_NODE_HEAD_UNLOCK(root);
	if (needfree) {
		free(route, M_WG);
	}
	return (0);
}

struct peer_del_arg {
	struct radix_node_head * pda_head;
	struct wg_peer *pda_peer;
	struct wg_route_table *pda_tbl;
};

static int
wg_peer_remove(struct radix_node *rn, void *arg)
{
	struct peer_del_arg *pda = arg;
	struct wg_peer *peer = pda->pda_peer;
	struct radix_node_head * rnh = pda->pda_head;
	struct wg_route_table *tbl = pda->pda_tbl;
	struct wg_route *route = (struct wg_route *)rn;
	struct radix_node *x;

	if (route->r_peer != peer)
		return (0);
	x = (struct radix_node *)rnh->rnh_deladdr(&route->r_cidr.a_addr, NULL, &rnh->rh);
	if (x != NULL)	 {
		tbl->t_count--;
		CK_LIST_REMOVE(route, r_entry);
		free(route, M_WG);
	}
	return (0);
}

int
wg_route_delete(struct wg_route_table *tbl, struct wg_peer *peer)
{
	struct peer_del_arg pda;

	pda.pda_peer = peer;
	pda.pda_tbl = tbl;
	RADIX_NODE_HEAD_LOCK(tbl->t_ip);
	pda.pda_head = tbl->t_ip;
	rn_walktree(&tbl->t_ip->rh, wg_peer_remove, &pda);
	RADIX_NODE_HEAD_UNLOCK(tbl->t_ip);

	RADIX_NODE_HEAD_LOCK(tbl->t_ip6);
	pda.pda_head = tbl->t_ip6;
	rn_walktree(&tbl->t_ip6->rh, wg_peer_remove, &pda);
	RADIX_NODE_HEAD_UNLOCK(tbl->t_ip6);
	return (0);
}

struct wg_peer *
wg_route_lookup(struct wg_route_table *tbl, struct mbuf *m,
		enum route_direction dir)
{
	RADIX_NODE_HEAD_RLOCK_TRACKER;
	struct ip *iphdr;
	struct ip6_hdr *ip6hdr;
	struct radix_node_head *root;
	struct radix_node	*node;
	struct wg_peer	*peer = NULL;
	struct sockaddr_in sin;
	struct sockaddr_in6 sin6;
	void *addr;
	int version;

	NET_EPOCH_ASSERT();
	iphdr = mtod(m, struct ip *);
	version = iphdr->ip_v;

	if (__predict_false(dir != IN && dir != OUT))
		panic("invalid route dir: %d\n", dir);

	if (version == 4) {
		root = tbl->t_ip;
		memset(&sin, 0, sizeof(sin));
		sin.sin_len = sizeof(struct sockaddr_in);
		if (dir == IN)
			sin.sin_addr = iphdr->ip_src;
		else
			sin.sin_addr = iphdr->ip_dst;
		addr = &sin;
	} else if (version == 6) {
		ip6hdr = mtod(m, struct ip6_hdr *);
		memset(&sin6, 0, sizeof(sin6));
		sin6.sin6_len = sizeof(struct sockaddr_in6);

		root = tbl->t_ip6;
		if (dir == IN)
			addr = &ip6hdr->ip6_src;
		else
			addr = &ip6hdr->ip6_dst;
		memcpy(&sin6.sin6_addr, addr, sizeof(sin6.sin6_addr));
		addr = &sin6;
	} else  {
		log(LOG_WARNING, "%s bad version %d\n", __func__, version);
		return (NULL);
	}
	RADIX_NODE_HEAD_RLOCK(root);
	if ((node = root->rnh_matchaddr(addr, &root->rh)) != NULL) {
		peer = ((struct wg_route *) node)->r_peer;
	} else {
		log(LOG_WARNING, "matchaddr failed\n");
	}
	RADIX_NODE_HEAD_RUNLOCK(root);
	return (peer);