summaryrefslogtreecommitdiffstats
path: root/src/if_wg.c
blob: 88604065c48ce4f007b51d9551f7ba7c211cf135 (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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
/*
 * Copyright (c) 2019 Matt Dunwoodie <ncon@noconroy.net>
 *
 * 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/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 <net/if.h>
#include <net/if_var.h>
#include <net/if_types.h>
#include <net/pfvar.h>
#include <net/if_wg.h>
#include <net/if_wg_vars.h>

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

#include <crypto/blake2s.h>
#include <crypto/curve25519.h>
#include <crypto/chachapoly.h>

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

struct wg_tag {
	union wg_ip		 t_ip;
	struct wg_softc		*t_sc;
	uint32_t		 t_dst;
	enum wg_pkt_type	 t_type;
	enum wg_pkt_state {
		WG_PKT_STATE_EMPTY = 0,
		WG_PKT_STATE_NEW,
		WG_PKT_STATE_DONE,
		WG_PKT_STATE_DEAD,
	}			 t_state;
};

/*
struct wg_tag {
	union wg_ip		 t_ip;
	struct wg_peer		*t_peer;
	struct noise_keypair	*t_keypair;
	enum wg_pkt_state {
		WG_PKT_STATE_NEW = 0,
		WG_PKT_STATE_DONE,
		WG_PKT_STATE_DEAD,
	}			 t_state;
};
*/

struct wg_route {
	union wg_ip		 	 r_ip;
	struct wg_peer	 	 	*r_peer;
	struct wg_softc			*r_sc;
	struct mbuf_queue	 	 r_outgoing;
	SLIST_HEAD(, wg_route_entry)	 r_routes;
};

struct wg_route_entry {
	SLIST_ENTRY(wg_route_entry)	 r_entry;
	struct wg_cidr		 	 r_cidr;
	struct wg_route			*r_dst;
};

struct wg_softc {
	struct ifnet 		 sc_if;
	in_port_t		 sc_port;
	struct wg_device	 sc_dev;
	struct art_root		*sc_ip_rt;
	struct socket		*sc_so4;
#ifdef INET6
	struct art_root		*sc_ip6_rt;
	struct socket		*sc_so6;
#endif
	struct taskq		*sc_taskq;
	struct task		 sc_tx_task;
	struct task		 sc_tx_slow_task;
	struct task		 sc_rx_task;
	struct task		 sc_rx_slow_task;
	struct mpq 		 sc_tx_queue;
	struct mpq 		 sc_tx_slow_queue;
	struct mpq 		 sc_rx_queue;
	struct mpq 		 sc_rx_slow_queue;
};

CTASSERT(WG_KEY_SIZE == CHACHA20POLY1305_KEY_SIZE);
CTASSERT(WG_HASH_SIZE == BLAKE2S_HASH_SIZE);
CTASSERT(WG_KEY_SIZE == BLAKE2S_KEY_SIZE);
CTASSERT(WG_KEY_SIZE == WG_HASH_SIZE);
CTASSERT(WG_MSG_PADDING_SIZE == CHACHA20POLY1305_AUTHTAG_SIZE);
CTASSERT(WG_XNONCE_SIZE == XCHACHA20POLY1305_NONCE_SIZE);

#define DPRINTF(sc, str, ...) do { if (ISSET((sc)->sc_if.if_flags, IFF_DEBUG)) \
    printf("%s: " str, (sc)->sc_if.if_xname, __VA_ARGS__); } while (0)
/*
#define DPRINTF(sc, ...) do { if (ISSET((sc)->sc_if.if_flags, IFF_DEBUG)) \
    printf("wg: " __VA_ARGS__); } while (0)
*/

#ifdef INET6
#define AF_VAL(af, v4, v6) ((af) == AF_INET ? v4 : (af) == AF_INET6 ? v6 : 0)
#else
#define AF_VAL(af, v4, _) ((af) == AF_INET ? v4 : 0)
#endif

#define drop_pkt_err(e) do { err = e; goto drop; } while (0)
#define peer_route(p) ((struct wg_route *)(p)->p_arg)

#define ret_error(err) do { ret = err; goto leave; } while (0)

/* wireguard.c */
void wg_kdf(uint8_t [WG_HASH_SIZE], uint8_t [WG_HASH_SIZE],
    uint8_t [WG_HASH_SIZE], uint8_t [WG_KEY_SIZE], uint8_t *, size_t);
void wg_hash2(uint8_t [WG_HASH_SIZE], uint8_t *, size_t, uint8_t *, size_t);
void wg_mix_hash(struct wg_handshake *, uint8_t *, size_t);
void wg_mix_dh(struct wg_handshake *, uint8_t [WG_KEY_SIZE], uint8_t [WG_KEY_SIZE]);
void wg_mix_psk(struct wg_handshake *, uint8_t [WG_KEY_SIZE]);
void wg_handshake_encrypt(struct wg_handshake *, uint8_t *, uint8_t *, size_t);
int wg_handshake_decrypt(struct wg_handshake *, uint8_t *, uint8_t *, size_t);
void wg_timestamp_get(uint8_t [WG_TIMESTAMP_SIZE]);
int wg_timespec_timedout(struct timespec *, time_t);
enum wg_pkt_type wg_pkt_type(uint8_t *, size_t);
void wg_keypair_generate(struct wg_keypair *);
enum wg_error wg_msg_initiation_valid_mac2(struct wg_msg_initiation *, struct wg_cookie *);
enum wg_error wg_msg_response_valid_mac2(struct wg_msg_response *, struct wg_cookie *);

struct wg_session	*wg_peer_hs_session(struct wg_peer *);
struct wg_session	*wg_peer_ks_session(struct wg_peer *);

struct wg_session *wg_peer_new_session(struct wg_peer *);
void wg_session_drop(struct wg_session *);

/* Some crappy API */
void
wg_device_init(struct wg_device *dev, int ipl,
    void (*notify_fn)(struct wg_peer *),
    void (*outq_fn)(struct wg_peer *, enum wg_pkt_type, uint32_t),
    void (*cleanup_fn)(struct wg_peer *), void *arg)
{
	bzero(dev, sizeof(*dev));
	dev->d_arg = arg;
	dev->d_outq = outq_fn;
	dev->d_notify = notify_fn;
	dev->d_cleanup = cleanup_fn;
	fm_init(&dev->d_peers, 4, ipl);
	fm_init(&dev->d_sessions, 12, ipl);
	mtx_init(&dev->d_mtx, ipl);
	/* d_cookie_maker, d_keypair initialised to 0 */
}

void
wg_device_setkey(struct wg_device *dev, struct wg_privkey *key)
{
	mtx_enter(&dev->d_mtx);
	wg_keypair_from_key(&dev->d_keypair, key);
	mtx_leave(&dev->d_mtx);
}

void
wg_device_getkey(struct wg_device *dev, struct wg_keypair *kp)
{
	mtx_enter(&dev->d_mtx);
	*kp = dev->d_keypair;
	mtx_leave(&dev->d_mtx);
}

void
wg_device_destroy(struct wg_device *dev)
{
	struct map_item *item;

	/* TODO lock fixed map */
	FM_FOREACH_FILLED(item, &dev->d_peers)
		wg_peer_drop(item->value);

	fm_destroy(&dev->d_sessions);
	fm_destroy(&dev->d_peers);
}

struct wg_peer *
wg_device_new_peer(struct wg_device *dev, struct wg_pubkey *key, void *arg)
{
	struct wg_peer *peer;
	peer = malloc(sizeof(*peer), M_DEVBUF, M_WAITOK | M_ZERO);

	peer->p_arg = arg;
	peer->p_device = dev;
	peer->p_remote = *key;
	mtx_init(&peer->p_mtx, dev->d_mtx.mtx_wantipl);

	mtx_enter(&peer->p_mtx);
	peer->p_id = fm_insert(&dev->d_peers, peer);
	mtx_leave(&peer->p_mtx);

	/* All other elements of wg_peer are nulled by M_ZERO */
	return peer;
}

struct wg_session *
wg_peer_new_session(struct wg_peer *peer)
{
	struct wg_session *session, *old_session;
	session = malloc(sizeof(*session), M_DEVBUF, M_WAITOK | M_ZERO);

	getnanotime(&session->s_created);
	session->s_peer = peer;
	session->s_state = WG_STATE_NEW;
	mtx_init(&session->s_mtx, peer->p_mtx.mtx_wantipl);

	mtx_enter(&peer->p_mtx);

	old_session = peer->p_hs_session;
	peer->p_hs_session = session;
	mtx_leave(&peer->p_mtx);

	mtx_enter(&session->s_mtx);
	session->s_local_id = fm_insert(&peer->p_device->d_sessions, session);
	mtx_leave(&session->s_mtx);

	if (old_session)
		wg_session_drop(old_session);

	return session;
}

struct wg_peer *
wg_device_ref_peerkey(struct wg_device *dev, struct wg_pubkey *key)
{
	/* For the time being, we just iterate through peers to find the
	 * matching peer */
	struct wg_peer *peer = NULL;
	struct map_item *item;

	/* TODO lock, or use better data structure */
	FM_FOREACH_FILLED(item, &dev->d_peers) {
		peer = item->value;
		if (memcmp(key->k, peer->p_remote.k, sizeof(key->k)) == 0)
			break;
		else
			peer = NULL;
	}
	if (peer)
		peer = fm_lookup(&dev->d_peers, peer->p_id);

	return peer;
}

void
wg_peer_put(struct wg_peer *peer)
{
	fm_put(&peer->p_device->d_peers, peer->p_id);
}

void
wg_peer_drop(struct wg_peer *peer)
{
	fm_drop(&peer->p_device->d_peers, peer->p_id);
	peer->p_device->d_cleanup(peer);
	wg_peer_clean(peer);
	free(peer, M_DEVBUF, sizeof(*peer));
}

void
wg_session_put(struct wg_session *session)
{
	fm_put(&session->s_peer->p_device->d_sessions, session->s_local_id);
}

void
wg_session_drop(struct wg_session *session)
{
	fm_drop(&session->s_peer->p_device->d_sessions, session->s_local_id);
	free(session, M_DEVBUF, sizeof(*session));
}

void
wg_peer_reset_attempts(struct wg_peer *peer)
{
	mtx_enter(&peer->p_mtx);
	peer->p_attempts = 0;
	mtx_leave(&peer->p_mtx);
}

void
wg_peer_clean(struct wg_peer *peer)
{
	struct wg_session *hs, *ks, *ks_old;

	mtx_enter(&peer->p_mtx);
	hs = peer->p_hs_session;
	ks = peer->p_ks_session;
	ks_old = peer->p_ks_session_old;

	peer->p_hs_session = NULL;
	peer->p_ks_session = NULL;
	peer->p_ks_session_old = NULL;
	mtx_leave(&peer->p_mtx);

	if (hs != NULL)
		wg_session_drop(hs);
	if (ks != NULL)
		wg_session_drop(ks);
	if (ks_old != NULL)
		wg_session_drop(ks_old);

}

void
wg_session_promote(struct wg_session *session)
{
	struct wg_session *old_session;
	struct wg_peer *peer = session->s_peer;
	struct wg_keyset *ks = &session->s_keyset;
	struct wg_handshake *hs = &session->s_handshake;

	/* TODO make better */
	/* Setup session: derive keys, initialise the antireplay structure */
	mtx_enter(&session->s_mtx);
	if (session->s_state == WG_STATE_RECV_RESPONSE) {
		session->s_state = WG_STATE_INITIATOR;
		wg_kdf(ks->k_txkey.k, ks->k_rxkey.k, NULL, hs->h_ck, NULL, 0);
	} else if (session->s_state == WG_STATE_MADE_RESPONSE) {
		session->s_state = WG_STATE_RESPONDER;
		wg_kdf(ks->k_rxkey.k, ks->k_txkey.k, NULL, hs->h_ck, NULL, 0);
	} else {
		mtx_leave(&session->s_mtx);
		return;
	}

	antireplay_init(&ks->k_ar);
	mtx_leave(&session->s_mtx);


	mtx_enter(&peer->p_mtx);
	old_session = peer->p_ks_session_old;
	if (peer->p_ks_session != NULL)
		peer->p_ks_session_old = peer->p_ks_session;
	peer->p_ks_session = peer->p_hs_session;
	peer->p_hs_session = NULL;
	mtx_leave(&peer->p_mtx);

	if (old_session != NULL)
		wg_session_drop(old_session);

	peer->p_device->d_notify(peer);
}

void
wg_peer_setshared(struct wg_peer *peer, struct wg_privkey *key)
{
	mtx_enter(&peer->p_mtx);
	peer->p_shared = *key;
	mtx_leave(&peer->p_mtx);
}

void
wg_peer_getshared(struct wg_peer *peer, struct wg_privkey *key)
{
	mtx_enter(&peer->p_mtx);
	*key = peer->p_shared;
	mtx_leave(&peer->p_mtx);
}

struct timespec
wg_peer_last_handshake(struct wg_peer *peer)
{
	struct timespec ret = { 0, 0 };
	mtx_enter(&peer->p_mtx);
	if (peer->p_ks_session != NULL)
		ret = peer->p_ks_session->s_created;
	mtx_leave(&peer->p_mtx);
	return ret;
}

struct wg_session *
wg_peer_last_session(struct wg_peer *peer)
{
	uint32_t id = 0;
	struct wg_session *session;

	mtx_enter(&peer->p_mtx);
	if (peer->p_ks_session != NULL)
		id = peer->p_ks_session->s_local_id;
	mtx_leave(&peer->p_mtx);

	if ((session = fm_lookup(&peer->p_device->d_sessions, id)) == NULL)
		return NULL;

	if (!wg_timespec_timedout(&session->s_created, WG_REJECT_AFTER_TIME) && 
	    session->s_keyset.k_txcounter < WG_REJECT_AFTER_MESSAGES)
		return session;
	
	wg_session_put(session);
	return NULL;
}

/* Crypto  */
enum wg_error
wg_device_rx_initiation(struct wg_device *dev, struct wg_msg_initiation *init,
    struct wg_session **s)
{
	struct wg_peer *peer;
	struct wg_keypair kp;
	struct wg_handshake hs;
	struct wg_timestamp ts;
	struct wg_pubkey remote;
	struct wg_session *session;

	enum wg_error ret = WG_OK;

	*s = NULL;

	/* We want to ensure that the keypair is not modified during the
	 * handshake, so we take a local copy here and bzero it before
	 * returning */
	wg_device_getkey(dev, &kp);

	/* Noise handshake */
	memcpy(hs.h_remote.k, init->ephemeral, WG_KEY_SIZE);
	wg_keypair_generate(&hs.h_local);

	wg_hash2(hs.h_ck, WG_CONSTRUCTION, strlen(WG_CONSTRUCTION), NULL, 0);
	memcpy(hs.h_hash, hs.h_ck, WG_HASH_SIZE);
	wg_mix_hash(&hs, WG_IDENTIFIER, strlen(WG_IDENTIFIER));

	wg_mix_hash(&hs, kp.pub.k, WG_KEY_SIZE);
	wg_kdf(hs.h_ck, NULL, NULL, hs.h_ck, hs.h_remote.k, WG_KEY_SIZE);
	wg_mix_hash(&hs, hs.h_remote.k, WG_KEY_SIZE);
	wg_mix_dh(&hs, kp.priv.k, hs.h_remote.k);

	if (!wg_handshake_decrypt(&hs, remote.k, init->static_pub,
	    WG_ENCRYPTED_SIZE(sizeof(remote.k))))
		ret_error(WG_DECRYPT);

	wg_mix_hash(&hs, init->static_pub, sizeof(init->static_pub));
	wg_mix_dh(&hs, kp.priv.k, remote.k);

	if (!wg_handshake_decrypt(&hs, ts.t, init->timestamp,
	    WG_ENCRYPTED_SIZE(sizeof(ts.t))))
		ret_error(WG_DECRYPT);

	wg_mix_hash(&hs, init->timestamp, sizeof(init->timestamp));
	wg_hash2(hs.h_k, WG_MAC1, strlen(WG_MAC1), kp.pub.k, WG_KEY_SIZE);

	blake2s(hs.h_mac, (void *)init, hs.h_k, sizeof(hs.h_mac),
	    offsetof(struct wg_msg_initiation, mac1), sizeof(hs.h_k));

	/* Check MAC matches */
	if (timingsafe_bcmp(hs.h_mac, init->mac1, WG_MAC_SIZE))
		ret_error(WG_MAC);

	/* Lookup peer key that was specified in the packet, as we need to
	 * know what peer this is for. */
	if ((peer = wg_device_ref_peerkey(dev, &remote)) == NULL)
		ret_error(WG_UNKNOWN_PEER);

	/* We want to ensure this packet is not replayed, so we validate that
	 * the timestamp (not necessarily representative of the real time) is
	 * greater than the last one we have received */
	mtx_enter(&peer->p_mtx);
	if (memcmp(ts.t, peer->p_timestamp.t, sizeof(ts.t)) >= 0)
		peer->p_timestamp = ts;
	mtx_leave(&peer->p_mtx);

	if (memcmp(ts.t, peer->p_timestamp.t, sizeof(ts.t)) != 0) {
		wg_peer_put(peer);
		ret_error(WG_TIMESTAMP);
	}

	session = wg_peer_new_session(peer);

	mtx_enter(&session->s_mtx);
	session->s_remote_id = init->sender;
	session->s_handshake = hs;
	session->s_state = WG_STATE_RECV_INITIATION;
	mtx_leave(&session->s_mtx);

	dev->d_outq(peer, WG_PKT_RESPONSE, session->s_local_id);
	wg_peer_put(peer);
	*s = session;
leave:
	if (ret != WG_OK)
		wg_session_put(session);
	explicit_bzero(&kp, sizeof(kp));
	explicit_bzero(&hs, sizeof(hs));
	return ret;
}

enum wg_error
wg_device_rx_response(struct wg_device *dev, struct wg_msg_response *resp,
    struct wg_session **s)
{
	struct wg_keypair kp;
	struct wg_handshake hs;
	struct wg_privkey shared;
	struct wg_session *session;

	enum wg_error ret = WG_OK;

	if ((session = fm_lookup(&dev->d_sessions, resp->receiver)) == NULL)
		return WG_ID;

	/* Load requried values */
	wg_device_getkey(dev, &kp);

	mtx_enter(&session->s_mtx);
	hs = session->s_handshake;
	mtx_leave(&session->s_mtx);

	mtx_enter(&session->s_peer->p_mtx);
	shared = session->s_peer->p_shared;
	mtx_leave(&session->s_peer->p_mtx);

	/* Noise recv handshake */
	memcpy(hs.h_remote.k, resp->ephemeral, WG_KEY_SIZE);

	wg_kdf(hs.h_ck, NULL, NULL, hs.h_ck, hs.h_remote.k, WG_KEY_SIZE);
	wg_mix_hash(&hs, hs.h_remote.k, WG_KEY_SIZE);

	wg_mix_dh(&hs, hs.h_local.priv.k, hs.h_remote.k);
	wg_mix_dh(&hs, kp.priv.k, hs.h_remote.k);

	wg_mix_psk(&hs, shared.k);

	if (!wg_handshake_decrypt(&hs, NULL, resp->empty, WG_ENCRYPTED_SIZE(0)))
		ret_error(WG_DECRYPT);

	wg_mix_hash(&hs, resp->empty, WG_ENCRYPTED_SIZE(0));

	wg_hash2(hs.h_k, WG_MAC1, strlen(WG_MAC1), kp.pub.k,
	    WG_KEY_SIZE);
	blake2s(hs.h_mac, (void *)resp, hs.h_k, sizeof(hs.h_mac),
	    offsetof(struct wg_msg_response, mac1), sizeof(hs.h_k));

	/* Compare macs */
	if (timingsafe_bcmp(hs.h_mac, resp->mac1, WG_MAC_SIZE))
		ret_error(WG_MAC);

	/* Update session only if we are in correct state */
	mtx_enter(&session->s_mtx);
	if (session->s_state == WG_STATE_MADE_INITIATION) {
		session->s_handshake = hs;
		session->s_remote_id = resp->sender;
		session->s_state = WG_STATE_RECV_RESPONSE;
	} else {
		ret = WG_STATE;
	}
	mtx_leave(&session->s_mtx);

	wg_session_promote(session);

	*s = session;
leave:
	if (ret != WG_OK)
		wg_session_put(session);
	explicit_bzero(&shared, sizeof(shared));
	explicit_bzero(&kp, sizeof(kp));
	explicit_bzero(&hs, sizeof(hs));
	return ret;

}

enum wg_error
wg_device_rx_cookie(struct wg_device *dev, struct wg_msg_cookie *cookie,
    struct wg_session **s)
{
	uint8_t key[WG_KEY_SIZE];
	uint8_t value[WG_COOKIE_SIZE];
	struct wg_session *session;

	enum wg_error ret = WG_OK;

	if ((session = fm_lookup(&dev->d_sessions, cookie->receiver)) == NULL)
		return WG_ID;

	wg_hash2(key, WG_COOKIE, strlen(WG_COOKIE),
	    session->s_peer->p_remote.k, WG_KEY_SIZE);

	/* TODO lock for h_mac? */
	if(!xchacha20poly1305_decrypt(value, cookie->value,
	    sizeof(cookie->value), session->s_handshake.h_mac, WG_MAC_SIZE,
	    cookie->nonce, key))
		ret_error(WG_DECRYPT);

	/* Update peer with new cookie data */
	mtx_enter(&session->s_peer->p_mtx);
	memcpy(session->s_peer->p_cookie.cookie, value,
	    sizeof(session->s_peer->p_cookie.cookie));
	getnanotime(&session->s_peer->p_cookie.time);
	mtx_leave(&session->s_peer->p_mtx);

	*s = session;
leave:
	if (ret != WG_OK)
		wg_session_put(session);
	return ret;
}

enum wg_error
wg_device_rx_transport(struct wg_device *dev, struct wg_msg_transport *msg,
    size_t len, struct wg_session **s)
{
	struct wg_session *session;
	enum wg_error ret = WG_OK;
	size_t data_len = len - offsetof(struct wg_msg_transport, data);
	uint64_t counter = letoh64(msg->counter);

	if ((session = fm_lookup(&dev->d_sessions, msg->receiver)) == NULL)
		return WG_ID;

	wg_session_promote(session);

	/* TODO fix locks, at the moment we just kinda don't care */
	if (session->s_state != WG_STATE_INITIATOR &&
	    session->s_state != WG_STATE_RESPONDER)
		ret_error(WG_STATE);

	if (wg_timespec_timedout(&session->s_created, WG_REJECT_AFTER_TIME) ||
	    session->s_keyset.k_rxcounter > WG_REJECT_AFTER_MESSAGES)
		ret_error(WG_REJECT);

	if (!chacha20poly1305_decrypt(msg->data, msg->data, data_len, NULL, 0,
	    msg->counter, session->s_keyset.k_rxkey.k))
		ret_error(WG_DECRYPT);

	if (antireplay_update(&session->s_keyset.k_ar, counter))
		ret_error(WG_REPLAY);

	session->s_keyset.k_rxcounter = counter;
	session->s_peer->p_rx_bytes += data_len - WG_MAC_SIZE;

	if (session->s_state == WG_STATE_RESPONDER &&
	    wg_timespec_timedout(&session->s_created,
	    WG_REKEY_AFTER_TIME_RECV) &&
	    wg_timespec_timedout(&session->s_peer->p_last_initiation,
	    WG_REKEY_TIMEOUT))
		dev->d_outq(session->s_peer, WG_PKT_INITIATION, session->s_peer->p_id);

	*s = session;
leave:
	if (ret != WG_OK)
		wg_session_put(session);
	return ret;
}


enum wg_error
wg_device_tx_initiation(struct wg_device *dev, struct wg_msg_initiation *init,
    uint32_t id, struct wg_session **s)
{
	struct wg_peer *peer;
	struct wg_keypair kp;
	struct wg_handshake hs;
	struct wg_session *session = NULL;

	enum wg_error ret = WG_OK;

	if ((peer = fm_lookup(&dev->d_peers, id)) == NULL)
		return WG_ID;

	mtx_enter(&peer->p_mtx);
	if (!wg_timespec_timedout(&peer->p_last_initiation, WG_REKEY_TIMEOUT))
		ret = WG_HS_RATE;
	if (peer->p_attempts >= WG_REKEY_ATTEMPT_COUNT)
		ret = WG_HS_ATTEMPTS;
	if (ret == WG_OK) {
		getnanotime(&peer->p_last_initiation);
		peer->p_attempts++;
	}
	mtx_leave(&peer->p_mtx);

	if (ret != WG_OK)
		goto leave;

	/* We need to generate the session here first, so we can use s_local_id
	 * below. We also want to operate on a local handshake, so we don't
	 * have to lock the session. */
	session = wg_peer_new_session(peer);

	wg_device_getkey(dev, &kp);
	wg_keypair_generate(&hs.h_local);

	/* Noise handshake */
	init->type = WG_MSG_INITIATION;
	init->sender = session->s_local_id;
	memcpy(init->ephemeral, hs.h_local.pub.k, WG_KEY_SIZE);

	wg_hash2(hs.h_ck, WG_CONSTRUCTION, strlen(WG_CONSTRUCTION), NULL, 0);
	memcpy(hs.h_hash, hs.h_ck, WG_HASH_SIZE);
	wg_mix_hash(&hs, WG_IDENTIFIER, strlen(WG_IDENTIFIER));

	wg_mix_hash(&hs, peer->p_remote.k, WG_KEY_SIZE);
	wg_kdf(hs.h_ck, NULL, NULL, hs.h_ck, hs.h_local.pub.k, WG_KEY_SIZE);
	wg_mix_hash(&hs, hs.h_local.pub.k, WG_KEY_SIZE);
	wg_mix_dh(&hs, hs.h_local.priv.k, peer->p_remote.k);

	wg_handshake_encrypt(&hs, init->static_pub, kp.pub.k,
	    WG_KEY_SIZE);

	wg_mix_hash(&hs, init->static_pub, WG_ENCRYPTED_SIZE(WG_KEY_SIZE));
	wg_mix_dh(&hs, kp.priv.k, peer->p_remote.k);

	wg_timestamp_get(init->timestamp);

	wg_handshake_encrypt(&hs, init->timestamp, init->timestamp, WG_TIMESTAMP_SIZE);
	wg_mix_hash(&hs, init->timestamp, WG_ENCRYPTED_SIZE(WG_TIMESTAMP_SIZE));
	wg_hash2(hs.h_k, WG_MAC1, strlen(WG_MAC1), peer->p_remote.k, WG_KEY_SIZE);

	blake2s(init->mac1, (void *) init, hs.h_k, sizeof(init->mac1),
	    offsetof(struct wg_msg_initiation, mac1), sizeof(hs.h_k));
	memcpy(hs.h_mac, init->mac1, sizeof(hs.h_mac));

	/* TODO lock for cookie time? */
	if (wg_timespec_timedout(&peer->p_cookie.time, WG_COOKIE_VALID_TIME))
		bzero(init->mac2, WG_MAC_SIZE);
	else
		blake2s(init->mac2, (void *)init, peer->p_cookie.cookie,
		    sizeof(init->mac2), offsetof(struct wg_msg_initiation, mac2),
		    sizeof(peer->p_cookie.cookie));

	mtx_enter(&session->s_mtx);
	session->s_handshake = hs;
	session->s_state = WG_STATE_MADE_INITIATION;
	mtx_leave(&session->s_mtx);

	*s = session;
leave:
	/* if (ret != WG_OK)
		wg_session_put(session); */
	wg_peer_put(peer);
	explicit_bzero(&kp, sizeof(kp));
	explicit_bzero(&hs, sizeof(hs));
	return ret;
}

enum wg_error
wg_device_tx_response(struct wg_device *dev, struct wg_msg_response *resp,
    uint32_t id, struct wg_session **s)
{
	struct wg_handshake hs;
	struct wg_session *session;

	enum wg_error ret = WG_OK;

	if ((session = fm_lookup(&dev->d_sessions, id)) == NULL)
		return WG_ID;

	resp->type = WG_MSG_RESPONSE;
	resp->sender = session->s_local_id;
	resp->receiver = session->s_remote_id;

	mtx_enter(&session->s_mtx);
	hs = session->s_handshake;
	mtx_leave(&session->s_mtx);

	/* Noise handshake */
	wg_kdf(hs.h_ck, NULL, NULL, hs.h_ck, hs.h_local.pub.k, WG_KEY_SIZE);
	wg_mix_hash(&hs, hs.h_local.pub.k, WG_KEY_SIZE);

	memcpy(resp->ephemeral, hs.h_local.pub.k, WG_KEY_SIZE);

	wg_mix_dh(&hs, hs.h_local.priv.k, hs.h_remote.k);
	wg_mix_dh(&hs, hs.h_local.priv.k, session->s_peer->p_remote.k);

	wg_mix_psk(&hs, session->s_peer->p_shared.k);

	wg_handshake_encrypt(&hs, resp->empty, NULL, 0);

	wg_mix_hash(&hs, resp->empty, WG_ENCRYPTED_SIZE(0));

	wg_hash2(hs.h_k, WG_MAC1, strlen(WG_MAC1), session->s_peer->p_remote.k, WG_KEY_SIZE);
	blake2s(resp->mac1, (void *)resp, hs.h_k, sizeof(resp->mac1),
	    offsetof(struct wg_msg_response, mac1), sizeof(hs.h_k));
	memcpy(hs.h_mac, resp->mac1, sizeof(hs.h_mac));

	/* TODO lock for cookie time? */
	if (wg_timespec_timedout(&session->s_peer->p_cookie.time, WG_COOKIE_VALID_TIME))
		bzero(resp->mac2, WG_MAC_SIZE);
	else
		blake2s(resp->mac2, (void *)resp, session->s_peer->p_cookie.cookie,
		    sizeof(resp->mac2), offsetof(struct wg_msg_response, mac2),
		    sizeof(session->s_peer->p_cookie.cookie));

	mtx_enter(&session->s_mtx);
	if (session->s_state == WG_STATE_RECV_INITIATION)
		session->s_state = WG_STATE_MADE_RESPONSE;
	mtx_leave(&session->s_mtx);

	if (session->s_state != WG_STATE_MADE_RESPONSE)
		session->s_state = WG_STATE_MADE_RESPONSE;
		ret_error(WG_STATE);

	*s = session;
leave:
	if (ret != WG_OK)
		wg_session_put(session);
	return ret;
}

enum wg_error
wg_device_tx_cookie(struct wg_device *dev, struct wg_cookie *c,
    uint32_t sender, uint8_t mac[WG_MAC_SIZE], struct wg_msg_cookie *msg)
{
	uint8_t key[WG_KEY_SIZE]; // Same as WG_HASH_SIZE

	msg->type = WG_MSG_COOKIE;
	msg->receiver = sender;
	arc4random_buf(msg->nonce, sizeof(msg->nonce));

	wg_hash2(key, WG_COOKIE, strlen(WG_COOKIE), dev->d_keypair.pub.k,
	    WG_KEY_SIZE);
	xchacha20poly1305_encrypt(msg->value, c->cookie, WG_MAC_SIZE, mac,
	    WG_MAC_SIZE, msg->nonce, key);

	explicit_bzero(key, sizeof(key));
	return WG_OK;
}

enum wg_error
wg_device_tx_transport(struct wg_device *dev, struct wg_msg_transport *msg,
    size_t len, uint32_t id, struct wg_session **s)
{
	struct wg_session *session;

	enum wg_error ret = WG_OK;

	if ((session = fm_lookup(&dev->d_sessions, id)) == NULL)
		return WG_ID;

	/* TODO we should do some locking */
	if (session->s_state != WG_STATE_INITIATOR &&
	    session->s_state != WG_STATE_RESPONDER)
		ret_error(WG_STATE);

	if (wg_timespec_timedout(&session->s_created, WG_REJECT_AFTER_TIME) ||
	    session->s_keyset.k_txcounter > WG_REJECT_AFTER_MESSAGES)
		ret_error(WG_REJECT);

	msg->type = WG_MSG_TRANSPORT;
	msg->receiver = session->s_remote_id;
	msg->counter = htole64(session->s_keyset.k_txcounter++);

	chacha20poly1305_encrypt(msg->data, msg->data, len, NULL, 0, msg->counter,
	    session->s_keyset.k_txkey.k);

	/* Packet OK, but we do want a rekey */
	if (((session->s_state == WG_STATE_INITIATOR &&
	    wg_timespec_timedout(&session->s_created, WG_REKEY_AFTER_TIME)) ||
	    session->s_keyset.k_txcounter > WG_REKEY_AFTER_MESSAGES) &&
	    wg_timespec_timedout(&session->s_peer->p_last_initiation,
	    WG_REKEY_TIMEOUT))
		dev->d_outq(session->s_peer, WG_PKT_INITIATION, session->s_peer->p_id);

	session->s_peer->p_tx_bytes += len;
	*s = session;
leave:
	if (ret != WG_OK)
		wg_session_put(session);
	return ret;
}

/* WireGuard crypto helper functions */
void
wg_kdf(uint8_t first[WG_HASH_SIZE], uint8_t second[WG_HASH_SIZE],
    uint8_t third[WG_HASH_SIZE], uint8_t key[WG_KEY_SIZE], uint8_t * input,
    size_t input_len)
{
	uint8_t 	buffer[WG_HASH_SIZE + 1];
	uint8_t 	secret[WG_HASH_SIZE];

	blake2s_hmac(secret, input, key, WG_HASH_SIZE, input_len, WG_KEY_SIZE);

	if (!first)
		return;

	buffer[0] = 1;
	blake2s_hmac(buffer, buffer, secret, WG_HASH_SIZE, 1, WG_KEY_SIZE);
	memcpy(first, buffer, WG_HASH_SIZE);

	if (!second)
		return;

	buffer[WG_HASH_SIZE] = 2;
	blake2s_hmac(buffer, buffer, secret, WG_HASH_SIZE, WG_HASH_SIZE + 1, WG_KEY_SIZE);
	memcpy(second, buffer, WG_HASH_SIZE);

	if (!third)
		return;

	buffer[WG_HASH_SIZE] = 3;
	blake2s_hmac(buffer, buffer, secret, WG_HASH_SIZE, WG_HASH_SIZE + 1, WG_KEY_SIZE);
	memcpy(third, buffer, WG_HASH_SIZE);
}

void
wg_hash2(uint8_t out[WG_HASH_SIZE], uint8_t * in1, size_t in1_len, uint8_t * in2, size_t in2_len)
{
	struct blake2s_state s;
	blake2s_init(&s, WG_HASH_SIZE);
	blake2s_update(&s, in1, in1_len);
	blake2s_update(&s, in2, in2_len);
	blake2s_final(&s, out, WG_HASH_SIZE);
}

void
wg_mix_hash(struct wg_handshake * hs, uint8_t * in, size_t in_len)
{
	wg_hash2(hs->h_hash, hs->h_hash, WG_HASH_SIZE, in, in_len);
}

void
wg_mix_dh(struct wg_handshake * hs, uint8_t priv[WG_KEY_SIZE], uint8_t pub[WG_KEY_SIZE])
{
	uint8_t 	DH    [WG_KEY_SIZE];
	crypto_scalarmult_curve25519(DH, priv, pub);
	wg_kdf(hs->h_ck, hs->h_k, NULL, hs->h_ck, DH, WG_KEY_SIZE);
	explicit_bzero(DH, WG_KEY_SIZE);
}

void
wg_mix_psk(struct wg_handshake * hs, uint8_t psk[WG_KEY_SIZE])
{
	uint8_t 	t     [WG_HASH_SIZE];
	wg_kdf(hs->h_ck, t, hs->h_k, hs->h_ck, psk, WG_KEY_SIZE);
	wg_mix_hash(hs, t, WG_HASH_SIZE);
	explicit_bzero(t, WG_HASH_SIZE);
}

void
wg_handshake_encrypt(struct wg_handshake *hs, uint8_t *dst, uint8_t *src, size_t srclen)
{
	return chacha20poly1305_encrypt(dst, src, srclen, hs->h_hash, WG_HASH_SIZE, 0, hs->h_k);
}

int
wg_handshake_decrypt(struct wg_handshake *hs, uint8_t *dst, uint8_t *src, size_t srclen)
{
	return chacha20poly1305_decrypt(dst, src, srclen, hs->h_hash, WG_HASH_SIZE, 0, hs->h_k);
}

void
wg_timestamp_get(uint8_t ts[WG_TIMESTAMP_SIZE])
{
	struct timespec tv;
	getnanotime(&tv);
	*(uint64_t *) (ts) = htobe64(0x400000000000000aULL + tv.tv_sec);
	*(uint32_t *) (ts + 8) = htobe32(tv.tv_nsec);
}

int
wg_timespec_timedout(struct timespec * start, time_t timeout)
{
	struct timespec now;

	getnanotime(&now);

	return now.tv_sec == start->tv_sec + timeout ?
		now.tv_nsec > start->tv_nsec :
		now.tv_sec > start->tv_sec + timeout;
}

enum wg_pkt_type
wg_pkt_type(uint8_t *buf, size_t len)
{
	struct wg_msg_unknown *msg;

	if (len < sizeof(*msg))
		return WG_PKT_UNKNOWN;
	else
		msg = (struct wg_msg_unknown *)buf;

	if (msg->type == WG_MSG_INITIATION && len == wg_pkt_len[msg->type])
		return WG_PKT_INITIATION;
	else if (msg->type == WG_MSG_RESPONSE && len == wg_pkt_len[msg->type])
		return WG_PKT_RESPONSE;
	else if (msg->type == WG_MSG_COOKIE && len == wg_pkt_len[msg->type])
		return WG_PKT_COOKIE;
	else if (msg->type == WG_MSG_TRANSPORT && len >= wg_pkt_len[msg->type])
		return WG_PKT_TRANSPORT;
	else
		return WG_PKT_UNKNOWN;
}

void
wg_keypair_from_key(struct wg_keypair *kp, const struct wg_privkey *key)
{
	const uint8_t basepoint[WG_KEY_SIZE] = {9};

	/* memmove as key may overlap with kp->priv */
	memmove(kp->priv.k, key->k, WG_KEY_SIZE);

	/* We don't care if the input is not a valid key, we just set
	 * the bits and be done with it. The curve25519 library *SHOULD*
	 * do this, but since this may be returned to the user, we do
	 * it here too. */
	kp->priv.k[0] &= 248;
	kp->priv.k[31] &= 127;
	kp->priv.k[31] |= 64;

	crypto_scalarmult_curve25519(kp->pub.k, kp->priv.k, basepoint);
}

void
wg_keypair_generate(struct wg_keypair *kp)
{
	arc4random_buf(kp->priv.k, sizeof(kp->priv.k));
	wg_keypair_from_key(kp, &kp->priv);
}

enum wg_error
wg_msg_initiation_valid_mac2(struct wg_msg_initiation *msg, struct wg_cookie *c)
{
	uint8_t mac[WG_MAC_SIZE];
	blake2s(mac, (uint8_t *)msg, c->cookie, WG_MAC_SIZE,
	    offsetof(struct wg_msg_initiation, mac2), WG_COOKIE_SIZE);
	return timingsafe_bcmp(mac, msg->mac2, WG_MAC_SIZE) ? WG_MAC : WG_OK;
}

enum wg_error
wg_msg_response_valid_mac2(struct wg_msg_response *msg, struct wg_cookie *c)
{
	uint8_t mac[WG_MAC_SIZE];
	blake2s(mac, (uint8_t *)msg, c->cookie, WG_MAC_SIZE,
	    offsetof(struct wg_msg_response, mac2), WG_COOKIE_SIZE);
	return timingsafe_bcmp(mac, msg->mac2, WG_MAC_SIZE) ? WG_MAC : WG_OK;
}

void
wg_cookie_from_token(struct wg_cookie *c, struct wg_cookie_maker *cm,
    uint8_t *ip, uint8_t ip_len)
{
	if (wg_timespec_timedout(&cm->time, WG_COOKIE_VALID_TIME)) {
		getnanotime(&cm->time);
		arc4random_buf(cm->seed, sizeof(cm->seed));
	}

	blake2s(c->cookie, ip, cm->seed, WG_MAC_SIZE, ip_len, WG_COOKIE_SIZE);
}

/* Timer Functions */
void
wg_timer_setup(struct wg_timers *t, void *p, void (*keepalive)(void *),
    void (*broken)(void *), void (*reinit)(void *), void (*cleanup)(void *))
{
	assert(p != NULL);
	assert(keepalive != NULL);
	assert(broken != NULL);
	assert(reinit != NULL);
	assert(cleanup != NULL);

	timeout_set_proc(&t->t_ka, keepalive, p);
	timeout_set_proc(&t->t_pka, keepalive, p);
	timeout_set_proc(&t->t_broken, broken, p);
	timeout_set_proc(&t->t_reinit, reinit, p);
	timeout_set_proc(&t->t_cleanup, cleanup, p);
}

void
wg_timer_stop(struct wg_timers *t)
{
	/* TODO need barrier? */
	timeout_del(&t->t_ka);
	timeout_del(&t->t_pka);
	timeout_del(&t->t_broken);
	timeout_del(&t->t_reinit);
	timeout_del(&t->t_cleanup);
}

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);
}

uint16_t
wg_timer_persistent_keepalive_get(struct wg_timers *t)
{
	return t->t_pka_interval;
}

void
wg_timer_persistent_keepalive_set(struct wg_timers *t, uint16_t interval)
{
	t->t_pka_interval = 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);
}

/* if_wg.c */
int		 wg_softc_route_add(struct wg_softc *, struct wg_cidr *, struct wg_route *);
int		 wg_softc_route_delete(struct wg_softc *, struct wg_cidr *);
struct wg_route	*wg_softc_route_lookup(struct wg_softc *, struct mbuf *, bool);

int		 wg_mbuf_ratelimit(struct wg_softc *, struct mbuf *);
struct wg_tag	*wg_mbuf_get_tag(struct mbuf *);

void		 wg_route_broken(struct wg_route *);
void		 wg_route_queue(struct wg_route *, enum wg_pkt_type, uint32_t);
void		 wg_peer_queue(struct wg_peer *, enum wg_pkt_type, uint32_t);

void		 wg_encrypt_hs(struct mbuf *);
void		 wg_encrypt(struct mbuf *);
void		 wg_decrypt_hs(struct mbuf *);
void		 wg_decrypt(struct mbuf *);

void		 wg_start(struct ifnet *);
int		 wg_output(struct ifnet *, struct mbuf *, struct sockaddr *,
		    struct rtentry *);
struct mbuf	*wg_input(void *, struct mbuf *, struct sockaddr *, int);
void		 wg_input_deliver(struct mbuf *);
void		 wg_output_deliver(struct mbuf *);

void		 wg_softc_peer_route_delete(struct wg_softc *, struct wg_peer *);
void		 wg_softc_peer_clean(struct wg_peer *);

void		 wgattach(int);
int		 wg_clone_create(struct if_clone *, int);
int		 wg_clone_destroy(struct ifnet *);
int		 wg_bind_port(struct wg_softc *);

int		 wg_ioctl_peer_set(struct wg_softc *, u_long,
		    struct wg_peer_set *);
int		 wg_ioctl_serv_set(struct wg_softc *, u_long,
		    struct wg_serv_set *);
int		 wg_ioctl_serv_get(struct wg_softc *, struct wg_serv_get *);
int		 wg_ioctl_peer_get(struct wg_softc *, struct wg_peer_get *);
int		 wg_ioctl(struct ifnet *, u_long, caddr_t);


MPQ_WORKER(wg_tx_slow_task_fn, wg_encrypt_hs, wg_output_deliver);
MPQ_WORKER(wg_tx_task_fn, wg_encrypt, wg_output_deliver);
MPQ_WORKER(wg_rx_slow_task_fn, wg_decrypt_hs, m_freem);
MPQ_WORKER(wg_rx_task_fn, wg_decrypt, wg_input_deliver);

/*
 * The following defines assist the antireplay_check function. *
 * ANTIREPLAY_INTEGER: the integer in the bitmap corresponding to num *
 * ANTIREPLAY_INTEGERBIT: the integer with corresponding single bit set
 */
#define ANTIREPLAY_INTEGER(ctx, num) (ctx->ar_bitmap[num % ARB_BITS / ARI_BITS])
#define ANTIREPLAY_INTEGERBIT(num) (1llu << (num & (ARI_BITS - 1)))

void
antireplay_init(struct antireplay *ctx)
{
	/* We just zero out the struct, expecting that then ctx->ar_head == 0 */
	explicit_bzero(ctx, sizeof(struct antireplay));
}

int
antireplay_update(struct antireplay *ctx, uint64_t num)
{
	/* Bits after ctx->ar_head need to be zeroed. This is called when num is
	 * in front of ctx->ar_head, and those bits need to be set to 0 */
	if (num < ctx->ar_head + ARB_BITS / ARI_BITS) {
		for (; ctx->ar_head <= num; ctx->ar_head += ARI_BITS) {
			ANTIREPLAY_INTEGER(ctx, (ctx->ar_head + 1)) = 0;
		}
	} else {
		bzero(ctx->ar_bitmap, ARB_BITS / ARI_BITS);
	}

	if (ctx->ar_head > (num + ARB_BITS - ARI_BITS)) {
		/* Expired */
		return 1;
	} else if (ANTIREPLAY_INTEGER(ctx, num) & ANTIREPLAY_INTEGERBIT(num)) {
		/* Replayed */
		return 1;
	} else {
		/* Unseen */
		return 0;
	}
}

/*
 * fixedmap.h
 */

//#define FMPRINTF(...) printf("fm: " __VA_ARGS__)
#define FMPRINTF(...) 0

void
fm_init(struct fixed_map *fm, size_t size, int ipl)
{
	bzero(fm, sizeof(*fm));
	mtx_init(&fm->mtx, ipl);
	fm_resize(fm, size);
}

void
fm_resize(struct fixed_map *fm, size_t size)
{
	size_t		 i;
	size_t 		 xsize;
	struct map_item	*xmap;

	for (xsize = 1; xsize < size; xsize <<= 1);

	mtx_enter(&fm->mtx);
	if (xsize < fm->size)
		goto leave;
	mtx_leave(&fm->mtx);

	xmap = mallocarray(xsize, sizeof(*xmap), M_DEVBUF, M_WAITOK | M_ZERO);

	mtx_enter(&fm->mtx);
	if (fm->map != NULL) {
		for (i = 0; i < fm->size; i++)
			xmap[fm->map[i].key % fm->size] = fm->map[i];
		free(fm->map, M_DEVBUF, 0);
	}
	fm->size = xsize;
	fm->map = xmap;
leave:
	mtx_leave(&fm->mtx);
}

void
fm_destroy(struct fixed_map *fm)
{
	struct map_item *item;
	FM_FOREACH_FILLED(item, fm)
		panic("non empty fixedmap");
	free(fm->map, M_DEVBUF, 0);
}

uint32_t
fm_insert(struct fixed_map *fm, void *v)
{
	uint32_t k = 0;
	struct map_item *item = NULL, *iter;

	mtx_enter(&fm->mtx);

	FM_FOREACH_EMPTY(iter, fm) {
		item = iter;
		break;
	}

	if (item == NULL)
		panic("fixed map not large enough");

	while (k == 0)
		k = (arc4random() & ~(fm->size - 1)) + (item - fm->map);

	item->key = k;
	item->state = FM_ITEM_FILLED;
	item->value = v;
	refcnt_init(&item->refcnt);
	mtx_leave(&fm->mtx);

	FMPRINTF("insert %x in %p - %d\n", k, fm, item->refcnt.refs);

	/* We want to take another reference, as one reference is in the map
	 * and the other one gets returned */
	refcnt_take(&item->refcnt);
	return k;
}

void *
fm_lookup(struct fixed_map *fm, uint32_t k)
{
	void *v = NULL;
	struct map_item *item;

	mtx_enter(&fm->mtx);
	item = fm->map + (k & (fm->size - 1));
	if (item->key == k) {
		refcnt_take(&item->refcnt);
		v = item->value;
		FMPRINTF("lookup %x in %p - %d\n", k, fm, item->refcnt.refs);
	} else {
		FMPRINTF("lookup %x in %p - failed\n", k, fm);
	}
	mtx_leave(&fm->mtx);
	return v;
}

void
fm_put(struct fixed_map *fm, uint32_t k)
{
	struct map_item *item;

	mtx_enter(&fm->mtx);
	item = fm->map + (k & (fm->size - 1));
	if (item->key != k)
		panic("element should be in map");
	refcnt_rele_wake(&item->refcnt);
	FMPRINTF("put %x in %p - %d\n", k, fm, item->refcnt.refs);
	mtx_leave(&fm->mtx);
}

void
fm_drop(struct fixed_map *fm, uint32_t k)
{
	struct map_item *item;

	mtx_enter(&fm->mtx);
	item = fm->map + (k & (fm->size - 1));
	if (item->key != k)
		panic("element should be in map");
	FMPRINTF("drop %x in %p - %d\n", k, fm, item->refcnt.refs);
	mtx_leave(&fm->mtx);

	refcnt_finalize(&item->refcnt, "fm_drop");

	mtx_enter(&fm->mtx);
	item->key = 0;
	item->state = FM_ITEM_EMPTY;
	item->value = NULL;
	mtx_leave(&fm->mtx);
}

/*
 * mpq.h
 */

void
mpq_init(struct mpq *mpq, int ipl)
{
	mpq->mpq_cursor = NULL;
	mpq->mpq_serializer = NULL;
	mtx_init(&mpq->mpq_mtx, ipl);
	ml_init(&mpq->mpq_list);
}

int
mpq_full(struct mpq *mpq)
{
	int full;
	mtx_enter(&mpq->mpq_mtx);
	full = ml_len(&mpq->mpq_list) >= MPQ_LEN;
	mtx_leave(&mpq->mpq_mtx);
	return full;
}

int
mpq_serialize_try_enter(struct mpq *mpq)
{
	int error = 1;
	mtx_enter(&mpq->mpq_mtx);
	if (mpq->mpq_serializer == NULL) {
		mpq->mpq_serializer = curcpu();
		error = 0;
	}
	mtx_leave(&mpq->mpq_mtx);
	return error;
}

void
mpq_serialize_leave(struct mpq *mpq)
{
	mtx_enter(&mpq->mpq_mtx);
	mpq->mpq_serializer = NULL;
	mtx_leave(&mpq->mpq_mtx);
}

void
mpq_threaddone(struct mpq *mpq, struct mbuf *m)
{
	mtx_enter(&mpq->mpq_mtx);
	SET(m->m_flags, M_LINK0);
	mtx_leave(&mpq->mpq_mtx);
}

void
mpq_enqueue(struct mpq *mpq, struct mbuf *m)
{
	CLR(m->m_flags, M_LINK0);
	mtx_enter(&mpq->mpq_mtx);
	if (ml_len(&mpq->mpq_list) < MPQ_LEN) {
		ml_enqueue(&mpq->mpq_list, m);
		if (mpq->mpq_cursor == NULL)
			mpq->mpq_cursor = m;
	} else {
		m_freem(m);
	}
	mtx_leave(&mpq->mpq_mtx);
}

struct mbuf
*mpq_dethread(struct mpq *mpq)
{
	struct mbuf *m;
	mtx_enter(&mpq->mpq_mtx);
	m = mpq->mpq_cursor;
	if (mpq->mpq_cursor != NULL)
		mpq->mpq_cursor = MBUF_LIST_NEXT(mpq->mpq_cursor);
	mtx_leave(&mpq->mpq_mtx);
	return m;
}

struct mbuf
*mpq_dequeue(struct mpq *mpq)
{
	struct mbuf *m;
	mtx_enter(&mpq->mpq_mtx);
	m = MBUF_LIST_FIRST(&mpq->mpq_list);
	if (m != NULL && ISSET(m->m_flags, M_LINK0))
		m = ml_dequeue(&mpq->mpq_list);
	else
		m = NULL;
	mtx_leave(&mpq->mpq_mtx);
	return m;
}

int
wg_softc_route_add(struct wg_softc *sc, struct wg_cidr *cidr, struct wg_route *r)
{
	struct art_node	*node;
	struct art_root	*root;
	struct wg_route_entry *route;

	if ((root = AF_VAL(cidr->c_af, sc->sc_ip_rt, sc->sc_ip6_rt)) == NULL)
		return EINVAL;

	rw_enter_write(&root->ar_lock);

	node = malloc(sizeof(*node), M_DEVBUF, M_WAITOK | M_ZERO);

	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(*route), M_DEVBUF, M_WAITOK);
	SLIST_INSERT_HEAD(&r->r_routes, route, r_entry);
	route->r_dst = r;
	route->r_cidr = *cidr;
	node->an_gc = (struct art_node *) route;

	rw_exit_write(&root->ar_lock);
	return 0;
}

int
wg_softc_route_delete(struct wg_softc *sc, struct wg_cidr *cidr)
{
	struct srp_ref	sr;
	struct art_node	*node;
	struct art_root	*root;
	struct wg_route_entry *route;

	if ((root = AF_VAL(cidr->c_af, sc->sc_ip_rt, sc->sc_ip6_rt)) == NULL)
		return EINVAL;

	rw_enter_write(&root->ar_lock);

	if ((node = art_lookup(root, &cidr->c_ip, cidr->c_mask, &sr)) == 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_entry *) node->an_gc;
	SLIST_REMOVE(&route->r_dst->r_routes, route, wg_route_entry, r_entry);
	free(route, M_DEVBUF, sizeof(struct wg_route_entry));
	free(node, M_DEVBUF, sizeof(*node));

	rw_exit_write(&root->ar_lock);

	return 0;
}

struct wg_route *
wg_softc_route_lookup(struct wg_softc * sc, struct mbuf * m, bool out)
{
	struct ip *iphdr;
#ifdef INET6
	struct ip6_hdr *ip6hdr;
#endif
	struct art_node	*node;
	struct srp_ref	sr;
	struct wg_route	*r = 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;
#ifdef INET6
	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;
#endif
	default:
		return NULL;
	}

	if (node != NULL)
		r = ((struct wg_route_entry *) node->an_gc)->r_dst;

	srp_leave(&sr);

	return r;
}

struct wg_tag *
wg_mbuf_get_tag(struct mbuf *m)
{
	struct m_tag	*mtag;

	if ((mtag = m_tag_find(m, PACKET_TAG_TUNNEL, NULL)) == NULL) {
		mtag = m_tag_get(PACKET_TAG_TUNNEL,
		    sizeof(struct wg_tag), M_NOWAIT);
		if (mtag == NULL)
			return (NULL);
		bzero(mtag + 1, sizeof(struct wg_tag));
		m_tag_prepend(m, mtag);
	}

	return ((struct wg_tag *)(mtag + 1));
}

/* The following functions are the peer send functions */
void
wg_route_send_initiation(struct wg_route *r)
{
	wg_route_queue(r, WG_PKT_INITIATION, r->r_peer->p_id);
}

void
wg_route_broken(struct wg_route *r)
{
	DPRINTF(r->r_sc, "broken session %x\n", r->r_peer->p_id);
	wg_peer_clean(r->r_peer);
	wg_route_queue(r, WG_PKT_INITIATION, r->r_peer->p_id);
}

void
wg_route_send_keepalive(struct wg_route *route)
{
	struct wg_session *session;
	if ((session = wg_peer_last_session(route->r_peer)) != NULL) {
		wg_route_queue(route, WG_PKT_TRANSPORT, session->s_local_id);
		wg_session_put(session);
	} else {
		wg_peer_reset_attempts(route->r_peer);
		wg_route_send_initiation(route);
	}
}

void
wg_route_clean(struct wg_route *r)
{
	DPRINTF(r->r_sc, "cleaning %x\n", r->r_peer->p_id);
	wg_peer_clean(r->r_peer);
}

void
wg_route_queue(struct wg_route *route, enum wg_pkt_type type, uint32_t dst)
{
	struct mbuf *m;
	struct wg_tag *tag;
	struct wg_softc *sc = route->r_sc;

	m = m_clget(NULL, M_WAITOK, wg_pkt_len[type]);
 	tag = wg_mbuf_get_tag(m);

	tag->t_sc = sc;
	tag->t_dst = dst;
	tag->t_type = type;
	tag->t_state = WG_PKT_STATE_NEW;

	m->m_len = wg_pkt_len[type];
	m_calchdrlen(m);

	if (type == WG_PKT_TRANSPORT) {
		m->m_len = 0;
		m_calchdrlen(m);
		mpq_enqueue(&sc->sc_tx_queue, m);
		task_add(sc->sc_taskq, &sc->sc_tx_task);
	} else {
		mpq_enqueue(&sc->sc_tx_slow_queue, m);
		task_add(sc->sc_taskq, &sc->sc_tx_slow_task);
	}
}

void
wg_peer_queue(struct wg_peer *peer, enum wg_pkt_type type, uint32_t dst)
{
	wg_route_queue(peer->p_arg, type, dst);
}

void
wg_peer_notify(struct wg_peer *peer)
{
	struct mbuf *m;
	struct sockaddr sa;
	struct wg_route *route = peer->p_arg;
	struct wg_softc *sc = route->r_sc;

	if (mq_empty(&route->r_outgoing))
		wg_route_send_keepalive(route);

	/* We know wg_output only uses sa to verify the AF */
	while ((m = mq_dequeue(&route->r_outgoing)) != NULL) {
		sa.sa_family = m->m_pkthdr.ph_family;
		wg_output(&sc->sc_if, m, &sa, NULL);
	}
	task_add(sc->sc_taskq, &sc->sc_tx_task);
}

void
wg_encrypt_hs(struct mbuf *m)
{
	enum wg_error err;
	struct wg_session *session;
	struct wg_tag *tag = wg_mbuf_get_tag(m);

	if (tag->t_state != WG_PKT_STATE_NEW)
		panic("not a new state packet: %d\n", tag->t_state);

	switch (tag->t_type) {
	case WG_PKT_INITIATION:
		if ((err = wg_device_tx_initiation(&tag->t_sc->sc_dev,
		    mtod(m, struct wg_msg_initiation *), tag->t_dst,
		    &session)) != WG_OK)
			drop_pkt_err(err);
		wg_timer_reinit_flag(&session->s_peer->p_timers);
		break;
	case WG_PKT_RESPONSE:
		if ((err = wg_device_tx_response(&tag->t_sc->sc_dev,
		    mtod(m, struct wg_msg_response *), tag->t_dst,
		    &session)) != WG_OK)
			drop_pkt_err(err);
		wg_timer_reinit_unflag(&session->s_peer->p_timers);
		break;
	default:
		panic("invalid packet type: %d\n", tag->t_type);
	}

	DPRINTF(tag->t_sc, "tx %s for %x, id %x\n", wg_pkt_str[tag->t_type],
	    session->s_peer->p_id, session->s_local_id);

	m->m_pkthdr.ph_cookie = m;
	tag->t_state = WG_PKT_STATE_DONE;
	tag->t_ip = peer_route(session->s_peer)->r_ip;
	wg_session_put(session);
	return;
drop:
	DPRINTF(tag->t_sc, "%s tx failed: %s\n", wg_pkt_str[tag->t_type],
	    wg_error_str[err]);
	tag->t_state = WG_PKT_STATE_DEAD;
}

void
wg_encrypt(struct mbuf *m)
{
	enum wg_error err;

	struct mbuf *em;
	struct wg_tag *tag;
	struct wg_session *session;
	struct wg_msg_transport *msg;

	size_t plain_len = m->m_pkthdr.len;
	size_t padding_len = WG_PADDING_SIZE(plain_len);
	size_t clear_len = plain_len + padding_len;
	size_t encrypted_len = WG_ENCRYPTED_SIZE(clear_len);
	size_t total_len = encrypted_len + sizeof(struct wg_msg_transport);

	tag = wg_mbuf_get_tag(m);

	if (tag->t_state != WG_PKT_STATE_NEW)
		panic("not a new state packet: %d\n", tag->t_state);

	em = m_clget(NULL, M_WAITOK, total_len);
	m->m_pkthdr.ph_cookie = em;
	em->m_len = total_len;
	m_calchdrlen(em);
	msg = mtod(em, struct wg_msg_transport *);

	m_copydata(m, 0, plain_len, msg->data);
	bzero(msg->data + plain_len, padding_len);

	if ((err = wg_device_tx_transport(&tag->t_sc->sc_dev, msg, clear_len,
	    tag->t_dst, &session)) != WG_OK)
		goto drop;

	if (plain_len > 0) {
		counters_pkt(tag->t_sc->sc_if.if_counters, ifc_opackets,
		    ifc_obytes, plain_len);
		wg_timer_broken_flag(&session->s_peer->p_timers);
	} else {
		DPRINTF(tag->t_sc, "send keepalive %x\n", session->s_local_id);
	}

	wg_timer_keepalive_unflag(&session->s_peer->p_timers);
	wg_timer_persistent_keepalive_tick(&session->s_peer->p_timers);

	m->m_pkthdr.ph_cookie = em;
	tag->t_state = WG_PKT_STATE_DONE;
	tag->t_ip = peer_route(session->s_peer)->r_ip;
	wg_session_put(session);
	return;
drop:
	m_freem(em);
	counters_inc(tag->t_sc->sc_if.if_counters, ifc_oerrors);
	DPRINTF(tag->t_sc, "failed transport tx: %s\n", wg_error_str[err]);
	tag->t_state = WG_PKT_STATE_DEAD;
}

void
wg_decrypt_hs(struct mbuf *m)
{
	enum wg_error err = WG_OK;

	struct wg_tag *tag;
	struct wg_session *session;

 	tag = wg_mbuf_get_tag(m);
	m_defrag(m, M_WAIT);

	if (tag->t_state != WG_PKT_STATE_NEW)
		panic("not a new state packet: %d", tag->t_state);

	switch (tag->t_type) {
	case WG_PKT_INITIATION:
		/* if (wg_mbuf_ratelimit(tag->t_sc, m))
			drop_pkt_err(WG_RATELIMIT); */

		if ((err = wg_device_rx_initiation(&tag->t_sc->sc_dev, 
		    mtod(m, struct wg_msg_initiation *), &session)) != WG_OK)
			drop_pkt_err(err);

		break;
	case WG_PKT_RESPONSE:
		/* if (wg_mbuf_ratelimit(tag->t_sc, m))
			drop_pkt_err(WG_RATELIMIT); */

		if ((err = wg_device_rx_response(&tag->t_sc->sc_dev, 
		    mtod(m, struct wg_msg_response *), &session)) != WG_OK)
			drop_pkt_err(err);

		wg_timer_reinit_unflag(&session->s_peer->p_timers);
		break;
	case WG_PKT_COOKIE:
		if ((err = wg_device_rx_cookie(&tag->t_sc->sc_dev, 
		    mtod(m, struct wg_msg_cookie *), &session)) != WG_OK)
			drop_pkt_err(err);
		break;
	default:
		panic("not a handshake packet: %d", tag->t_type);
	}

	DPRINTF(tag->t_sc, "rx %s for %x, id %x\n", wg_pkt_str[tag->t_type],
	    session->s_peer->p_id, session->s_local_id);

	tag->t_state = WG_PKT_STATE_DONE;
	peer_route(session->s_peer)->r_ip = tag->t_ip;
	wg_session_put(session);
	return;
drop:
	counters_inc(tag->t_sc->sc_if.if_counters, ifc_ierrors);
	DPRINTF(tag->t_sc, "%s rx failed: %s\n", wg_pkt_str[tag->t_type], wg_error_str[err]);
	tag->t_state = WG_PKT_STATE_DEAD;
}

void
wg_decrypt(struct mbuf *m)
{
	enum wg_error err;
	struct wg_session *session;
	struct wg_tag *tag = wg_mbuf_get_tag(m);
	struct wg_msg_transport *msg = mtod(m, struct wg_msg_transport *);

	m_defrag(m, M_WAIT);

	KASSERT(tag->t_type == WG_PKT_TRANSPORT);
	KASSERT(tag->t_state == WG_PKT_STATE_NEW);

	if ((err = wg_device_rx_transport(&tag->t_sc->sc_dev, msg,
	    m->m_pkthdr.len, &session)) != WG_OK)
		drop_pkt_err(err);

	m_adj(m, sizeof(struct wg_msg_transport));

	if (m->m_pkthdr.len == WG_ENCRYPTED_SIZE(0)) {
		tag->t_state = WG_PKT_STATE_DEAD;
		DPRINTF(tag->t_sc, "recv keepalive %x\n", session->s_local_id);
		goto keepalive;
	}

	if (mtod(m, struct ip *)->ip_v == IPVERSION)
		m->m_pkthdr.ph_family = AF_INET;
#ifdef INET6
	else if ((mtod(m, struct ip6_hdr *)->ip6_vfc & IPV6_VERSION_MASK) ==
	    IPV6_VERSION)
		m->m_pkthdr.ph_family = AF_INET6;
#endif
	else
		drop_pkt_err(WG_INVALID_PKT);

	/* Lookup outgoing route for incoming packet ip src, for crypto key
	 * routing. 'false' indicates src address */
	if (wg_softc_route_lookup(tag->t_sc, m, false) != session->s_peer->p_arg)
		drop_pkt_err(WG_ALLOWED_IP_FAIL);

	counters_pkt(tag->t_sc->sc_if.if_counters, ifc_ipackets, ifc_ibytes,
	    m->m_pkthdr.len);
	wg_timer_keepalive_flag(&session->s_peer->p_timers);

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

	tag->t_state = WG_PKT_STATE_DONE;

keepalive:
	wg_timer_persistent_keepalive_tick(&session->s_peer->p_timers);
	wg_timer_broken_unflag(&session->s_peer->p_timers);

	peer_route(session->s_peer)->r_ip = tag->t_ip;
	wg_session_put(session);
	return;
drop:
	counters_inc(tag->t_sc->sc_if.if_counters, ifc_ierrors);
	DPRINTF(tag->t_sc, "failed transport rx: %s\n", wg_error_str[err]);
	tag->t_state = WG_PKT_STATE_DEAD;
}

/* The following functions are the stack facing network functions. They will
 * handle packets in and out for sending and receiving.
 */
void
wg_start(struct ifnet *ifp)
{
	struct mbuf *m;
	struct wg_softc *sc = ifp->if_softc;

	while (!mpq_full(&sc->sc_tx_queue) && (m = ifq_dequeue(&ifp->if_snd)) != NULL)
		mpq_enqueue(&sc->sc_tx_queue, m);
	task_add(sc->sc_taskq, &sc->sc_tx_task);
}

int
wg_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *sa,
    struct rtentry *rt)
{
	int error;
	struct wg_tag *tag;
	struct wg_route *route;
	struct wg_session *session;
	struct wg_softc *sc = ifp->if_softc;

	if (!AF_VAL(sa->sa_family, 1, 1)) {
		counters_inc(sc->sc_if.if_counters, ifc_noproto);
		m_freem(m);
		return EAFNOSUPPORT;
	}

	if ((tag = wg_mbuf_get_tag(m)) == NULL) {
		counters_inc(sc->sc_if.if_counters, ifc_oerrors);
		m_freem(m);
		return ENOBUFS;
	}

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

	route = wg_softc_route_lookup(sc, m, true);

	if (route == NULL || route->r_ip.sa.sa_family == AF_UNSPEC) {
		if (m->m_pkthdr.ph_family == AF_INET)
			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
#ifdef INET6
		else if (m->m_pkthdr.ph_family == AF_INET6)
			icmp6_error(m, ICMP6_DST_UNREACH,
			    ICMP6_DST_UNREACH_ADDR, 0);
#endif
		else
			m_freem(m);
		counters_inc(sc->sc_if.if_counters, ifc_oerrors);
		return ENETUNREACH;
	}

#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

	if ((session = wg_peer_last_session(route->r_peer)) == NULL) {
		if (mq_push(&route->r_outgoing, m) != 0)
			counters_inc(sc->sc_if.if_counters, ifc_oqdrops);
		wg_peer_reset_attempts(route->r_peer);
		wg_route_send_initiation(route);
		return 0;
	}

	tag->t_sc = sc;
	tag->t_dst = session->s_local_id;
	tag->t_type = WG_PKT_TRANSPORT;
	tag->t_state = WG_PKT_STATE_NEW;
	wg_session_put(session);

	if ((error = if_enqueue(ifp, m)) != 0) {
		counters_inc(sc->sc_if.if_counters, ifc_oqdrops);
		if_start(ifp);
		return error;
	}

	return 0;
}

struct mbuf *
wg_input(void *_sc, struct mbuf *m, struct sockaddr *sa, int hlen)
{
	struct wg_tag *tag;
	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))
		goto leave;

	if ((tag = wg_mbuf_get_tag(m)) == NULL)
		goto free;

	memcpy(&tag->t_ip.sa, sa, sa->sa_len);
	tag->t_sc = sc;
	tag->t_type = wg_pkt_type(mtod(m, uint8_t *), m->m_pkthdr.len);
	tag->t_state = WG_PKT_STATE_NEW;

	switch (tag->t_type) {
	case WG_PKT_INITIATION:
	case WG_PKT_RESPONSE:
	case WG_PKT_COOKIE:
		mpq_enqueue(&sc->sc_rx_slow_queue, m);
		task_add(sc->sc_taskq, &sc->sc_rx_slow_task);
		break;
	case WG_PKT_TRANSPORT:
		mpq_enqueue(&sc->sc_rx_queue, m);
		task_add(sc->sc_taskq, &sc->sc_rx_task);
		break;
	default:
		break;
	}


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

void
wg_input_deliver(struct mbuf *m)
{
	void (*fn_input)(struct ifnet *, struct mbuf *);
	struct wg_tag *tag = wg_mbuf_get_tag(m);
	struct wg_softc *sc = tag->t_sc;

	if (tag->t_state == WG_PKT_STATE_NEW)
		panic("unexpected state on: %p\n", m);
	else if (tag->t_state == WG_PKT_STATE_DEAD)
		m_freem(m);
	else if (tag->t_state == WG_PKT_STATE_DONE) {
#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_OUT);
#endif
		fn_input = AF_VAL(m->m_pkthdr.ph_family, ipv4_input, ipv6_input);
		NET_LOCK();
		if (fn_input)
			fn_input(&sc->sc_if, m);
		else
			panic("invalid af");
		NET_UNLOCK();
	} else {
		panic("invalid state: %d\n", tag->t_state);
	}
}

void
wg_output_deliver(struct mbuf *m)
{
	int error;
	struct socket *so;
	struct wg_softc *sc;
	struct mbuf peernam, *em;
	struct wg_tag *tag = wg_mbuf_get_tag(m);

	if (tag->t_state == WG_PKT_STATE_NEW)
		panic("unexpected state on: %p\n", m);
	else if (tag->t_state == WG_PKT_STATE_DEAD)
		m_freem(m);
	else if (tag->t_state == WG_PKT_STATE_DONE) {
		em = m->m_pkthdr.ph_cookie;
		bzero(&peernam, sizeof(struct mbuf));

		peernam.m_type = MT_SONAME;
		peernam.m_data = (caddr_t) &tag->t_ip;
		peernam.m_len = tag->t_ip.sa.sa_len;

		sc = tag->t_sc;

		so = AF_VAL(tag->t_ip.sa.sa_family, sc->sc_so4, sc->sc_so6);
		if (so) {
			int s = solock(so);
			if ((error = so->so_proto->pr_usrreq(so, PRU_SEND, em,
			    &peernam, NULL, NULL)) != 0)
				DPRINTF(sc, "unable to send: %d\n", error);
			sounlock(so, s);
		} else {
			m_freem(em);
		}

		if (em != m)
			m_freem(m);
	} else {
		panic("invalid state: %d\n", tag->t_state);
	}
}

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

void
wgattach(int nwg)
{
	if_clone_attach(&wg_cloner);
}

int
wg_clone_create(struct if_clone * ifc, int unit)
{
	struct ifnet	*ifp;
	struct inpcb	*inp;
	struct wg_softc *sc = malloc(sizeof(*sc), M_DEVBUF, M_WAITOK | M_ZERO);

	/* softc */
	socreate(AF_INET, &sc->sc_so4, SOCK_DGRAM, 0);
	sc->sc_ip_rt = art_alloc(0, 32, 0);
	inp = sotoinpcb(sc->sc_so4);
	inp->inp_upcall = wg_input;
	inp->inp_upcall_arg = sc;

#ifdef INET6
	socreate(AF_INET6, &sc->sc_so6, SOCK_DGRAM, 0);
	sc->sc_ip6_rt = art_alloc(0, 128, 0);
	inp = sotoinpcb(sc->sc_so6);
	inp->inp_upcall = wg_input;
	inp->inp_upcall_arg = sc;
#endif

	wg_device_init(&sc->sc_dev, IPL_NET, wg_peer_notify,
	    wg_peer_queue, wg_softc_peer_clean, sc);

	sc->sc_taskq = taskq_create("wg", ncpus, IPL_NET, TASKQ_MPSAFE);
	task_set(&sc->sc_tx_task, wg_tx_task_fn, &sc->sc_tx_queue);
	task_set(&sc->sc_tx_slow_task, wg_tx_slow_task_fn, &sc->sc_tx_slow_queue);
	task_set(&sc->sc_rx_task, wg_rx_task_fn, &sc->sc_rx_queue);
	task_set(&sc->sc_rx_slow_task, wg_rx_slow_task_fn, &sc->sc_rx_slow_queue);
	mpq_init(&sc->sc_tx_queue, IPL_NET);
	mpq_init(&sc->sc_tx_slow_queue, IPL_NET);
	mpq_init(&sc->sc_rx_queue, IPL_NET);
	mpq_init(&sc->sc_rx_slow_queue, IPL_NET);

	/* ifnet */

	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_DEBUG | IFF_NOARP | IFF_MULTICAST | IFF_BROADCAST;
	ifp->if_xflags = IFXF_CLONED;

	ifp->if_ioctl = wg_ioctl;
	ifp->if_output = wg_output;
	ifp->if_start = wg_start;
	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(uint32_t));
#endif

	NET_RLOCK();
	wg_bind_port(sc);
	NET_RUNLOCK();

	DPRINTF(sc, "created interface: %s\n", ifp->if_xname);

	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_device_destroy(&sc->sc_dev);

	taskq_destroy(sc->sc_taskq);

	soclose(sc->sc_so4, 0);
#ifdef INET6
	soclose(sc->sc_so6, 0);
#endif

	if_detach(ifp);

	DPRINTF(sc, "destroyed interface: %s\n", ifp->if_xname);

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

	/* Free structures */
	free(sc->sc_ip_rt, M_RTABLE, sizeof(*sc->sc_ip_rt));
#ifdef INET6
	free(sc->sc_ip6_rt, M_RTABLE, sizeof(*sc->sc_ip6_rt));
#endif
	free(sc, M_DEVBUF, sizeof(*sc));

	return (0);
}

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

	m_inithdr(&hostnam);

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

	/* This just seems dirty */
	soassertlocked(sc->sc_so4);
	inp = sotoinpcb(sc->sc_so4);
	inp->inp_lport = 0;
	inp->inp_laddr = (struct in_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;

#ifdef INET6
	sin6 = mtod(&hostnam, struct sockaddr_in6 *);

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

	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;
#endif

	return 0;
}

void
wg_softc_peer_route_delete(struct wg_softc *sc, struct wg_peer *peer)
{
	struct wg_route_entry *raip, *traip;
	struct wg_route *route = peer->p_arg;
	SLIST_FOREACH_SAFE(raip, &route->r_routes, r_entry, traip)
		wg_softc_route_delete(sc, &raip->r_cidr);
}

void
wg_softc_peer_clean(struct wg_peer *peer)
{
	struct wg_softc *sc = peer->p_device->d_arg;
	wg_timer_stop(&peer->p_timers);
	wg_softc_peer_route_delete(sc, peer);
	free(peer->p_arg, M_DEVBUF, sizeof(struct wg_route));
	DPRINTF(sc, "deleted peer: %x\n", peer->p_id);
}

int
wg_ioctl_peer_set(struct wg_softc *sc, u_long cmd, struct wg_peer_set *wsp)
{
	int ret = 0;
	struct wg_peer *peer;
	struct wg_route *route;

	struct wg_pubkey pub;

	if (suser(curproc))
		return EPERM;

	/* Silently ignore set peer when the key is for ourselves */
	if (!memcmp(sc->sc_dev.d_keypair.pub.k, wsp->sp_pubkey.k, WG_KEY_SIZE))
		return 0;
	if (IS_NULL_KEY(wsp->sp_pubkey.k) || IS_MASKED_KEY(wsp->sp_pubkey.k))
		return EINVAL;

	pub = wsp->sp_pubkey;
	if ((peer = wg_device_ref_peerkey(&sc->sc_dev, &pub)) == NULL) {
		route = malloc(sizeof(*route), M_DEVBUF, M_WAITOK | M_ZERO);
		peer = wg_device_new_peer(&sc->sc_dev, &pub, route);

		route->r_sc = sc;
		route->r_peer = peer;
		mq_init(&route->r_outgoing, IFQ_MAXLEN, IPL_NET);
		SLIST_INIT(&route->r_routes);

		wg_timer_setup(&peer->p_timers, route,
		    (void (*)(void *)) wg_route_send_keepalive,
		    (void (*)(void *)) wg_route_broken,
		    (void (*)(void *)) wg_route_send_initiation,
		    (void (*)(void *)) wg_route_clean);

		DPRINTF(sc, "added peer: %x\n", peer->p_id);
	}

	route = peer->p_arg;

	switch (cmd) {
	case SIOCSWGPEERIP:
		route->r_ip = wsp->sp_ip;
		break;
	case SIOCSWGPEERPSK:
		if (IS_NULL_KEY(wsp->sp_shared.k) ||
		    IS_MASKED_KEY(wsp->sp_shared.k))
			return EINVAL;
		wg_peer_setshared(peer, &wsp->sp_shared);
		break;
	case SIOCSWGPEERPKA:
		wg_timer_persistent_keepalive_set(&peer->p_timers, wsp->sp_pka);
		break;
	case SIOCDWGPEER:
		wg_peer_put(peer);
		wg_peer_drop(peer);
		return WG_OK;
	case SIOCSWGPEERAIP:
		ret = wg_softc_route_add(sc, &wsp->sp_route, route);
		break;
	case SIOCDWGPEERAIP:
		ret = wg_softc_route_delete(sc, &wsp->sp_route);
		break;
	case SIOCCWGPEERAIP:
		wg_softc_peer_route_delete(sc, peer);
		break;
	}

	wg_peer_put(peer);

	return ret;
}

int
wg_ioctl_serv_set(struct wg_softc *sc, u_long cmd, struct wg_serv_set *wss)
{
	struct wg_peer *peer;
	struct wg_keypair kp;

	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 */
		/* Check that the new key does not belong to a peer */
		/* TODO cleanup kp */
		wg_keypair_from_key(&kp, &wss->ss_privkey);
		peer = wg_device_ref_peerkey(&sc->sc_dev, &kp.pub);
		if (peer != NULL){
			wg_peer_put(peer);
			return ENOTSUP;
		}
		if (IS_NULL_KEY(wss->ss_privkey.k) ||
		    IS_MASKED_KEY(wss->ss_privkey.k))
			return EINVAL;

		wg_device_setkey(&sc->sc_dev, &wss->ss_privkey);
		break;
	case SIOCCWGPEERS: /* Clear all WireGuard peers */
		break;
	}
	return 0;
}

int
wg_ioctl_serv_get(struct wg_softc *sc, struct wg_serv_get *wgs)
{
	struct map_item *item;
	struct wg_peer *peer;
	size_t num = 0;

	wgs->gs_port = sc->sc_port;
	wg_device_getkey(&sc->sc_dev, &wgs->gs_keypair);

	/* For the time being, no lock as we hold kernel lock in ioctl */
	FM_FOREACH_FILLED(item, &sc->sc_dev.d_peers) {
		if (num < wgs->gs_num_peers) {
			peer = item->value;
			copyout(peer->p_remote.k, wgs->gs_peers[num].k, WG_KEY_SIZE);
		}
		num++;
	}
	wgs->gs_num_peers = num;
	return 0;
}

int
wg_ioctl_peer_get(struct wg_softc *sc, struct wg_peer_get *wgp)
{
	size_t num = 0;
	struct wg_peer *peer;
	struct wg_route *route;

	if ((peer = wg_device_ref_peerkey(&sc->sc_dev, &wgp->gp_pubkey)) == NULL)
		return ENOENT;

	route = peer->p_arg;

	wg_peer_getshared(peer, &wgp->gp_shared);

	wgp->gp_last_handshake = wg_peer_last_handshake(peer);
	wgp->gp_pka = wg_timer_persistent_keepalive_get(&peer->p_timers);

	wgp->gp_tx_bytes = peer->p_tx_bytes;
	wgp->gp_rx_bytes = peer->p_rx_bytes;
	wgp->gp_ip = route->r_ip;

	struct wg_route_entry *r;
	SLIST_FOREACH(r, &route->r_routes, r_entry) {
		if (num < wgp->gp_num_routes)
			copyout(&r->r_cidr, &wgp->gp_routes[num], sizeof(*wgp->gp_routes));
		num++;
	}
	wgp->gp_num_routes = num;
	wg_peer_put(peer);
	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_serv_set(sc, cmd, (struct wg_serv_set *) 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_peer_set(sc, cmd, (struct wg_peer_set *) data);
		break;
	case SIOCGWGSERV: /* Get WireGuard server configuration */
		ret = wg_ioctl_serv_get(sc, (struct wg_serv_get *) data);
		break;
	case SIOCGWGPEER: /* Get WireGuard peer status */
		ret = wg_ioctl_peer_get(sc, (struct wg_peer_get *) 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;
#ifdef INET6
			sotoinpcb(sc->sc_so6)->inp_rtableid =
			    ifr->ifr_rdomainid;
#endif
			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;
}