summaryrefslogtreecommitdiffstats
path: root/src/if_wg.c
blob: 1674b519b0016b946ad27ea84637c497720ad870 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
/*
 * Copyright (c) 2019 Matt Dunwoodie
 *
 * 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 <sys/types.h>
#include <sys/systm.h>
#include <sys/param.h>
#include <sys/time.h>

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

#include <sys/sockio.h>
#include <sys/socketvar.h>
#include <sys/errno.h>
#include <sys/proc.h>
#include <sys/rwlock.h>
#include <sys/protosw.h>
#include <sys/hashmap.h>
#include <sys/mpq.h>

#include <net/if.h>
#include <net/if_var.h>
#include <net/if_types.h>
#include <net/pfvar.h>
#include <net/wireguard.h>
#include <net/if_wg.h>

#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/ip_icmp.h>
#include <netinet/icmp6.h>
#include <netinet/in_pcb.h>

#include "bpfilter.h"
#if NBPFILTER > 0
#include <net/bpf.h>
#endif

//#define WG_SESSION_GET(p, session) (&(p)->p_sess[(p)->p_sessi + session])
#define WG_DEBUG 1
#ifdef WG_DEBUG
#define DPRINTF(...)    do { printf(__VA_ARGS__); } while (0)
#else
#define DPRINTF(...)    do { } while (0)
#endif

enum wg_session_type {
	WG_SESSION_NEXT,
	WG_SESSION_CURRENT,
	WG_SESSION_OLD,
};

struct wg_peer {
	struct wg_softc		*p_sc;
	union wg_ip		p_ip;
	uint8_t			p_init_count;
	u_int64_t		p_tx_bytes, p_rx_bytes;
	struct mbuf_queue	p_outgoing;
	SLIST_HEAD(, wg_route) p_aip;

	struct wg_handshake p_hs;
	struct wg_session p_sess;//[3];
	//int p_sessi;

	struct wg_timers {
		struct timeout	t_ka;
		struct timeout	t_pka;
		struct timeout	t_broken;
		struct timeout	t_reinit;
		struct timeout	t_cleanup;
		struct timespec	t_last_initiation;
		struct timespec	t_last_handshake;
		uint16_t	t_pka_interval;
	} p_timers;
};

struct wg_pkt {
	struct mbuf *p_m;
	struct wg_peer *p_p;
	struct wg_softc *p_sc;
	enum wg_pkt_type p_type;
	enum wg_pkt_state {
		WG_PKT_NEW = 0,
		WG_PKT_PASS,
		WG_PKT_DEAD,
		WG_PKT_FREE,
	} p_state;
	union wg_ip	p_ip;
};

struct wg_peer_item {
	u_int8_t key[WG_KEY_SIZE];
	struct wg_peer *peer;
};

struct wg_id_item {
	u_int32_t id;
	struct wg_peer *peer;
};

struct wg_route {
	SLIST_ENTRY(wg_route) r_next;
	struct wg_cidr r_cidr;
	struct wg_peer *r_peer;
};

struct wg_softc {
	SLIST_ENTRY(wg_softc)	sc_next;
	struct ifnet 	sc_if;

	struct socket	*sc_so4;
	struct socket	*sc_so6;
	in_port_t	sc_port;

	struct wg_keypair sc_kp;
	struct wg_cookie sc_cookie;

	struct art_root *sc_ip_rt, *sc_ip6_rt;

	HASHMAP_HEAD(wg_id_hashmap, wg_id_item)	sc_id_hashmap;
	HASHMAP_HEAD(wg_peer_hashmap, wg_peer_item)	sc_peer_hashmap;

	MPQ_HEAD(wg_pkt_queue, struct wg_pkt) sc_txq, sc_rxq, sc_txq_slow, sc_rxq_slow;
};

/* Lookup tables */
int wg_route_register(struct wg_softc *, struct wg_peer *, struct wg_cidr *);
struct wg_peer *wg_route_lookup(struct wg_softc *, struct mbuf *, bool);

u_int64_t wg_id_hash(struct wg_id_item *);
int wg_id_cmp(struct wg_id_item *, struct wg_id_item *);
uint32_t wg_id_create(struct wg_softc *, struct wg_peer *);
void wg_id_destroy(struct wg_softc *, uint32_t);
struct wg_peer *wg_id_lookup(struct wg_softc *, uint32_t);

int wg_peer_cmp(struct wg_peer_item *, struct wg_peer_item *);
u_int64_t wg_peer_hash(struct wg_peer_item *);
struct wg_peer *wg_peer_create(struct wg_softc *, uint8_t [WG_KEY_SIZE]);
void wg_peer_destroy(struct wg_softc *, struct wg_peer *);
struct wg_peer *wg_peer_lookup(struct wg_softc *, uint8_t *);

/* Send packet functions */
void wg_send_pkt(struct wg_softc *, struct wg_peer *, enum wg_pkt_type);
void wg_want_reinit(struct wg_peer *);
void wg_want_init(struct wg_peer *);
void wg_want_keepalive(struct wg_peer *);

/* Timer functions */
void wg_timer_broken(void *);
void wg_timer_reinit(void *);
void wg_timer_cleanup(void *);
void wg_timer_setup(struct wg_timers *, struct wg_peer *);
void wg_timer_persistent_keepalive_tick(struct wg_timers *);
void wg_timer_cleanup_tick(struct wg_timers *);
void wg_timer_keepalive_flag(struct wg_timers *);
void wg_timer_keepalive_unflag(struct wg_timers *);
void wg_timer_broken_flag(struct wg_timers *);
void wg_timer_broken_unflag(struct wg_timers *);
void wg_timer_reinit_flag(struct wg_timers *);
void wg_timer_reinit_unflag(struct wg_timers *);

/* TX/RX functions */
void wg_transmit_slow(struct wg_pkt *);
void wg_receive_slow(struct wg_pkt *);
void wg_free_pkt(struct wg_pkt *);
void wg_transport_encrypt(struct wg_pkt *);
void wg_transport_decrypt(struct wg_pkt *);
struct mbuf *wg_input(void *, struct mbuf *, struct sockaddr *, int);
int wg_output(struct ifnet *, struct mbuf *, struct sockaddr *, struct rtentry *);
void wg_input_deliver(struct wg_pkt *);
void wg_output_deliver(struct wg_pkt *);

/* Interface functions */
void wgattach(int);
struct wg_softc *wg_softc_create(void);
void wg_softc_destroy(struct wg_softc *);
int wg_clone_create(struct if_clone *, int);
int wg_clone_destroy(struct ifnet *);
int wg_bind_port(struct wg_softc *);
int wg_ioctl_set_peer(struct wg_softc *, u_long, struct wg_set_peer *);
int wg_ioctl_set_serv(struct wg_softc *, u_long, struct wg_set_serv *);
void wg_ioctl_get_serv(struct wg_softc *, struct wg_get_serv *);
int wg_ioctl_get_peer(struct wg_softc *, struct wg_get_peer *);
int wg_ioctl(struct ifnet *, u_long, caddr_t);

SIPHASH_KEY wg_siphashkey;
MPQ_GENERATE(wg_pkt_queue, struct wg_pkt);
#define WG_PKT_INIT(p, m, sc, type) { .p_p = p, .p_m = m, .p_sc = sc, \
	.p_state = WG_PKT_NEW, .p_type = type }

int
wg_route_register(struct wg_softc *sc, struct wg_peer *p, struct wg_cidr *cidr)
{
	struct srp_ref	sr;
	struct art_node	*node;
	struct art_root	*root;
	struct wg_route *route;

	if (cidr->c_af == AF_INET)
		root = sc->sc_ip_rt;
	else if (cidr->c_af == AF_INET6)
		root = sc->sc_ip6_rt;
	else
		return EINVAL;

	rw_enter_write(&root->ar_lock);

	/* We hijack the an_gc element (struct art) to store our own route. */
	if (p) {
		node = malloc(sizeof(*node), M_DEVBUF, M_WAITOK | M_ZERO);

		/*
		 * art_insert will return current route if it exists, therefore
		 * we want to make sure not to have two routes to the same CIDR.
		 */
		if (art_insert(root, node, &cidr->c_ip, cidr->c_mask) != node) {
			free(node, M_DEVBUF, sizeof(*node));
			rw_exit_write(&root->ar_lock);
			return EEXIST;
		}

		route = malloc(sizeof(struct wg_route), M_DEVBUF, M_WAITOK);
		node->an_gc = (struct art_node *) route;
		route->r_peer = p;
		route->r_cidr = *cidr;
		SLIST_INSERT_HEAD(&p->p_aip, route, r_next);
	} else {
		node = art_lookup(root, &cidr->c_ip, cidr->c_mask, &sr);
		if (node == NULL) {
			srp_leave(&sr);
			rw_exit_write(&root->ar_lock);
			return ENOATTR;
		}

		if (art_delete(root, node, &cidr->c_ip, cidr->c_mask) == NULL)
			panic("art_delete failed to delete node %p", node);

		srp_leave(&sr);
		route = (struct wg_route *) node->an_gc;
		SLIST_REMOVE(&route->r_peer->p_aip, route, wg_route, r_next);
		free(route, M_DEVBUF, sizeof(struct wg_route));
		free(node, M_DEVBUF, sizeof(*node));
	}

	rw_exit_write(&root->ar_lock);

	return 0;
}

struct wg_peer *
wg_route_lookup(struct wg_softc * sc, struct mbuf * m, bool out)
{
	struct ip	*iphdr;
	struct ip6_hdr	*ip6hdr;
	struct art_node	*node;
	struct srp_ref	sr;
	struct wg_peer	*p = NULL;

	switch (m->m_pkthdr.ph_family) {
	case AF_INET:
		iphdr = mtod(m, struct ip *);
		if (out)
			node = art_match(sc->sc_ip_rt, &iphdr->ip_dst, &sr);
		else
			node = art_match(sc->sc_ip_rt, &iphdr->ip_src, &sr);
		break;
	case AF_INET6:
		ip6hdr = mtod(m, struct ip6_hdr *);
		if (out)
			node = art_match(sc->sc_ip6_rt, &ip6hdr->ip6_dst, &sr);
		else
			node = art_match(sc->sc_ip6_rt, &ip6hdr->ip6_src, &sr);
		break;
	default:
		return NULL;
	}

	if (node != NULL)
		p = ((struct wg_route *) node->an_gc)->r_peer;

	srp_leave(&sr);

	return p;
}

u_int64_t
wg_id_hash(struct wg_id_item *item)
{
	return item->id;
}

int
wg_id_cmp(struct wg_id_item *a, struct wg_id_item *b)
{
	return a->id == b->id;
}

uint32_t
wg_id_create(struct wg_softc *sc, struct wg_peer *p)
{
	struct wg_id_item item = { arc4random() , p };
	HASHMAP_SET(&sc->sc_id_hashmap, item);
	DPRINTF("wg_id_create: %p - 0x%08x\n", p, item.id);
	return item.id;
}

void
wg_id_destroy(struct wg_softc *sc, uint32_t id)
{
	struct wg_id_item item = { id, NULL };
	DPRINTF("wg_id_destroy: 0x%08x\n", id);
	HASHMAP_UNSET(&sc->sc_id_hashmap, item);
}

struct wg_peer *
wg_id_lookup(struct wg_softc *sc, uint32_t id)
{
	struct wg_id_item item = { id, NULL };
	HASHMAP_LOOKUP(&sc->sc_id_hashmap, item);
	return item.peer;
}

int
wg_peer_cmp(struct wg_peer_item *a, struct wg_peer_item *b)
{
	return memcmp(a->key, b->key, WG_KEY_SIZE) == 0;
}

u_int64_t
wg_peer_hash(struct wg_peer_item *item)
{
	return SipHash24(&wg_siphashkey, item->key, WG_KEY_SIZE);
}

struct wg_peer *
wg_peer_create(struct wg_softc *sc, uint8_t key[WG_KEY_SIZE])
{
	size_t num_peers;
	struct wg_peer *p;
	struct wg_peer_item item;

	p = malloc(sizeof(struct wg_peer), M_DEVBUF, M_WAITOK | M_ZERO);
	p->p_sc = sc;

	mq_init(&p->p_outgoing, IFQ_MAXLEN, IPL_NET);
	wg_handshake_init(&p->p_hs);
	wg_session_init(&p->p_sess);

	p->p_hs.hs_skey = &sc->sc_kp;
	memcpy(p->p_hs.hs_spub, key, WG_KEY_SIZE);

	wg_timer_setup(&p->p_timers, p);

	/* Resize hashmap to fit peer */
	num_peers = HASHMAP_NUM(&sc->sc_peer_hashmap) + 1;
	HASHMAP_RESIZE(&sc->sc_peer_hashmap, wg_peer_hashmap, num_peers);
	HASHMAP_RESIZE(&sc->sc_id_hashmap, wg_id_hashmap, num_peers * 3);

	/* Insert peer to hashmap */
	item.peer = p;
	memcpy(item.key, key, WG_KEY_SIZE);
	HASHMAP_SET(&sc->sc_peer_hashmap, item);

	return p;
}

void
wg_peer_destroy(struct wg_softc *sc, struct wg_peer *p)
{
	struct wg_peer_item item;
	struct wg_route *route, *troute;

	/* Remove all allowed IPs for peer */
	SLIST_FOREACH_SAFE(route, &p->p_aip, r_next, troute)
		wg_route_register(sc, NULL, &route->r_cidr);

	/* Remove all session IDs for peer */
	//wg_conn_reset(&p->p_conn);
	wg_timer_cleanup(p);

	/* Remove from key hashmap */
	memcpy(item.key, p->p_hs.hs_skey->pub, WG_KEY_SIZE);
	HASHMAP_UNSET(&sc->sc_peer_hashmap, item);

	/* Barrier on packets */
	MPQ_BARRIER(&sc->sc_txq);
	MPQ_BARRIER(&sc->sc_rxq);
	MPQ_BARRIER(&sc->sc_txq_slow);
	MPQ_BARRIER(&sc->sc_rxq_slow);

	/* Finally, no references should exist, we can free */
	explicit_bzero(p, sizeof(struct wg_peer));
	free(p, M_DEVBUF, sizeof(struct wg_peer));
}

struct wg_peer *
wg_peer_lookup(struct wg_softc *sc, uint8_t *pubkey)
{
	struct wg_peer_item item = { {0}, NULL };
	memcpy(item.key, pubkey, WG_KEY_SIZE);
	HASHMAP_LOOKUP(&sc->sc_peer_hashmap, item);
	return item.peer;
}

void
wg_peer_new_session(struct wg_softc *sc, struct wg_peer *p)
{
	struct mbuf *m;

	wg_timer_reinit_unflag(&p->p_timers);
	wg_timer_cleanup_tick(&p->p_timers);

	if (mq_empty(&p->p_outgoing))
		wg_want_keepalive(p);

	while ((m = mq_dequeue(&p->p_outgoing)) != NULL) {
		struct wg_pkt pkt = WG_PKT_INIT(p, m, sc, WG_PKT_TRANSPORT);

		if (MPQ_ADD(wg_pkt_queue, &sc->sc_txq, &pkt) != 0) {
			counters_inc(sc->sc_if.if_counters, ifc_oqdrops);
			m_free(m);
		}
	}

	getnanotime(&p->p_timers.t_last_handshake);
}

void
wg_send_pkt(struct wg_softc *sc, struct wg_peer *p, enum wg_pkt_type t)
{
	struct mbuf *m = m_clget(NULL, M_NOWAIT, 1000);
	if (m == NULL)
		return;

	m->m_len = 0;
	m_calchdrlen(m);
	struct wg_pkt pkt = WG_PKT_INIT(p, m, sc, t);
	DPRINTF("wg_send_pkt: sending packet %d\n", t);

	switch (pkt.p_type) {
	case WG_PKT_INITIATION:
	case WG_PKT_RESPONSE:
	case WG_PKT_COOKIE:
		if (MPQ_ADD(wg_pkt_queue, &sc->sc_txq_slow, &pkt) != 0)
			m_freem(pkt.p_m);
		break;
	case WG_PKT_TRANSPORT:
		if (MPQ_ADD(wg_pkt_queue, &sc->sc_txq, &pkt) != 0)
			m_freem(pkt.p_m);
		break;
	case WG_PKT_UNKNOWN:
		panic("wg_send_pkt invalid pkt.p_type\n");
	}
}

void
wg_want_reinit(struct wg_peer *p)
{
	DPRINTF("wg_want_reinit\n");
	if (wg_timespec_timedout(&p->p_timers.t_last_initiation, WG_REKEY_TIMEOUT) &&
	    p->p_init_count < 20) {
		DPRINTF("wg_want_reinit: granted\n");
		wg_send_pkt(p->p_sc, p, WG_PKT_INITIATION);
		getnanotime(&p->p_timers.t_last_initiation);
		wg_timer_reinit_flag(&p->p_timers);
		p->p_init_count++;
	}
}

void
wg_want_init(struct wg_peer *p)
{
	DPRINTF("wg_want_init\n");
	p->p_init_count = 0;
	wg_want_reinit(p);
}

void
wg_want_keepalive(struct wg_peer *p)
{
	DPRINTF("wg_want_keepalive\n");
	wg_send_pkt(p->p_sc, p, WG_PKT_TRANSPORT);
}

void
wg_timer_broken(void *_p)
{
	DPRINTF("wg_timer_broken\n");
	struct wg_peer *p = _p;
	//wg_conn_reset(&p->p_conn);
	wg_want_init(p);
}

void
wg_timer_reinit(void *_p)
{
	DPRINTF("wg_timer_reinit\n");
	struct wg_peer *p = _p;
	wg_want_reinit(p);
}

void
wg_timer_cleanup(void *_p)
{
	DPRINTF("wg_timer_cleanup\n");
	struct wg_peer *p = _p;
	//wg_conn_reset(&p->p_conn);
	timeout_del(&p->p_timers.t_ka);
	timeout_del(&p->p_timers.t_pka);
	timeout_del(&p->p_timers.t_broken);
	timeout_del(&p->p_timers.t_reinit);
	timeout_del(&p->p_timers.t_cleanup);
}

void
wg_timer_setup(struct wg_timers *t, struct wg_peer *p)
{
	DPRINTF("wg_timer_setup\n");
	timeout_set_proc(&t->t_ka, (void (*)(void *)) wg_want_keepalive, p);
	timeout_set_proc(&t->t_pka, (void (*)(void *)) wg_want_keepalive, p);
	timeout_set_proc(&t->t_broken, wg_timer_broken, p);
	timeout_set_proc(&t->t_reinit, wg_timer_reinit, p);
	timeout_set_proc(&t->t_cleanup, wg_timer_cleanup, p);
}

void
wg_timer_persistent_keepalive_tick(struct wg_timers *t)
{
	if (t->t_pka_interval > 0)
		timeout_add_sec(&t->t_pka, t->t_pka_interval);
}

void
wg_timer_cleanup_tick(struct wg_timers *t)
{
	timeout_add_sec(&t->t_cleanup, WG_REJECT_AFTER_TIME * 3);
}

void
wg_timer_keepalive_flag(struct wg_timers *t)
{
	timeout_add_sec(&t->t_ka, WG_KEEPALIVE_TIMEOUT);
}

void
wg_timer_keepalive_unflag(struct wg_timers *t)
{
	timeout_del(&t->t_ka);
}

void
wg_timer_broken_flag(struct wg_timers *t)
{
	if (timeout_pending(&t->t_broken) == 0)
		timeout_add_sec(&t->t_broken, WG_REKEY_TIMEOUT + WG_KEEPALIVE_TIMEOUT);
}

void
wg_timer_broken_unflag(struct wg_timers *t)
{
	timeout_del(&t->t_broken);
}

void
wg_timer_reinit_flag(struct wg_timers *t)
{
	timeout_add_sec(&t->t_reinit, WG_REKEY_TIMEOUT);
}

void
wg_timer_reinit_unflag(struct wg_timers *t)
{
	timeout_del(&t->t_reinit);
}

void
wg_transmit_slow(struct wg_pkt *pkt)
{
	uint32_t id;
	enum wg_error e;
	struct wg_msg_initiation *init;
	struct wg_msg_response *resp;
	struct wg_msg_cookie *cookie;

	switch (pkt->p_type) {
	case WG_PKT_INITIATION:
		DPRINTF("wg_transmit_slow: initiation\n");
		init = mtod(pkt->p_m, struct wg_msg_initiation *);
		pkt->p_m->m_len = sizeof(struct wg_msg_initiation);

		id = wg_handshake_clean(&pkt->p_p->p_hs);
		wg_id_destroy(pkt->p_sc, id);
		id = wg_id_create(pkt->p_sc, pkt->p_p);
		if ((e = wg_handshake_make_initiation(&pkt->p_p->p_hs, id, init)) != WG_OK) {
			DPRINTF("wg_transmit_slow: unable to initiate %d\n", e);
			goto dead;
		}
		break;
	case WG_PKT_RESPONSE:
		DPRINTF("wg_transmit_slow: response\n");
		resp = mtod(pkt->p_m, struct wg_msg_response *);
		pkt->p_m->m_len = sizeof(struct wg_msg_response);

		wg_id_destroy(pkt->p_sc, pkt->p_p->p_hs.hs_local_id);
		id = wg_id_create(pkt->p_sc, pkt->p_p);

		if ((e = wg_handshake_make_response(&pkt->p_p->p_hs, id, resp)) != WG_OK) {
			DPRINTF("wg_transmit_slow: response bad state %d\n", e);
			goto dead;
		}

		if ((e = wg_session_from_handshake(&pkt->p_p->p_sess, &pkt->p_p->p_hs)) != WG_OK) {
			DPRINTF("wg_transmit_slow: unable to session %d\n", e);
			goto dead;
		};

		wg_peer_new_session(pkt->p_sc, pkt->p_p);
		break;
	case WG_PKT_COOKIE:
		DPRINTF("wg_transmit_slow: cookie\n");
		cookie = mtod(pkt->p_m, struct wg_msg_cookie *);
		pkt->p_m->m_len = sizeof(struct wg_msg_cookie);
		wg_handshake_make_cookie(&pkt->p_sc->sc_kp, &pkt->p_sc->sc_cookie,
		    0, NULL, 0, NULL, cookie);
		break;
	default:
		panic("wg_transmit_slow invalid pkt->p_type\n");
	}

	m_calchdrlen(pkt->p_m);
	pkt->p_state = WG_PKT_PASS;
	return;
dead:
	pkt->p_state = WG_PKT_DEAD;
}

void
wg_receive_slow(struct wg_pkt *pkt)
{
	enum wg_error e;
	struct wg_peer *p;
	struct wg_handshake hs;
	struct wg_msg_initiation *init;
	struct wg_msg_response *resp;
	struct wg_msg_cookie *cookie;

	switch (pkt->p_type) {
	case WG_PKT_INITIATION:
		init = mtod(pkt->p_m, struct wg_msg_initiation *);
		if ((e = wg_handshake_recv_initiation(&hs, &pkt->p_sc->sc_kp, init)) != WG_OK) {
			DPRINTF("wg_receive_slow: bad initiation %d\n", e);
			goto dead;
		}

		if ((p = wg_peer_lookup(pkt->p_sc, hs.hs_spub)) == NULL) {
			DPRINTF("wg_receive_slow: unable to find initiation peer\n");
			goto dead;
		}

		if ((e = wg_handshake_merge(&p->p_hs, &hs)) != WG_OK) {
			DPRINTF("wg_receive_slow: unable to merge %d\n", e);
			goto dead;
		}

		wg_send_pkt(p->p_sc, p, WG_PKT_RESPONSE);
		break;
	case WG_PKT_RESPONSE:
		resp = mtod(pkt->p_m, struct wg_msg_response *);
		p = wg_id_lookup(pkt->p_sc, resp->receiver);

		if (p == NULL) {
			DPRINTF("wg_receive_slow: unknown response id %x\n", resp->receiver);
			goto dead;
		}

		if ((e = wg_handshake_recv_response(&p->p_hs, resp)) != 0) {
			DPRINTF("wg_receive_slow: bad response %d\n", e);
			goto dead;
		}

		if ((e = wg_session_from_handshake(&p->p_sess, &p->p_hs)) != WG_OK) {
			DPRINTF("wg_receive_slow: unable to session %d\n", e);
			goto dead;
		};

		wg_peer_new_session(pkt->p_sc, p);
		break;
	case WG_PKT_COOKIE:
		cookie = mtod(pkt->p_m, struct wg_msg_cookie *);
		p = wg_id_lookup(pkt->p_sc, cookie->receiver);
		if (p == NULL) {
			DPRINTF("wg_receive_slow: unknown cookie id %x\n", cookie->receiver);
			goto dead;
		}

		if ((e = wg_handshake_recv_cookie(&p->p_hs, cookie)) != 0) {
			DPRINTF("wg_receive_slow: bad cookie %d\n", e);
			goto dead;
		}

		break;
	default:
		panic("wg_transmit_slow invalid pkt->p_type\n");
	}

	m_calchdrlen(pkt->p_m);
	pkt->p_state = WG_PKT_PASS;
	pkt->p_p = p;
	return;
dead:
	pkt->p_state = WG_PKT_DEAD;
	return;
}

void
wg_free_pkt(struct wg_pkt *pkt)
{
	/* RACEY! competing with transport thread */
	if (pkt->p_state == WG_PKT_PASS)
		pkt->p_p->p_ip = pkt->p_ip;
	m_free(pkt->p_m);
}

void
wg_transport_encrypt(struct wg_pkt *pkt)
{
	struct wg_msg_transport *msg;

	struct mbuf *m = pkt->p_m;
	struct wg_session *s = &pkt->p_p->p_sess;
	size_t encrypted_len, padding_len, plain_len;

	if (m_defrag(m, M_NOWAIT)) {
		counters_inc(pkt->p_sc->sc_if.if_counters, ifc_oerrors);
		pkt->p_state = WG_PKT_FREE;
		return;
	}

	plain_len = m->m_pkthdr.len;
	padding_len = WG_PADDING_SIZE(plain_len);
	encrypted_len = WG_ENCRYPTED_SIZE(plain_len + padding_len);

	pkt->p_m = m_clget(NULL, M_NOWAIT, encrypted_len + sizeof(struct wg_msg_transport));
	if (pkt->p_m == NULL) {
		m_free(m);
		pkt->p_state = WG_PKT_FREE;
		return;
	}

	pkt->p_m->m_len = encrypted_len + sizeof(struct wg_msg_transport);
	m_calchdrlen(pkt->p_m);

	msg = mtod(pkt->p_m, struct wg_msg_transport *);
	memcpy(msg->data, mtod(m, void *), plain_len);
	bzero(msg->data + plain_len, padding_len);

	switch (wg_session_encrypt(s, msg, plain_len + padding_len)) {
	case WG_REKEY:
		wg_want_init(pkt->p_p);
	case WG_OK:
		break;
	case WG_REJECT:
		wg_want_init(pkt->p_p);
		if (mq_push(&pkt->p_p->p_outgoing, m) != 0)
			counters_inc(pkt->p_sc->sc_if.if_counters, ifc_oqdrops);
		pkt->p_state = WG_PKT_DEAD;
		return;
	default:
		pkt->p_state = WG_PKT_DEAD;
		return;
	}

#if NBPFILTER > 0
	if (pkt->p_p->p_sc->sc_if.if_bpf && m->m_pkthdr.len > 0)
		bpf_mtap_af(pkt->p_p->p_sc->sc_if.if_bpf, m->m_pkthdr.ph_family, m, BPF_DIRECTION_OUT);
#endif
	pkt->p_p->p_tx_bytes += m->m_pkthdr.len;
	counters_pkt(pkt->p_p->p_sc->sc_if.if_counters, ifc_opackets, ifc_obytes, m->m_pkthdr.len);

	pkt->p_state = WG_PKT_PASS;

	wg_timer_keepalive_unflag(&pkt->p_p->p_timers);
	wg_timer_persistent_keepalive_tick(&pkt->p_p->p_timers);
	if (plain_len > 0) {
		wg_timer_broken_flag(&pkt->p_p->p_timers);
	}

	/* free original packet */
	m_free(m);
}

void
wg_transport_decrypt(struct wg_pkt *pkt)
{
	size_t newlen;
	struct wg_session *s;
	struct wg_softc *sc = pkt->p_sc;
	struct mbuf *m = pkt->p_m;
	struct wg_msg_transport *msg = mtod(m, struct wg_msg_transport *);

	pkt->p_p = wg_id_lookup(sc, msg->receiver);
	if (pkt->p_p == NULL) {
		pkt->p_state = WG_PKT_DEAD;
		return;
	}

	s = &pkt->p_p->p_sess;

	switch (wg_session_decrypt(s, msg, m->m_pkthdr.len)) {
	case WG_REKEY:
		wg_want_init(pkt->p_p);
	case WG_OK:
		break;
	default:
		pkt->p_state = WG_PKT_DEAD;
		return;
	}

	m_adj(m, sizeof(struct wg_msg_transport));

	if (m->m_pkthdr.len == WG_ENCRYPTED_SIZE(0)) {
		pkt->p_state = WG_PKT_DEAD;
		goto keepalive;
	}

	if ((mtod(m, u_int8_t *)[0] >> 4) == IPVERSION &&
		m->m_pkthdr.len >= sizeof(struct ip)) {

		m->m_pkthdr.ph_family = AF_INET;
		newlen = be16toh(mtod(m, struct ip *)->ip_len);
	} else if ((mtod(m, u_int8_t *)[0] >> 4) == IPV6_VERSION >> 4 &&
		m->m_pkthdr.len >= sizeof(struct ip6_hdr)) {

		m->m_pkthdr.ph_family = AF_INET6;
		newlen = be16toh(mtod(m, struct ip6_hdr *)->ip6_plen) + sizeof(struct ip6_hdr);
	} else {
		pkt->p_state = WG_PKT_DEAD;
		return;
	}

	/* Prevent malicious packets from accessing out of bounds memory */
	if (newlen > m->m_pkthdr.len) {
		pkt->p_state = WG_PKT_DEAD;
		return;
	}

	m->m_len = newlen;
	m_calchdrlen(m);

	m->m_pkthdr.ph_ifidx = sc->sc_if.if_index;
	m->m_pkthdr.ph_rtableid = sc->sc_if.if_rdomain;
	m->m_flags &= ~(M_MCAST | M_BCAST);

	pf_pkt_addr_changed(m);

	/* Lookup outgoing route for incoming packet ip src, for crypto key
	 * routing. 'false' indicates src address */
	if (wg_route_lookup(sc, m, false) != pkt->p_p) {
		pkt->p_state = WG_PKT_DEAD;
		return;
	}

#if NBPFILTER > 0
	if (sc->sc_if.if_bpf)
		bpf_mtap_af(sc->sc_if.if_bpf, m->m_pkthdr.ph_family, m, BPF_DIRECTION_IN);
#endif

	pkt->p_p->p_rx_bytes += m->m_pkthdr.len;
	counters_pkt(sc->sc_if.if_counters, ifc_ipackets, ifc_ibytes, m->m_pkthdr.len);
	pkt->p_state = WG_PKT_PASS;

	/* Non keepalive */
	wg_timer_keepalive_flag(&pkt->p_p->p_timers);

keepalive:
	wg_timer_persistent_keepalive_tick(&pkt->p_p->p_timers);
	wg_timer_broken_unflag(&pkt->p_p->p_timers);
}

struct mbuf *
wg_input(void *_sc, struct mbuf *m, struct sockaddr *sa, int hlen)
{
	struct wg_softc *sc = _sc;

	if (!ISSET(sc->sc_if.if_flags, IFF_RUNNING))
		goto free;

	m_adj(m, hlen);

	if (m_defrag(m, M_NOWAIT))
		return NULL;

	struct wg_pkt pkt = WG_PKT_INIT(NULL, m, sc, wg_pkt_type(mtod(m, uint8_t *), m->m_pkthdr.len));

	memcpy(&pkt.p_ip, sa, sa->sa_len);
	switch (pkt.p_type) {
	case WG_PKT_INITIATION:
	case WG_PKT_RESPONSE:
		if (MPQ_SERIAL_LEN(&sc->sc_rxq_slow) > MPQ_GET_SIZE(&sc->sc_rxq_slow) / 4 &&
		    wg_handshake_valid_mac2(&sc->sc_cookie, mtod(m, uint8_t *),
		        m->m_pkthdr.len) == WG_MAC) {
			/*wg_send_pkt();*/
			printf("want cookie!\n");
		}
	case WG_PKT_COOKIE:
		if (MPQ_ADD(wg_pkt_queue, &sc->sc_rxq_slow, &pkt) != 0)
			goto free;
		break;
	case WG_PKT_TRANSPORT:
		if (MPQ_ADD(wg_pkt_queue, &sc->sc_rxq, &pkt) != 0)
			goto free;
		break;
	case WG_PKT_UNKNOWN:
		goto free;
		break;
	}

	return NULL;
free:
	m_free(m);
	counters_inc(sc->sc_if.if_counters, ifc_ierrors);
	return NULL;
}

int
wg_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *sa, struct rtentry *rt)
{
	struct wg_peer *p;
	struct wg_softc *sc = ifp->if_softc;
	int error = 0;

	if (!ISSET(sc->sc_if.if_flags, IFF_RUNNING)) {
		error = EIO;
		goto free;
	}

	if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6) {
		counters_inc(sc->sc_if.if_counters, ifc_noproto);
		goto free;
	}

	m->m_pkthdr.ph_family = sa->sa_family;

	if ((p = wg_route_lookup(sc, m, true)) == NULL ||
	     p->p_ip.sa.sa_family == AF_UNSPEC) {
		if (m->m_pkthdr.ph_family == AF_INET)
			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
		else if (m->m_pkthdr.ph_family == AF_INET6)
			icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR, 0);
		else
			m_free(m);
		counters_inc(sc->sc_if.if_counters, ifc_oerrors);
		error = ENETUNREACH;
		goto exit;
	}

	struct wg_pkt pkt = WG_PKT_INIT(p, m, sc, WG_PKT_TRANSPORT);

	if (MPQ_ADD(wg_pkt_queue, &sc->sc_txq, &pkt) == 0) {
		goto exit;
	} else {
		error = ENOBUFS;
		counters_inc(sc->sc_if.if_counters, ifc_oqdrops);
	}
free:
	m_free(m);
exit:
	return error;
}

void
wg_input_deliver(struct wg_pkt *pkt)
{
	NET_RLOCK();
	switch (pkt->p_state) {
	case WG_PKT_PASS:
		/* RACEY! competing with slow thread */
		pkt->p_p->p_ip = pkt->p_ip;
		if (pkt->p_m->m_pkthdr.ph_family == AF_INET)
			ipv4_input(&pkt->p_sc->sc_if, pkt->p_m);
		else if (pkt->p_m->m_pkthdr.ph_family == AF_INET6)
			ipv6_input(&pkt->p_sc->sc_if, pkt->p_m);
		else
			panic("invalid AF\n");
		break;
	case WG_PKT_NEW:
	case WG_PKT_DEAD:
		m_free(pkt->p_m);
	case WG_PKT_FREE:
		break;
	}
	NET_RUNLOCK();

}

void
wg_output_deliver(struct wg_pkt *pkt)
{
	struct mbuf 	peernam;

	NET_RLOCK();
	switch (pkt->p_state) {
	case WG_PKT_PASS:
		bzero(&peernam, sizeof(struct mbuf));

		peernam.m_type = MT_SONAME;
		peernam.m_data = (caddr_t) &pkt->p_p->p_ip;
		peernam.m_len = pkt->p_p->p_ip.sa.sa_len;

		if (pkt->p_p->p_ip.sa.sa_family  == AF_INET)
			pkt->p_p->p_sc->sc_so4->so_proto->pr_usrreq(
					pkt->p_p->p_sc->sc_so4,
					PRU_SEND, pkt->p_m, &peernam, NULL,
					NULL);
		else if (pkt->p_p->p_ip.sa.sa_family == AF_INET6)
			pkt->p_p->p_sc->sc_so6->so_proto->pr_usrreq(
					pkt->p_p->p_sc->sc_so6,
					PRU_SEND, pkt->p_m, &peernam, NULL,
					NULL);
		else
			m_free(pkt->p_m);
		break;
	case WG_PKT_NEW:
	case WG_PKT_DEAD:
		m_free(pkt->p_m);
	case WG_PKT_FREE:
		break;
	}
	NET_RUNLOCK();
}

/* The following functions are for interface control */
struct if_clone wg_cloner =
IF_CLONE_INITIALIZER("wg", wg_clone_create, wg_clone_destroy);

struct taskq *wg_taskq;
SLIST_HEAD(, wg_softc) wg_devs;

void
wgattach(int nwg)
{
	if_clone_attach(&wg_cloner);
	arc4random_buf(&wg_siphashkey, sizeof(wg_siphashkey));
	SLIST_INIT(&wg_devs);
}

struct wg_softc *
wg_softc_create()
{
	struct inpcb	*inp;
	struct wg_softc *sc = malloc(sizeof(*sc), M_DEVBUF, M_WAITOK | M_ZERO);

	socreate(AF_INET, &sc->sc_so4, SOCK_DGRAM, 0);
	socreate(AF_INET6, &sc->sc_so6, SOCK_DGRAM, 0);

	sc->sc_ip_rt = art_alloc(0, 32, 0);
	sc->sc_ip6_rt = art_alloc(0, 128, 0);

	inp = sotoinpcb(sc->sc_so4);
	inp->inp_upcall = wg_input;
	inp->inp_upcall_arg = sc;

	inp = sotoinpcb(sc->sc_so6);
	inp->inp_upcall = wg_input;
	inp->inp_upcall_arg = sc;

	HASHMAP_INIT(&sc->sc_id_hashmap, 0, wg_id_cmp, wg_id_hash);
	HASHMAP_INIT(&sc->sc_peer_hashmap, 0, wg_peer_cmp, wg_peer_hash);

	MPQ_INIT(wg_pkt_queue, &sc->sc_txq, wg_taskq, wg_transport_encrypt, wg_output_deliver);
	MPQ_INIT(wg_pkt_queue, &sc->sc_rxq, wg_taskq, wg_transport_decrypt, wg_input_deliver);
	MPQ_INIT(wg_pkt_queue, &sc->sc_txq_slow, wg_taskq, wg_transmit_slow, wg_output_deliver);
	MPQ_INIT(wg_pkt_queue, &sc->sc_rxq_slow, wg_taskq, wg_receive_slow, wg_free_pkt);

	MPQ_SET_SIZE(wg_pkt_queue, &sc->sc_txq, 256);
	MPQ_SET_SIZE(wg_pkt_queue, &sc->sc_rxq, 256);
	MPQ_SET_SIZE(wg_pkt_queue, &sc->sc_txq_slow, 32);
	MPQ_SET_SIZE(wg_pkt_queue, &sc->sc_rxq_slow, 32);

	return sc;
}

void
wg_softc_destroy(struct wg_softc *sc)
{
	int i;
	struct wg_peer_item item;

	HASHMAP_FOREACH_UNSAFE(&sc->sc_peer_hashmap, item, i)
		wg_peer_destroy(sc, item.peer);

	MPQ_DESTROY(&sc->sc_txq);
	MPQ_DESTROY(&sc->sc_rxq);
	MPQ_DESTROY(&sc->sc_txq_slow);
	MPQ_DESTROY(&sc->sc_rxq_slow);

	soclose(sc->sc_so4, 0);
	soclose(sc->sc_so6, 0);

	HASHMAP_DEINIT(&sc->sc_id_hashmap);
	HASHMAP_DEINIT(&sc->sc_peer_hashmap);
}

int
wg_clone_create(struct if_clone * ifc, int unit)
{
	struct ifnet	*ifp;
	struct wg_softc *sc;

	if (SLIST_EMPTY(&wg_devs))
		wg_taskq = taskq_create("wireguard", ncpus, IPL_NET, 0);

	sc = wg_softc_create();
	SLIST_INSERT_HEAD(&wg_devs, sc, sc_next);

	ifp = &sc->sc_if;
	ifp->if_softc = sc;

	snprintf(ifp->if_xname, sizeof(ifp->if_xname), "wg%d", unit);

	ifp->if_mtu = 1420;
	ifp->if_flags = IFF_NOARP | IFF_MULTICAST;
	ifp->if_xflags = IFXF_CLONED;

	ifp->if_ioctl = wg_ioctl;
	ifp->if_output = wg_output;
	ifp->if_rtrequest = p2p_rtrequest;

	ifp->if_type = IFT_TUNNEL;
	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);

	if_attach(ifp);
	if_alloc_sadl(ifp);
	if_counters_alloc(ifp);

#if NBPFILTER > 0
	bpfattach(&ifp->if_bpf, ifp, DLT_LOOP, sizeof(u_int32_t));
#endif

	return (0);
}

int
wg_clone_destroy(struct ifnet * ifp)
{
	struct wg_softc *sc = ifp->if_softc;

	CLR(sc->sc_if.if_flags, IFF_RUNNING);

	wg_softc_destroy(sc);

	if_detach(ifp);

#if NBPFILTER > 0
	bpfdetach(ifp);
#endif

	SLIST_REMOVE(&wg_devs, sc, wg_softc, sc_next);

	free(sc, M_DEVBUF, sizeof(*sc));
	free(sc->sc_ip_rt, M_RTABLE, sizeof(*sc->sc_ip_rt));
	free(sc->sc_ip6_rt, M_RTABLE, sizeof(*sc->sc_ip6_rt));


	if (SLIST_EMPTY(&wg_devs))
		taskq_destroy(wg_taskq);

	return (0);
}

int
wg_bind_port(struct wg_softc *sc)
{
	int error;
	struct inpcb *inp;
	struct mbuf hostnam;
	struct sockaddr_in *sin;
	struct sockaddr_in6 *sin6;

	m_inithdr(&hostnam);
	sin = mtod(&hostnam, struct sockaddr_in *);
	sin6 = mtod(&hostnam, struct sockaddr_in6 *);

	/* This just seems dirty */
	inp = sotoinpcb(sc->sc_so4);
	inp->inp_lport = 0;
	inp->inp_laddr = (struct in_addr) { 0 };

	inp = sotoinpcb(sc->sc_so6);
	inp->inp_lport = 0;
	inp->inp_laddr6 = (struct in6_addr) { .s6_addr = { 0 } };

	/* Bind ports */
	sin->sin_len = sizeof(*sin);
	sin->sin_family = AF_INET;
	sin->sin_port = htons(sc->sc_port);
	sin->sin_addr = (struct in_addr) { 0 };
	hostnam.m_len = sin->sin_len;

	if ((error = sobind(sc->sc_so4, &hostnam, curproc)) != 0)
		return error;

	bzero(sin6, sizeof(*sin6));
	sin6->sin6_len = sizeof(*sin6);
	sin6->sin6_family = AF_INET6;
	sin6->sin6_port = htons(sc->sc_port);
	sin6->sin6_addr = (struct in6_addr) { .s6_addr = { 0 } };
	hostnam.m_len = sin6->sin6_len;

	if ((error = sobind(sc->sc_so6, &hostnam, curproc)) != 0)
		return error;

	return 0;
}

int
wg_ioctl_set_peer(struct wg_softc *sc, u_long cmd, struct wg_set_peer *wsp)
{
	int ret = 0;
	struct wg_peer *p;
	struct wg_route *route, *troute;

	if (suser(curproc))
		return EPERM;

	if ((p = wg_peer_lookup(sc, wsp->sp_pubkey)) == NULL) {
		p = wg_peer_create(sc, wsp->sp_pubkey);
	}

	switch (cmd) {
	case SIOCSWGPEERIP:
		memcpy(&p->p_ip, &wsp->sp_ip, sizeof(p->p_ip));
		break;
	case SIOCSWGPEERPSK:
		memcpy(p->p_hs.hs_shared, wsp->sp_psk, sizeof(p->p_hs.hs_shared));
		break;
	case SIOCSWGPEERPKA:
		p->p_timers.t_pka_interval = wsp->sp_pka;
		break;
	case SIOCDWGPEER:
		wg_peer_destroy(sc, p);
		break;
	case SIOCSWGPEERAIP:
		ret = wg_route_register(sc, p, &wsp->sp_aip);
		break;
	case SIOCDWGPEERAIP:
		ret = wg_route_register(sc, NULL, &wsp->sp_aip);
		break;
	case SIOCCWGPEERAIP:
		SLIST_FOREACH_SAFE(route, &p->p_aip, r_next, troute)
			wg_route_register(sc, NULL, &route->r_cidr);
		break;
	}

	return ret;
}

int
wg_ioctl_set_serv(struct wg_softc *sc, u_long cmd, struct wg_set_serv *wss)
{
	if (suser(curproc))
		return EPERM;

	switch (cmd) {
	case SIOCSWGSERVPORT: /* Set WireGuard server port */
		sc->sc_port = wss->ss_port;
		return wg_bind_port(sc);
	case SIOCSWGSERVKEY: /* Set WireGuard server private + public key */
		wg_keypair_from_bytes(&sc->sc_kp, wss->ss_privkey);
		break;
	case SIOCCWGPEERS: /* Clear all WireGuard peers */
		break;
	}
	return 0;
}

void
wg_ioctl_get_serv(struct wg_softc *sc, struct wg_get_serv *wgs)
{
	size_t i, num = 0;
	struct wg_peer_item item;

	wgs->gs_port = sc->sc_port;
	memcpy(wgs->gs_pubkey, sc->sc_kp.pub, sizeof(wgs->gs_pubkey));

	/* We only want to pass the private key to root */
	if (!suser(curproc))
		memcpy(wgs->gs_privkey, sc->sc_kp.priv, sizeof(wgs->gs_privkey));
	else
		bzero(wgs->gs_privkey, sizeof(wgs->gs_privkey));

	HASHMAP_FOREACH_UNSAFE(&sc->sc_peer_hashmap, item, i) {
		if (num < wgs->gs_num_peers) {
			copyout(item.key, wgs->gs_peers[num], WG_KEY_SIZE);
		}
		num++;
	}
	wgs->gs_num_peers = num;
}

int
wg_ioctl_get_peer(struct wg_softc *sc, struct wg_get_peer *wgp)
{
	size_t num = 0;
	struct wg_peer *p;
	struct wg_route *r;

	if ((p = wg_peer_lookup(sc, wgp->gp_pubkey)) == NULL)
		return ENOENT;

	/* We only want to pass the preshared key to root */
	if (!suser(curproc))
		memcpy(wgp->gp_psk, p->p_hs.hs_shared, sizeof(wgp->gp_psk));
	else
		bzero(wgp->gp_psk, sizeof(wgp->gp_psk));

	wgp->gp_last_handshake = p->p_timers.t_last_handshake;
	wgp->gp_pka = p->p_timers.t_pka_interval;

	wgp->gp_tx_bytes = p->p_tx_bytes;
	wgp->gp_rx_bytes = p->p_rx_bytes;
	wgp->gp_ip = p->p_ip;

	SLIST_FOREACH(r, &p->p_aip, r_next) {
		if (num < wgp->gp_num_aip)
			copyout(&r->r_cidr, &wgp->gp_aip[num], sizeof(*wgp->gp_aip));
		num++;
	}
	wgp->gp_num_aip = num;
	return 0;
}

int
wg_ioctl(struct ifnet * ifp, u_long cmd, caddr_t data)
{
	int ret = 0;
	struct wg_softc *sc = ifp->if_softc;
	struct ifreq *ifr = (struct ifreq *) data;

	switch (cmd) {
	/* WireGuard IOCTLs */
	case SIOCSWGSERVPORT: /* Set WireGuard server port */
	case SIOCSWGSERVKEY: /* Set WireGuard server private + public key */
	case SIOCCWGPEERS: /* Clear all WireGuard peers */
		ret = wg_ioctl_set_serv(sc, cmd, (struct wg_set_serv *) data);
		break;
	case SIOCSWGPEERIP: /* Set WireGuard peer endpoint IP */
	case SIOCSWGPEERPSK: /* Set WireGuard peer preshared key */
	case SIOCSWGPEERAIP: /* Add WireGuard peer allowedip */
	case SIOCSWGPEERPKA: /* Set WireGuard peer persistent keepalive */
	case SIOCDWGPEER: /* Delete WireGuard peer */
	case SIOCDWGPEERAIP: /* Delete WireGuard peer allowedip */
	case SIOCCWGPEERAIP: /* Clear WireGuard peer */
		ret = wg_ioctl_set_peer(sc, cmd, (struct wg_set_peer *) data);
		break;
	case SIOCGWGSERV: /* Get WireGuard server configuration */
		wg_ioctl_get_serv(sc, (struct wg_get_serv *) data);
		break;
	case SIOCGWGPEER: /* Get WireGuard peer status */
		wg_ioctl_get_peer(sc, (struct wg_get_peer *) data);
		break;

	/* Interface IOCTLs */
	case SIOCSIFADDR:
		ifp->if_flags |= IFF_UP;
		/* FALLTHROUGH */
	case SIOCSIFFLAGS:
		if (ISSET(ifp->if_flags, IFF_UP)) {
			if (!ISSET(ifp->if_flags, IFF_RUNNING)) {
				SET(sc->sc_if.if_flags, IFF_RUNNING);
			}
		} else {
			if (ISSET(ifp->if_flags, IFF_RUNNING)) {
				CLR(sc->sc_if.if_flags, IFF_RUNNING);
			}
		}
		break;
	case SIOCSIFMTU:
		/* Arbitrary limits */
		if (ifr->ifr_mtu <= 0 || ifr->ifr_mtu > 9000)
			ret = EINVAL;
		else
			ifp->if_mtu = ifr->ifr_mtu;
		break;
	case SIOCSLIFPHYRTABLE:
		if (ifr->ifr_rdomainid < 0 ||
		    ifr->ifr_rdomainid > RT_TABLEID_MAX ||
		    !rtable_exists(ifr->ifr_rdomainid)) {
			ret = EINVAL;
		} else {
			sotoinpcb(sc->sc_so4)->inp_rtableid = ifr->ifr_rdomainid;
			sotoinpcb(sc->sc_so6)->inp_rtableid = ifr->ifr_rdomainid;
			ret = wg_bind_port(sc);
		}
		break;
	case SIOCGLIFPHYRTABLE:
		ifr->ifr_rdomainid = sotoinpcb(sc->sc_so4)->inp_rtableid;
		break;

	case SIOCADDMULTI:
	case SIOCDELMULTI:
		break;

	default:
		ret = ENOTTY;
	}

	return ret;
}