xref: /freebsd/sys/net/if_ovpn.c (revision 3a3af6b2a160bea72509a9d5ef84e25906b0478a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2021-2022 Rubicon Communications, LLC (Netgate)
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  */
28 #include "opt_inet.h"
29 #include "opt_inet6.h"
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf_ring.h>
34 #include <sys/epoch.h>
35 #include <sys/file.h>
36 #include <sys/filedesc.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/module.h>
41 #include <sys/nv.h>
42 #include <sys/priv.h>
43 #include <sys/protosw.h>
44 #include <sys/rmlock.h>
45 #include <sys/sdt.h>
46 #include <sys/smp.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sockio.h>
50 #include <sys/sysctl.h>
51 #include <sys/time.h>
52 
53 #include <machine/atomic.h>
54 
55 #include <net/bpf.h>
56 #include <net/if.h>
57 #include <net/if_clone.h>
58 #include <net/if_types.h>
59 #include <net/if_var.h>
60 #include <net/netisr.h>
61 #include <net/route/nhop.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/in_fib.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip6.h>
67 #include <netinet/ip_var.h>
68 #include <netinet/udp.h>
69 #include <netinet/udp_var.h>
70 
71 #include <netinet6/ip6_var.h>
72 #include <netinet6/in6_fib.h>
73 
74 #include <machine/in_cksum.h>
75 
76 #include <opencrypto/cryptodev.h>
77 
78 #include "if_ovpn.h"
79 
80 struct ovpn_kkey_dir {
81 	int			refcount;
82 	uint8_t			key[32];
83 	uint8_t			keylen;
84 	uint8_t			nonce[8];
85 	uint8_t			noncelen;
86 	enum ovpn_key_cipher	cipher;
87 	crypto_session_t	cryptoid;
88 
89 	struct mtx		replay_mtx;
90 	/*
91 	 * Last seen gapless sequence number. New rx seq numbers must be
92 	 * strictly higher than this.
93 	 */
94 	uint32_t		rx_seq;
95 	/* Seen packets, relative to rx_seq. bit(0) will always be 0. */
96 	uint64_t		rx_window;
97 };
98 
99 struct ovpn_kkey {
100 	struct ovpn_kkey_dir	*encrypt;
101 	struct ovpn_kkey_dir	*decrypt;
102 	uint8_t			 keyid;
103 	uint32_t		 peerid;
104 };
105 
106 struct ovpn_keepalive {
107 	uint32_t	interval;
108 	uint32_t	timeout;
109 };
110 
111 struct ovpn_wire_header {
112 	uint32_t	 opcode; /* opcode, key id, peer id */
113 	uint32_t	 seq;
114 	uint8_t		 auth_tag[16];
115 };
116 
117 struct ovpn_notification {
118 	enum ovpn_notif_type	type;
119 	uint32_t		peerid;
120 };
121 
122 struct ovpn_softc;
123 
124 struct ovpn_kpeer {
125 	int			 refcount;
126 	uint32_t		 peerid;
127 
128 	struct ovpn_softc	*sc;
129 	struct sockaddr_storage	 local;
130 	struct sockaddr_storage	 remote;
131 
132 	struct in_addr		 vpn4;
133 	struct in6_addr		 vpn6;
134 
135 	struct ovpn_kkey	 keys[2];
136 	uint32_t		 tx_seq;
137 
138 	struct ovpn_keepalive	 keepalive;
139 	uint32_t		*last_active;
140 	struct callout		 ping_send;
141 	struct callout		 ping_rcv;
142 };
143 
144 #define OVPN_MAX_PEERS	128
145 
146 struct ovpn_counters {
147 	uint64_t	lost_ctrl_pkts_in;
148 	uint64_t	lost_ctrl_pkts_out;
149 	uint64_t	lost_data_pkts_in;
150 	uint64_t	lost_data_pkts_out;
151 	uint64_t	nomem_data_pkts_in;
152 	uint64_t	nomem_data_pkts_out;
153 	uint64_t	received_ctrl_pkts;
154 	uint64_t	received_data_pkts;
155 	uint64_t	sent_ctrl_pkts;
156 	uint64_t	sent_data_pkts;
157 
158 	uint64_t	transport_bytes_sent;
159 	uint64_t	transport_bytes_received;
160 	uint64_t	tunnel_bytes_sent;
161 	uint64_t	tunnel_bytes_received;
162 };
163 #define OVPN_COUNTER_SIZE (sizeof(struct ovpn_counters)/sizeof(uint64_t))
164 
165 struct ovpn_softc {
166 	int			 refcount;
167 	struct rmlock		 lock;
168 	struct ifnet		*ifp;
169 	struct socket		*so;
170 	int			 peercount;
171 	struct ovpn_kpeer	*peers[OVPN_MAX_PEERS]; /* XXX Hard limit for now? */
172 
173 	/* Pending packets */
174 	struct buf_ring		*rxring;
175 	struct buf_ring		*notifring;
176 
177 	counter_u64_t 		 counters[OVPN_COUNTER_SIZE];
178 
179 	struct epoch_context	 epoch_ctx;
180 };
181 
182 static struct ovpn_kpeer *ovpn_find_peer(struct ovpn_softc *, uint32_t);
183 static bool ovpn_udp_input(struct mbuf *, int, struct inpcb *,
184     const struct sockaddr *, void *);
185 static int ovpn_transmit_to_peer(struct ifnet *, struct mbuf *,
186     struct ovpn_kpeer *, struct rm_priotracker *);
187 static int ovpn_encap(struct ovpn_softc *, uint32_t, struct mbuf *);
188 static int ovpn_get_af(struct mbuf *);
189 static void ovpn_free_kkey_dir(struct ovpn_kkey_dir *);
190 static bool ovpn_check_replay(struct ovpn_kkey_dir *, uint32_t);
191 
192 #define OVPN_MTU_MIN		576
193 #define OVPN_MTU_MAX		(IP_MAXPACKET - sizeof(struct ip) - \
194     sizeof(struct udphdr) - sizeof(struct ovpn_wire_header))
195 
196 #define OVPN_OP_DATA_V2		0x09
197 #define OVPN_OP_SHIFT		3
198 
199 VNET_DEFINE_STATIC(struct if_clone *, ovpn_cloner);
200 #define	V_ovpn_cloner	VNET(ovpn_cloner)
201 
202 #define OVPN_RLOCK_TRACKER	struct rm_priotracker _ovpn_lock_tracker; \
203     struct rm_priotracker *_ovpn_lock_trackerp = &_ovpn_lock_tracker
204 #define OVPN_RLOCK(sc)		rm_rlock(&(sc)->lock, _ovpn_lock_trackerp)
205 #define OVPN_RUNLOCK(sc)	rm_runlock(&(sc)->lock, _ovpn_lock_trackerp)
206 #define OVPN_WLOCK(sc)		rm_wlock(&(sc)->lock)
207 #define OVPN_WUNLOCK(sc)	rm_wunlock(&(sc)->lock)
208 #define OVPN_ASSERT(sc)		rm_assert(&(sc)->lock, RA_LOCKED)
209 #define OVPN_RASSERT(sc)	rm_assert(&(sc)->lock, RA_RLOCKED)
210 #define OVPN_WASSERT(sc)	rm_assert(&(sc)->lock, RA_WLOCKED)
211 #define OVPN_UNLOCK_ASSERT(sc)	rm_assert(&(sc)->lock, RA_UNLOCKED)
212 
213 #define OVPN_COUNTER_ADD(sc, name, val)	\
214 	counter_u64_add(sc->counters[offsetof(struct ovpn_counters, name) / \
215 	    sizeof(uint64_t)], val)
216 
217 #define TO_IN(x)		((struct sockaddr_in *)(x))
218 #define TO_IN6(x)		((struct sockaddr_in6 *)(x))
219 
220 SDT_PROVIDER_DEFINE(if_ovpn);
221 SDT_PROBE_DEFINE1(if_ovpn, tx, transmit, start, "struct mbuf *");
222 SDT_PROBE_DEFINE2(if_ovpn, tx, route, ip4, "struct in_addr *", "struct ovpn_kpeer *");
223 SDT_PROBE_DEFINE2(if_ovpn, tx, route, ip6, "struct in6_addr *", "struct ovpn_kpeer *");
224 
225 static const char ovpnname[] = "ovpn";
226 static const char ovpngroupname[] = "openvpn";
227 
228 static MALLOC_DEFINE(M_OVPN, ovpnname, "OpenVPN DCO Interface");
229 
230 SYSCTL_DECL(_net_link);
231 static SYSCTL_NODE(_net_link, IFT_OTHER, openvpn, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
232     "OpenVPN DCO Interface");
233 VNET_DEFINE_STATIC(int, replay_protection) = 0;
234 #define	V_replay_protection	VNET(replay_protection)
235 SYSCTL_INT(_net_link_openvpn, OID_AUTO, replay_protection, CTLFLAG_VNET | CTLFLAG_RW,
236     &VNET_NAME(replay_protection), 0, "Validate sequence numbers");
237 
238 static struct ovpn_kpeer *
239 ovpn_find_peer(struct ovpn_softc *sc, uint32_t peerid)
240 {
241 	struct ovpn_kpeer *p = NULL;
242 
243 	OVPN_ASSERT(sc);
244 
245 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
246 		p = sc->peers[i];
247 		if (p == NULL)
248 			continue;
249 
250 		if (p->peerid == peerid) {
251 			MPASS(p->sc == sc);
252 			break;
253 		}
254 	}
255 
256 	return (p);
257 }
258 
259 static struct ovpn_kpeer *
260 ovpn_find_only_peer(struct ovpn_softc *sc)
261 {
262 	OVPN_ASSERT(sc);
263 
264 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
265 		if (sc->peers[i] == NULL)
266 			continue;
267 		return (sc->peers[i]);
268 	}
269 
270 	MPASS(false);
271 
272 	return (NULL);
273 }
274 
275 static uint16_t
276 ovpn_get_port(struct sockaddr_storage *s)
277 {
278 	switch (s->ss_family) {
279 	case AF_INET: {
280 		struct sockaddr_in *in = (struct sockaddr_in *)s;
281 		return (in->sin_port);
282 	}
283 	case AF_INET6: {
284 		struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)s;
285 		return (in6->sin6_port);
286 	}
287 	default:
288 		panic("Unsupported address family %d", s->ss_family);
289 	}
290 }
291 
292 static int
293 ovpn_nvlist_to_sockaddr(const nvlist_t *nvl, struct sockaddr_storage *sa)
294 {
295 	int af;
296 
297 	if (! nvlist_exists_number(nvl, "af"))
298 		return (EINVAL);
299 	if (! nvlist_exists_binary(nvl, "address"))
300 		return (EINVAL);
301 	if (! nvlist_exists_number(nvl, "port"))
302 		return (EINVAL);
303 
304 	af = nvlist_get_number(nvl, "af");
305 
306 	switch (af) {
307 #ifdef INET
308 	case AF_INET: {
309 		struct sockaddr_in *in = (struct sockaddr_in *)sa;
310 		size_t len;
311 		const void *addr = nvlist_get_binary(nvl, "address", &len);
312 		in->sin_family = af;
313 		if (len != sizeof(in->sin_addr))
314 			return (EINVAL);
315 
316 		memcpy(&in->sin_addr, addr, sizeof(in->sin_addr));
317 		in->sin_port = nvlist_get_number(nvl, "port");
318 		break;
319 	}
320 #endif
321 #ifdef INET6
322 	case AF_INET6: {
323 		struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)sa;
324 		size_t len;
325 		const void *addr = nvlist_get_binary(nvl, "address", &len);
326 		in6->sin6_family = af;
327 		if (len != sizeof(in6->sin6_addr))
328 			return (EINVAL);
329 
330 		memcpy(&in6->sin6_addr, addr, sizeof(in6->sin6_addr));
331 		in6->sin6_port = nvlist_get_number(nvl, "port");
332 		break;
333 	}
334 #endif
335 	default:
336 		return (EINVAL);
337 	}
338 
339 	return (0);
340 }
341 
342 static bool
343 ovpn_has_peers(struct ovpn_softc *sc)
344 {
345 	OVPN_ASSERT(sc);
346 
347 	return (sc->peercount > 0);
348 }
349 
350 static void
351 ovpn_rele_so(struct ovpn_softc *sc, struct ovpn_kpeer *peer)
352 {
353 	bool has_peers;
354 
355 	OVPN_WASSERT(sc);
356 
357 	if (sc->so == NULL)
358 		return;
359 
360 	has_peers = ovpn_has_peers(sc);
361 
362 	/* Only remove the tunnel function if we're releasing the socket for
363 	 * the last peer. */
364 	if (! has_peers)
365 		(void)udp_set_kernel_tunneling(sc->so, NULL, NULL, NULL);
366 
367 	sorele(sc->so);
368 
369 	if (! has_peers)
370 		sc->so = NULL;
371 }
372 
373 static void
374 ovpn_notify_del_peer(struct ovpn_softc *sc, struct ovpn_kpeer *peer)
375 {
376 	struct ovpn_notification *n;
377 
378 	OVPN_WASSERT(sc);
379 
380 	n = malloc(sizeof(*n), M_OVPN, M_NOWAIT);
381 	if (n == NULL)
382 		return;
383 
384 	n->peerid = peer->peerid;
385 	n->type = OVPN_NOTIF_DEL_PEER;
386 	if (buf_ring_enqueue(sc->notifring, n) != 0) {
387 		free(n, M_OVPN);
388 	} else if (sc->so != NULL) {
389 		/* Wake up userspace */
390 		sc->so->so_error = EAGAIN;
391 		sorwakeup(sc->so);
392 		sowwakeup(sc->so);
393 	}
394 }
395 
396 static void
397 ovpn_peer_release_ref(struct ovpn_kpeer *peer, bool locked)
398 {
399 	struct ovpn_softc *sc;
400 
401 	atomic_add_int(&peer->refcount, -1);
402 
403 	if (atomic_load_int(&peer->refcount) > 0)
404 		return;
405 
406 	sc = peer->sc;
407 
408 	if (! locked) {
409 		OVPN_WLOCK(sc);
410 
411 		/* Might have changed before we acquired the lock. */
412 		if (atomic_load_int(&peer->refcount) > 0) {
413 			OVPN_WUNLOCK(sc);
414 			return;
415 		}
416 	}
417 
418 	/* The peer should have been removed from the list already. */
419 	MPASS(ovpn_find_peer(sc, peer->peerid) == NULL);
420 
421 	ovpn_notify_del_peer(sc, peer);
422 
423 	for (int i = 0; i < 2; i++) {
424 		ovpn_free_kkey_dir(peer->keys[i].encrypt);
425 		ovpn_free_kkey_dir(peer->keys[i].decrypt);
426 	}
427 
428 	ovpn_rele_so(sc, peer);
429 
430 	callout_stop(&peer->ping_send);
431 	callout_stop(&peer->ping_rcv);
432 	uma_zfree_pcpu(pcpu_zone_4, peer->last_active);
433 	free(peer, M_OVPN);
434 
435 	if (! locked)
436 		OVPN_WUNLOCK(sc);
437 }
438 
439 static int
440 ovpn_new_peer(struct ifnet *ifp, const nvlist_t *nvl)
441 {
442 #ifdef INET6
443 	struct epoch_tracker et;
444 #endif
445 	struct sockaddr_storage remote;
446 	struct ovpn_kpeer *peer = NULL;
447 	struct file *fp = NULL;
448 	struct sockaddr *name = NULL;
449 	struct ovpn_softc *sc = ifp->if_softc;
450 	struct thread *td = curthread;
451 	struct socket *so = NULL;
452 	u_int fflag;
453 	int fd;
454 	uint32_t peerid;
455 	int ret = 0, i;
456 
457 	if (nvl == NULL)
458 		return (EINVAL);
459 
460 	if (! nvlist_exists_number(nvl, "peerid"))
461 		return (EINVAL);
462 
463 	if (! nvlist_exists_number(nvl, "fd"))
464 		return (EINVAL);
465 
466 	if (! nvlist_exists_nvlist(nvl, "remote"))
467 		return (EINVAL);
468 
469 	peerid = nvlist_get_number(nvl, "peerid");
470 
471 	ret = ovpn_nvlist_to_sockaddr(nvlist_get_nvlist(nvl, "remote"),
472 	    &remote);
473 	if (ret != 0)
474 		return (ret);
475 
476 	fd = nvlist_get_number(nvl, "fd");
477 
478 	/* Look up the userspace process and use the fd to find the socket. */
479 	ret = getsock_cap(td, fd, &cap_connect_rights, &fp,
480 	    &fflag, NULL);
481 	if (ret != 0)
482 		return (ret);
483 
484 	so = fp->f_data;
485 
486 	peer = malloc(sizeof(*peer), M_OVPN, M_WAITOK | M_ZERO);
487 	peer->peerid = peerid;
488 	peer->sc = sc;
489 	peer->tx_seq = 1;
490 	peer->refcount = 1;
491 	peer->last_active = uma_zalloc_pcpu(pcpu_zone_4, M_WAITOK | M_ZERO);
492 
493 	if (nvlist_exists_binary(nvl, "vpn_ipv4")) {
494 		size_t len;
495 		const void *addr = nvlist_get_binary(nvl, "vpn_ipv4", &len);
496 		if (len != sizeof(peer->vpn4)) {
497 			ret = EINVAL;
498 			goto error;
499 		}
500 		memcpy(&peer->vpn4, addr, len);
501 	}
502 
503 	if (nvlist_exists_binary(nvl, "vpn_ipv6")) {
504 		size_t len;
505 		const void *addr = nvlist_get_binary(nvl, "vpn_ipv6", &len);
506 		if (len != sizeof(peer->vpn6)) {
507 			ret = EINVAL;
508 			goto error;
509 		}
510 		memcpy(&peer->vpn6, addr, len);
511 	}
512 
513 	callout_init_rm(&peer->ping_send, &sc->lock, CALLOUT_SHAREDLOCK);
514 	callout_init_rm(&peer->ping_rcv, &sc->lock, 0);
515 
516 	ret = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, &name);
517 	if (ret)
518 		goto error;
519 
520 	if (ovpn_get_port((struct sockaddr_storage *)name) == 0) {
521 		ret = EINVAL;
522 		goto error;
523 	}
524 	if (name->sa_family != remote.ss_family) {
525 		ret = EINVAL;
526 		goto error;
527 	}
528 
529 	memcpy(&peer->local, name, name->sa_len);
530 	memcpy(&peer->remote, &remote, sizeof(remote));
531 	free(name, M_SONAME);
532 	name = NULL;
533 
534 	if (peer->local.ss_family == AF_INET6 &&
535 	    IN6_IS_ADDR_V4MAPPED(&TO_IN6(&peer->remote)->sin6_addr)) {
536 		/* V4 mapped address, so treat this as v4, not v6. */
537 		in6_sin6_2_sin_in_sock((struct sockaddr *)&peer->local);
538 		in6_sin6_2_sin_in_sock((struct sockaddr *)&peer->remote);
539 	}
540 
541 #ifdef INET6
542 	if (peer->local.ss_family == AF_INET6 &&
543 	    IN6_IS_ADDR_UNSPECIFIED(&TO_IN6(&peer->local)->sin6_addr)) {
544 		NET_EPOCH_ENTER(et);
545 		ret = in6_selectsrc_addr(curthread->td_proc->p_fibnum,
546 		    &TO_IN6(&peer->remote)->sin6_addr,
547 		    0, NULL, &TO_IN6(&peer->local)->sin6_addr, NULL);
548 		NET_EPOCH_EXIT(et);
549 		if (ret != 0) {
550 			goto error;
551 		}
552 	}
553 #endif
554 	OVPN_WLOCK(sc);
555 
556 	/* Disallow peer id re-use. */
557 	if (ovpn_find_peer(sc, peerid) != NULL) {
558 		ret = EEXIST;
559 		goto error_locked;
560 	}
561 
562 	/* Make sure this is really a UDP socket. */
563 	if (so->so_type != SOCK_DGRAM || so->so_proto->pr_type != SOCK_DGRAM) {
564 		ret = EPROTOTYPE;
565 		goto error_locked;
566 	}
567 
568 	/* Must be the same socket as for other peers on this interface. */
569 	if (sc->so != NULL && so != sc->so)
570 		goto error_locked;
571 
572 	if (sc->so == NULL)
573 		sc->so = so;
574 
575 	/* Insert the peer into the list. */
576 	for (i = 0; i < OVPN_MAX_PEERS; i++) {
577 		if (sc->peers[i] != NULL)
578 			continue;
579 
580 		MPASS(sc->peers[i] == NULL);
581 		sc->peers[i] = peer;
582 		sc->peercount++;
583 		soref(sc->so);
584 		break;
585 	}
586 	if (i == OVPN_MAX_PEERS) {
587 		ret = ENOSPC;
588 		goto error_locked;
589 	}
590 
591 	ret = udp_set_kernel_tunneling(sc->so, ovpn_udp_input, NULL, sc);
592 	if (ret == EBUSY) {
593 		/* Fine, another peer already set the input function. */
594 		ret = 0;
595 	}
596 	if (ret != 0) {
597 		sc->peers[i] = NULL;
598 		sc->peercount--;
599 		goto error_locked;
600 	}
601 
602 	OVPN_WUNLOCK(sc);
603 
604 	goto done;
605 
606 error_locked:
607 	OVPN_WUNLOCK(sc);
608 error:
609 	free(name, M_SONAME);
610 	uma_zfree_pcpu(pcpu_zone_4, peer->last_active);
611 	free(peer, M_OVPN);
612 done:
613 	if (fp != NULL)
614 		fdrop(fp, td);
615 
616 	return (ret);
617 }
618 
619 static int
620 _ovpn_del_peer(struct ovpn_softc *sc, uint32_t peerid)
621 {
622 	struct ovpn_kpeer *peer;
623 	int i;
624 
625 	OVPN_WASSERT(sc);
626 
627 	for (i = 0; i < OVPN_MAX_PEERS; i++) {
628 		if (sc->peers[i] == NULL)
629 			continue;
630 		if (sc->peers[i]->peerid != peerid)
631 			continue;
632 
633 		peer = sc->peers[i];
634 		break;
635 	}
636 	if (i == OVPN_MAX_PEERS)
637 		return (ENOENT);
638 
639 	sc->peers[i] = NULL;
640 	sc->peercount--;
641 
642 	ovpn_peer_release_ref(peer, true);
643 
644 	return (0);
645 }
646 
647 static int
648 ovpn_del_peer(struct ifnet *ifp, nvlist_t *nvl)
649 {
650 	struct ovpn_softc *sc = ifp->if_softc;
651 	uint32_t peerid;
652 	int ret;
653 
654 	OVPN_WASSERT(sc);
655 
656 	if (nvl == NULL)
657 		return (EINVAL);
658 
659 	if (! nvlist_exists_number(nvl, "peerid"))
660 		return (EINVAL);
661 
662 	peerid = nvlist_get_number(nvl, "peerid");
663 
664 	ret = _ovpn_del_peer(sc, peerid);
665 
666 	return (ret);
667 }
668 
669 static int
670 ovpn_create_kkey_dir(struct ovpn_kkey_dir **kdirp,
671     const nvlist_t *nvl)
672 {
673 	struct crypto_session_params csp;
674 	struct ovpn_kkey_dir *kdir;
675 	const char *ciphername;
676 	enum ovpn_key_cipher cipher;
677 	const void *key, *iv;
678 	size_t keylen = 0, ivlen = 0;
679 	int error;
680 
681 	if (! nvlist_exists_string(nvl, "cipher"))
682 		return (EINVAL);
683 	ciphername = nvlist_get_string(nvl, "cipher");
684 
685 	if (strcmp(ciphername, "none") == 0)
686 		cipher = OVPN_CIPHER_ALG_NONE;
687 	else if (strcmp(ciphername, "AES-256-GCM") == 0)
688 		cipher = OVPN_CIPHER_ALG_AES_GCM;
689 	else if (strcmp(ciphername, "CHACHA20-POLY1305") == 0)
690 		cipher = OVPN_CIPHER_ALG_CHACHA20_POLY1305;
691 	else
692 		return (EINVAL);
693 
694 	if (cipher != OVPN_CIPHER_ALG_NONE) {
695 		if (! nvlist_exists_binary(nvl, "key"))
696 			return (EINVAL);
697 		key = nvlist_get_binary(nvl, "key", &keylen);
698 		if (keylen > sizeof(kdir->key))
699 			return (E2BIG);
700 
701 		if (! nvlist_exists_binary(nvl, "iv"))
702 			return (EINVAL);
703 		iv = nvlist_get_binary(nvl, "iv", &ivlen);
704 		if (ivlen != 8)
705 			return (E2BIG);
706 	}
707 
708 	kdir = malloc(sizeof(struct ovpn_kkey_dir), M_OVPN,
709 	    M_WAITOK | M_ZERO);
710 
711 	kdir->cipher = cipher;
712 	kdir->keylen = keylen;
713 	memcpy(kdir->key, key, keylen);
714 	kdir->noncelen = ivlen;
715 	memcpy(kdir->nonce, iv, ivlen);
716 
717 	if (kdir->cipher != OVPN_CIPHER_ALG_NONE) {
718 		/* Crypto init */
719 		bzero(&csp, sizeof(csp));
720 		csp.csp_mode = CSP_MODE_AEAD;
721 
722 		if (kdir->cipher == OVPN_CIPHER_ALG_CHACHA20_POLY1305)
723 			csp.csp_cipher_alg = CRYPTO_CHACHA20_POLY1305;
724 		else
725 			csp.csp_cipher_alg = CRYPTO_AES_NIST_GCM_16;
726 
727 		csp.csp_flags |= CSP_F_SEPARATE_AAD;
728 
729 		csp.csp_cipher_klen = kdir->keylen;
730 		csp.csp_cipher_key = kdir->key;
731 		csp.csp_ivlen = 96 / 8;
732 
733 		error = crypto_newsession(&kdir->cryptoid, &csp,
734 		    CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE);
735 		if (error) {
736 			free(kdir, M_OVPN);
737 			return (error);
738 		}
739 	}
740 
741 	mtx_init(&kdir->replay_mtx, "if_ovpn rx replay", NULL, MTX_DEF);
742 	*kdirp = kdir;
743 
744 	return (0);
745 }
746 
747 static void
748 ovpn_free_kkey_dir(struct ovpn_kkey_dir *kdir)
749 {
750 	if (kdir == NULL)
751 		return;
752 
753 	mtx_destroy(&kdir->replay_mtx);
754 
755 	crypto_freesession(kdir->cryptoid);
756 	free(kdir, M_OVPN);
757 }
758 
759 static int
760 ovpn_set_key(struct ifnet *ifp, const nvlist_t *nvl)
761 {
762 	struct ovpn_softc *sc = ifp->if_softc;
763 	struct ovpn_kkey_dir *enc, *dec;
764 	struct ovpn_kpeer *peer;
765 	int slot, keyid, peerid;
766 	int error;
767 
768 	if (nvl == NULL)
769 		return (EINVAL);
770 
771 	if (! nvlist_exists_number(nvl, "slot"))
772 		return (EINVAL);
773 	slot = nvlist_get_number(nvl, "slot");
774 
775 	if (! nvlist_exists_number(nvl, "keyid"))
776 		return (EINVAL);
777 	keyid = nvlist_get_number(nvl, "keyid");
778 
779 	if (! nvlist_exists_number(nvl, "peerid"))
780 		return (EINVAL);
781 	peerid = nvlist_get_number(nvl, "peerid");
782 
783 	if (slot != OVPN_KEY_SLOT_PRIMARY &&
784 	    slot != OVPN_KEY_SLOT_SECONDARY)
785 		return (EINVAL);
786 
787 	if (! nvlist_exists_nvlist(nvl, "encrypt") ||
788 	    ! nvlist_exists_nvlist(nvl, "decrypt"))
789 		return (EINVAL);
790 
791 	error = ovpn_create_kkey_dir(&enc, nvlist_get_nvlist(nvl, "encrypt"));
792 	if (error)
793 		return (error);
794 
795 	error = ovpn_create_kkey_dir(&dec, nvlist_get_nvlist(nvl, "decrypt"));
796 	if (error) {
797 		ovpn_free_kkey_dir(enc);
798 		return (error);
799 	}
800 
801 	OVPN_WLOCK(sc);
802 
803 	peer = ovpn_find_peer(sc, peerid);
804 	if (peer == NULL) {
805 		ovpn_free_kkey_dir(dec);
806 		ovpn_free_kkey_dir(enc);
807 		OVPN_WUNLOCK(sc);
808 		return (ENOENT);
809 	}
810 
811 	ovpn_free_kkey_dir(peer->keys[slot].encrypt);
812 	ovpn_free_kkey_dir(peer->keys[slot].decrypt);
813 
814 	peer->keys[slot].encrypt = enc;
815 	peer->keys[slot].decrypt = dec;
816 
817 	peer->keys[slot].keyid = keyid;
818 	peer->keys[slot].peerid = peerid;
819 
820 	OVPN_WUNLOCK(sc);
821 
822 	return (0);
823 }
824 
825 static int
826 ovpn_check_key(struct ovpn_softc *sc, struct ovpn_kpeer *peer, enum ovpn_key_slot slot)
827 {
828 	OVPN_ASSERT(sc);
829 
830 	if (peer->keys[slot].encrypt == NULL)
831 		return (ENOLINK);
832 
833 	if (peer->keys[slot].decrypt == NULL)
834 		return (ENOLINK);
835 
836 	return (0);
837 }
838 
839 static int
840 ovpn_start(struct ifnet *ifp)
841 {
842 	struct ovpn_softc *sc = ifp->if_softc;
843 
844 	OVPN_WLOCK(sc);
845 
846 	ifp->if_flags |= IFF_UP;
847 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
848 	if_link_state_change(ifp, LINK_STATE_UP);
849 
850 	OVPN_WUNLOCK(sc);
851 
852 	return (0);
853 }
854 
855 static int
856 ovpn_swap_keys(struct ifnet *ifp, nvlist_t *nvl)
857 {
858 	struct ovpn_softc *sc = ifp->if_softc;
859 	struct ovpn_kpeer *peer;
860 	struct ovpn_kkey tmpkey;
861 	int error;
862 
863 	if (nvl == NULL)
864 		return (EINVAL);
865 
866 	if (! nvlist_exists_number(nvl, "peerid"))
867 		return (EINVAL);
868 
869 	OVPN_WLOCK(sc);
870 
871 	peer = ovpn_find_peer(sc, nvlist_get_number(nvl, "peerid"));
872 	if (peer == NULL) {
873 		OVPN_WUNLOCK(sc);
874 		return (ENOENT);
875 	}
876 
877 	/* Check that we have a second key to swap to. */
878 	error = ovpn_check_key(sc, peer, OVPN_KEY_SLOT_SECONDARY);
879 	if (error) {
880 		OVPN_WUNLOCK(sc);
881 		return (error);
882 	}
883 
884 	tmpkey = peer->keys[0];
885 	peer->keys[0] = peer->keys[1];
886 	peer->keys[1] = tmpkey;
887 
888 	OVPN_WUNLOCK(sc);
889 
890 	return (0);
891 }
892 
893 static int
894 ovpn_del_key(struct ifnet *ifp, const nvlist_t *nvl)
895 {
896 	enum ovpn_key_slot slot;
897 	struct ovpn_kpeer *peer;
898 	struct ovpn_softc *sc = ifp->if_softc;
899 
900 	if (nvl == NULL)
901 		return (EINVAL);
902 
903 	if (! nvlist_exists_number(nvl, "peerid"))
904 		return (EINVAL);
905 
906 	if (! nvlist_exists_number(nvl, "slot"))
907 		return (EINVAL);
908 	slot = nvlist_get_number(nvl, "slot");
909 
910 	if (slot != OVPN_KEY_SLOT_PRIMARY &&
911 	    slot != OVPN_KEY_SLOT_SECONDARY)
912 		return (EINVAL);
913 
914 	OVPN_WLOCK(sc);
915 
916 	peer = ovpn_find_peer(sc, nvlist_get_number(nvl, "peerid"));
917 	if (peer == NULL) {
918 		OVPN_WUNLOCK(sc);
919 		return (ENOENT);
920 	}
921 
922 	ovpn_free_kkey_dir(peer->keys[slot].encrypt);
923 	ovpn_free_kkey_dir(peer->keys[slot].decrypt);
924 
925 	peer->keys[slot].encrypt = NULL;
926 	peer->keys[slot].decrypt = NULL;
927 
928 	peer->keys[slot].keyid = 0;
929 	peer->keys[slot].peerid = 0;
930 
931 	OVPN_WUNLOCK(sc);
932 
933 	return (0);
934 }
935 
936 static int
937 ovpn_send_pkt(struct ifnet *ifp, const nvlist_t *nvl)
938 {
939 	struct epoch_tracker et;
940 	struct ovpn_softc *sc = ifp->if_softc;
941 	struct mbuf *m;
942 	const uint8_t *pkt;
943 	size_t pktlen;
944 	uint32_t peerid;
945 	int ret;
946 
947 	if (nvl == NULL)
948 		return (EINVAL);
949 
950 	if (! nvlist_exists_binary(nvl, "packet"))
951 		return (EINVAL);
952 	pkt = nvlist_get_binary(nvl, "packet", &pktlen);
953 
954 	if (! nvlist_exists_number(nvl, "peerid"))
955 		return (EINVAL);
956 
957 	peerid = nvlist_get_number(nvl, "peerid");
958 
959 	/*
960 	 * Check that userspace isn't giving us a data packet. That might lead
961 	 * to IV re-use, which would be bad.
962 	 */
963 	if ((pkt[0] >> OVPN_OP_SHIFT) == OVPN_OP_DATA_V2)
964 		return (EINVAL);
965 
966 	m = m_get2(pktlen, M_WAITOK, MT_DATA, M_PKTHDR);
967 	if (m == NULL)
968 		return (ENOMEM);
969 
970 	m->m_len = m->m_pkthdr.len = pktlen;
971 	m_copyback(m, 0, m->m_len, pkt);
972 
973 	/* Now prepend IP/UDP headers and transmit the mbuf. */
974 	NET_EPOCH_ENTER(et);
975 	ret = ovpn_encap(sc, peerid, m);
976 	NET_EPOCH_EXIT(et);
977 	if (ret == 0)
978 		OVPN_COUNTER_ADD(sc, sent_ctrl_pkts, 1);
979 	else
980 		OVPN_COUNTER_ADD(sc, lost_ctrl_pkts_out, 1);
981 
982 	return (ret);
983 }
984 
985 static void
986 ovpn_send_ping(void *arg)
987 {
988 	static const uint8_t ping_str[] = {
989 		0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
990 		0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48
991 	};
992 
993 	struct epoch_tracker et;
994 	struct ovpn_kpeer *peer = arg;
995 	struct ovpn_softc *sc = peer->sc;
996 	struct mbuf *m;
997 
998 	OVPN_RASSERT(sc);
999 
1000 	/* Ensure we repeat! */
1001 	callout_reset(&peer->ping_send, peer->keepalive.interval * hz,
1002 	    ovpn_send_ping, peer);
1003 
1004 	m = m_get2(sizeof(ping_str), M_NOWAIT, MT_DATA, M_PKTHDR);
1005 	if (m == NULL)
1006 		return;
1007 
1008 	m_copyback(m, 0, sizeof(ping_str), ping_str);
1009 	m->m_len = m->m_pkthdr.len = sizeof(ping_str);
1010 
1011 	CURVNET_SET(sc->ifp->if_vnet);
1012 	NET_EPOCH_ENTER(et);
1013 	(void)ovpn_transmit_to_peer(sc->ifp, m, peer, NULL);
1014 	NET_EPOCH_EXIT(et);
1015 	CURVNET_RESTORE();
1016 }
1017 
1018 static void
1019 ovpn_timeout(void *arg)
1020 {
1021 	struct ovpn_kpeer *peer = arg;
1022 	struct ovpn_softc *sc = peer->sc;
1023 	uint32_t last, _last_active;
1024 	int ret __diagused;
1025 	int cpu;
1026 
1027 	OVPN_WASSERT(sc);
1028 
1029 	last = 0;
1030 	CPU_FOREACH(cpu) {
1031 		_last_active = *zpcpu_get_cpu(peer->last_active, cpu);
1032 		if (_last_active > last)
1033 			last = _last_active;
1034 	}
1035 
1036 	if (last + peer->keepalive.timeout > time_uptime) {
1037 		callout_reset(&peer->ping_rcv,
1038 		    (peer->keepalive.timeout - (time_uptime - last)) * hz,
1039 		    ovpn_timeout, peer);
1040 		return;
1041 	}
1042 
1043 	CURVNET_SET(sc->ifp->if_vnet);
1044 	ret = _ovpn_del_peer(sc, peer->peerid);
1045 	MPASS(ret == 0);
1046 	CURVNET_RESTORE();
1047 }
1048 
1049 static int
1050 ovpn_set_peer(struct ifnet *ifp, const nvlist_t *nvl)
1051 {
1052 	struct ovpn_softc *sc = ifp->if_softc;
1053 	struct ovpn_kpeer *peer;
1054 
1055 	if (nvl == NULL)
1056 		return (EINVAL);
1057 
1058 	if (! nvlist_exists_number(nvl, "interval") ||
1059 	    ! nvlist_exists_number(nvl, "timeout") ||
1060 	    ! nvlist_exists_number(nvl, "peerid"))
1061 		return (EINVAL);
1062 
1063 	OVPN_WLOCK(sc);
1064 
1065 	peer = ovpn_find_peer(sc, nvlist_get_number(nvl, "peerid"));
1066 	if (peer == NULL) {
1067 		OVPN_WUNLOCK(sc);
1068 		return (ENOENT);
1069 	}
1070 
1071 	peer->keepalive.interval = nvlist_get_number(nvl, "interval");
1072 	peer->keepalive.timeout = nvlist_get_number(nvl, "timeout");
1073 
1074 	if (peer->keepalive.interval > 0)
1075 		callout_reset(&peer->ping_send, peer->keepalive.interval * hz,
1076 		    ovpn_send_ping, peer);
1077 	if (peer->keepalive.timeout > 0)
1078 		callout_reset(&peer->ping_rcv, peer->keepalive.timeout * hz,
1079 		    ovpn_timeout, peer);
1080 
1081 	OVPN_WUNLOCK(sc);
1082 
1083 	return (0);
1084 }
1085 
1086 static int
1087 ovpn_ioctl_set(struct ifnet *ifp, struct ifdrv *ifd)
1088 {
1089 	struct ovpn_softc *sc = ifp->if_softc;
1090 	uint8_t *buf = NULL;
1091 	nvlist_t *nvl = NULL;
1092 	int ret;
1093 
1094 	if (ifd->ifd_len != 0) {
1095 		if (ifd->ifd_len > OVPN_MAX_REQUEST_SIZE)
1096 			return (E2BIG);
1097 
1098 		buf = malloc(ifd->ifd_len, M_OVPN, M_WAITOK);
1099 
1100 		ret = copyin(ifd->ifd_data, buf, ifd->ifd_len);
1101 		if (ret != 0) {
1102 			free(buf, M_OVPN);
1103 			return (ret);
1104 		}
1105 
1106 		nvl = nvlist_unpack(buf, ifd->ifd_len, 0);
1107 		free(buf, M_OVPN);
1108 		if (nvl == NULL) {
1109 			return (EINVAL);
1110 		}
1111 	}
1112 
1113 	switch (ifd->ifd_cmd) {
1114 	case OVPN_NEW_PEER:
1115 		ret = ovpn_new_peer(ifp, nvl);
1116 		break;
1117 	case OVPN_DEL_PEER:
1118 		OVPN_WLOCK(sc);
1119 		ret = ovpn_del_peer(ifp, nvl);
1120 		OVPN_WUNLOCK(sc);
1121 		break;
1122 	case OVPN_NEW_KEY:
1123 		ret = ovpn_set_key(ifp, nvl);
1124 		break;
1125 	case OVPN_START_VPN:
1126 		ret = ovpn_start(ifp);
1127 		break;
1128 	case OVPN_SWAP_KEYS:
1129 		ret = ovpn_swap_keys(ifp, nvl);
1130 		break;
1131 	case OVPN_DEL_KEY:
1132 		ret = ovpn_del_key(ifp, nvl);
1133 		break;
1134 	case OVPN_SEND_PKT:
1135 		ret = ovpn_send_pkt(ifp, nvl);
1136 		break;
1137 	case OVPN_SET_PEER:
1138 		ret = ovpn_set_peer(ifp, nvl);
1139 		break;
1140 	default:
1141 		ret = ENOTSUP;
1142 	}
1143 
1144 	nvlist_destroy(nvl);
1145 	return (ret);
1146 }
1147 
1148 static int
1149 ovpn_add_counters(nvlist_t *parent, const char *name, counter_u64_t in,
1150     counter_u64_t out)
1151 {
1152 	nvlist_t *nvl;
1153 
1154 	nvl = nvlist_create(0);
1155 	if (nvl == NULL)
1156 		return (ENOMEM);
1157 
1158 	nvlist_add_number(nvl, "in", counter_u64_fetch(in));
1159 	nvlist_add_number(nvl, "out", counter_u64_fetch(out));
1160 
1161 	nvlist_add_nvlist(parent, name, nvl);
1162 
1163 	nvlist_destroy(nvl);
1164 
1165 	return (0);
1166 }
1167 
1168 static int
1169 ovpn_get_stats(struct ovpn_softc *sc, nvlist_t **onvl)
1170 {
1171 	nvlist_t *nvl;
1172 	int ret;
1173 
1174 	nvl = nvlist_create(0);
1175 	if (nvl == NULL)
1176 		return (ENOMEM);
1177 
1178 #define OVPN_COUNTER_OUT(name, in, out) \
1179 	do { \
1180 		ret = ovpn_add_counters(nvl, name, \
1181 		    sc->counters[offsetof(struct ovpn_counters, in) / \
1182 		    sizeof(uint64_t)], \
1183 		    sc->counters[offsetof(struct ovpn_counters, out) / \
1184 		    sizeof(uint64_t)]); \
1185 		if (ret != 0) \
1186 			goto error; \
1187 	} while(0)
1188 
1189 	OVPN_COUNTER_OUT("lost_ctrl", lost_ctrl_pkts_in, lost_ctrl_pkts_out);
1190 	OVPN_COUNTER_OUT("lost_data", lost_data_pkts_in, lost_data_pkts_out);
1191 	OVPN_COUNTER_OUT("nomem_data", nomem_data_pkts_in,
1192 	    nomem_data_pkts_out);
1193 	OVPN_COUNTER_OUT("data", received_data_pkts, sent_data_pkts);
1194 	OVPN_COUNTER_OUT("ctrl", received_ctrl_pkts, sent_ctrl_pkts);
1195 	OVPN_COUNTER_OUT("tunnel", tunnel_bytes_received,
1196 	    tunnel_bytes_received);
1197 	OVPN_COUNTER_OUT("transport", transport_bytes_received,
1198 	    transport_bytes_received);
1199 #undef OVPN_COUNTER_OUT
1200 
1201 	*onvl = nvl;
1202 
1203 	return (0);
1204 
1205 error:
1206 	nvlist_destroy(nvl);
1207 	return (ret);
1208 }
1209 
1210 static int
1211 ovpn_poll_pkt(struct ovpn_softc *sc, nvlist_t **onvl)
1212 {
1213 	nvlist_t *nvl;
1214 
1215 	nvl = nvlist_create(0);
1216 	if (nvl == NULL)
1217 		return (ENOMEM);
1218 
1219 	nvlist_add_number(nvl, "pending",
1220 	    buf_ring_count(sc->rxring) + buf_ring_count(sc->notifring));
1221 
1222 	*onvl = nvl;
1223 
1224 	return (0);
1225 }
1226 
1227 static int
1228 opvn_get_pkt(struct ovpn_softc *sc, nvlist_t **onvl)
1229 {
1230 	struct ovpn_notification *n;
1231 	struct ovpn_wire_header *ohdr;
1232 	struct mbuf *m;
1233 	uint8_t *buf;
1234 	nvlist_t *nvl;
1235 	uint32_t peerid;
1236 	u_int mlength;
1237 
1238 	/* Check if we have notifications pending. */
1239 	n = buf_ring_dequeue_mc(sc->notifring);
1240 	if (n != NULL) {
1241 		nvl = nvlist_create(0);
1242 		if (nvl == NULL) {
1243 			free(n, M_OVPN);
1244 			return (ENOMEM);
1245 		}
1246 		nvlist_add_number(nvl, "peerid", n->peerid);
1247 		nvlist_add_number(nvl, "notification", n->type);
1248 		free(n, M_OVPN);
1249 
1250 		*onvl = nvl;
1251 
1252 		return (0);
1253 	}
1254 
1255 	/* Queued packet. */
1256 	m = buf_ring_dequeue_mc(sc->rxring);
1257 	if (m == NULL)
1258 		return (ENOENT);
1259 
1260 	mlength = m_length(m, NULL);
1261 	buf = malloc(mlength, M_NVLIST, M_WAITOK);
1262 	m_copydata(m, 0, mlength, buf);
1263 	ohdr = (struct ovpn_wire_header *)buf;
1264 	peerid = ntohl(ohdr->opcode) & 0x00ffffff;
1265 
1266 	nvl = nvlist_create(0);
1267 	if (nvl == NULL) {
1268 		OVPN_COUNTER_ADD(sc, lost_ctrl_pkts_in, 1);
1269 		m_freem(m);
1270 		free(buf, M_NVLIST);
1271 		return (ENOMEM);
1272 	}
1273 
1274 	nvlist_move_binary(nvl, "packet", buf, mlength);
1275 	buf = NULL;
1276 	nvlist_add_number(nvl, "peerid", peerid);
1277 
1278 	*onvl = nvl;
1279 
1280 	m_freem(m);
1281 
1282 	return (0);
1283 }
1284 
1285 static int
1286 ovpn_ioctl_get(struct ifnet *ifp, struct ifdrv *ifd)
1287 {
1288 	struct ovpn_softc *sc = ifp->if_softc;
1289 	nvlist_t *nvl = NULL;
1290 	int error;
1291 
1292 	switch (ifd->ifd_cmd) {
1293 	case OVPN_GET_STATS:
1294 		error = ovpn_get_stats(sc, &nvl);
1295 		break;
1296 	case OVPN_POLL_PKT:
1297 		error = ovpn_poll_pkt(sc, &nvl);
1298 		break;
1299 	case OVPN_GET_PKT:
1300 		error = opvn_get_pkt(sc, &nvl);
1301 		break;
1302 	default:
1303 		error = ENOTSUP;
1304 		break;
1305 	}
1306 
1307 	if (error == 0) {
1308 		void *packed = NULL;
1309 		size_t len;
1310 
1311 		MPASS(nvl != NULL);
1312 
1313 		packed = nvlist_pack(nvl, &len);
1314 		if (! packed) {
1315 			nvlist_destroy(nvl);
1316 			return (ENOMEM);
1317 		}
1318 
1319 		if (len > ifd->ifd_len) {
1320 			free(packed, M_NVLIST);
1321 			nvlist_destroy(nvl);
1322 			return (ENOSPC);
1323 		}
1324 
1325 		error = copyout(packed, ifd->ifd_data, len);
1326 		ifd->ifd_len = len;
1327 
1328 		free(packed, M_NVLIST);
1329 		nvlist_destroy(nvl);
1330 	}
1331 
1332 	return (error);
1333 }
1334 
1335 static int
1336 ovpn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1337 {
1338 	struct ifdrv *ifd;
1339 	int error;
1340 
1341 	switch (cmd) {
1342 	case SIOCSDRVSPEC:
1343 	case SIOCGDRVSPEC:
1344 		error = priv_check(curthread, PRIV_NET_OVPN);
1345 		if (error)
1346 			return (error);
1347 		break;
1348 	}
1349 
1350 	switch (cmd) {
1351 	case SIOCSDRVSPEC:
1352 		ifd = (struct ifdrv *)data;
1353 		error = ovpn_ioctl_set(ifp, ifd);
1354 		break;
1355 	case SIOCGDRVSPEC:
1356 		ifd = (struct ifdrv *)data;
1357 		error = ovpn_ioctl_get(ifp, ifd);
1358 		break;
1359 	case SIOCSIFMTU: {
1360 		struct ifreq *ifr = (struct ifreq *)data;
1361 		if (ifr->ifr_mtu < OVPN_MTU_MIN || ifr->ifr_mtu > OVPN_MTU_MAX)
1362 			return (EINVAL);
1363 
1364 		ifp->if_mtu = ifr->ifr_mtu;
1365 		return (0);
1366 	}
1367 	case SIOCSIFADDR:
1368 	case SIOCADDMULTI:
1369 	case SIOCDELMULTI:
1370 	case SIOCGIFMTU:
1371 	case SIOCSIFFLAGS:
1372 		return (0);
1373 	default:
1374 		error = EINVAL;
1375 	}
1376 
1377 	return (error);
1378 }
1379 
1380 static int
1381 ovpn_encrypt_tx_cb(struct cryptop *crp)
1382 {
1383 	struct ovpn_kpeer *peer = crp->crp_opaque;
1384 	struct ovpn_softc *sc = peer->sc;
1385 	struct mbuf *m = crp->crp_buf.cb_mbuf;
1386 	int ret;
1387 
1388 	if (crp->crp_etype != 0) {
1389 		crypto_freereq(crp);
1390 		ovpn_peer_release_ref(peer, false);
1391 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
1392 		m_freem(m);
1393 		return (0);
1394 	}
1395 
1396 	CURVNET_SET(sc->ifp->if_vnet);
1397 
1398 	MPASS(crp->crp_buf.cb_type == CRYPTO_BUF_MBUF);
1399 
1400 	ret = ovpn_encap(sc, peer->peerid, m);
1401 	if (ret == 0) {
1402 		OVPN_COUNTER_ADD(sc, sent_data_pkts, 1);
1403 		OVPN_COUNTER_ADD(sc, tunnel_bytes_sent, m->m_pkthdr.len -
1404 		    sizeof(struct ovpn_wire_header));
1405 	}
1406 
1407 	CURVNET_RESTORE();
1408 
1409 	crypto_freereq(crp);
1410 	ovpn_peer_release_ref(peer, false);
1411 
1412 	return (0);
1413 }
1414 
1415 static void
1416 ovpn_finish_rx(struct ovpn_softc *sc, struct mbuf *m,
1417     struct ovpn_kpeer *peer, struct ovpn_kkey *key, uint32_t seq,
1418     struct rm_priotracker *_ovpn_lock_trackerp)
1419 {
1420 	uint32_t af;
1421 	int ret __diagused;
1422 
1423 	OVPN_RASSERT(sc);
1424 
1425 	/* Replay protection. */
1426 	if (V_replay_protection && ! ovpn_check_replay(key->decrypt, seq)) {
1427 		OVPN_RUNLOCK(sc);
1428 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
1429 		m_freem(m);
1430 		return;
1431 	}
1432 
1433 	critical_enter();
1434 	*zpcpu_get(peer->last_active) = time_uptime;
1435 	critical_exit();
1436 
1437 	OVPN_RUNLOCK(sc);
1438 
1439 	OVPN_COUNTER_ADD(sc, received_data_pkts, 1);
1440 	OVPN_COUNTER_ADD(sc, tunnel_bytes_received, m->m_pkthdr.len);
1441 
1442 	/* Receive the packet on our interface. */
1443 	m->m_pkthdr.rcvif = sc->ifp;
1444 
1445 	/* Clear checksum flags in case the real hardware set them. */
1446 	m->m_pkthdr.csum_flags = 0;
1447 
1448 	/* Ensure we can read the first byte. */
1449 	m = m_pullup(m, 1);
1450 	if (m == NULL) {
1451 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
1452 		return;
1453 	}
1454 
1455 	/*
1456 	 * Check for address family, and disregard any control packets (e.g.
1457 	 * keepalive).
1458 	 */
1459 	af = ovpn_get_af(m);
1460 	if (af != 0) {
1461 		BPF_MTAP2(sc->ifp, &af, sizeof(af), m);
1462 		ret = netisr_dispatch(af == AF_INET ? NETISR_IP : NETISR_IPV6,
1463 		    m);
1464 		MPASS(ret == 0);
1465 	} else {
1466 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
1467 		m_freem(m);
1468 	}
1469 }
1470 
1471 static struct ovpn_kkey *
1472 ovpn_find_key(struct ovpn_softc *sc, struct ovpn_kpeer *peer,
1473     const struct ovpn_wire_header *ohdr)
1474 {
1475 	struct ovpn_kkey *key = NULL;
1476 	uint8_t keyid;
1477 
1478 	OVPN_RASSERT(sc);
1479 
1480 	keyid = (ntohl(ohdr->opcode) >> 24) & 0x07;
1481 
1482 	if (peer->keys[0].keyid == keyid)
1483 		key = &peer->keys[0];
1484 	else if (peer->keys[1].keyid == keyid)
1485 		key = &peer->keys[1];
1486 
1487 	return (key);
1488 }
1489 
1490 static int
1491 ovpn_decrypt_rx_cb(struct cryptop *crp)
1492 {
1493 	struct ovpn_softc *sc = crp->crp_opaque;
1494 	struct mbuf *m = crp->crp_buf.cb_mbuf;
1495 	struct ovpn_kkey *key;
1496 	struct ovpn_kpeer *peer;
1497 	struct ovpn_wire_header *ohdr;
1498 	uint32_t peerid;
1499 
1500 	OVPN_RLOCK_TRACKER;
1501 
1502 	OVPN_RLOCK(sc);
1503 
1504 	MPASS(crp->crp_buf.cb_type == CRYPTO_BUF_MBUF);
1505 
1506 	if (crp->crp_etype != 0) {
1507 		crypto_freereq(crp);
1508 		atomic_add_int(&sc->refcount, -1);
1509 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
1510 		OVPN_RUNLOCK(sc);
1511 		m_freem(m);
1512 		return (0);
1513 	}
1514 
1515 	CURVNET_SET(sc->ifp->if_vnet);
1516 
1517 	ohdr = mtodo(m, sizeof(struct udphdr));
1518 
1519 	peerid = ntohl(ohdr->opcode) & 0x00ffffff;
1520 	peer = ovpn_find_peer(sc, peerid);
1521 	if (peer == NULL) {
1522 		/* No such peer. Drop packet. */
1523 		crypto_freereq(crp);
1524 		atomic_add_int(&sc->refcount, -1);
1525 		OVPN_RUNLOCK(sc);
1526 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
1527 		m_freem(m);
1528 		CURVNET_RESTORE();
1529 		return (0);
1530 	}
1531 
1532 	key = ovpn_find_key(sc, peer, ohdr);
1533 	if (key == NULL) {
1534 		crypto_freereq(crp);
1535 		atomic_add_int(&sc->refcount, -1);
1536 		/*
1537 		 * Has this key been removed between us starting the decrypt
1538 		 * and finishing it?
1539 		 */
1540 		OVPN_RUNLOCK(sc);
1541 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
1542 		m_freem(m);
1543 		CURVNET_RESTORE();
1544 		return (0);
1545 	}
1546 
1547 	/* Now remove the outer headers */
1548 	m_adj_decap(m, sizeof(struct udphdr) +
1549 	    sizeof(struct ovpn_wire_header));
1550 
1551 	ovpn_finish_rx(sc, m, peer, key, ntohl(ohdr->seq), _ovpn_lock_trackerp);
1552 	OVPN_UNLOCK_ASSERT(sc);
1553 
1554 	CURVNET_RESTORE();
1555 
1556 	crypto_freereq(crp);
1557 	atomic_add_int(&sc->refcount, -1);
1558 
1559 	return (0);
1560 }
1561 
1562 static uint8_t EMPTY_BUFFER[AES_BLOCK_LEN];
1563 
1564 static int
1565 ovpn_get_af(struct mbuf *m)
1566 {
1567 	struct ip *ip;
1568 	struct ip6_hdr *ip6;
1569 
1570 	/*
1571 	 * We should pullup, but we're only interested in the first byte, so
1572 	 * that'll always be contiguous.
1573 	 */
1574 	ip = mtod(m, struct ip *);
1575 	if (ip->ip_v == IPVERSION)
1576 		return (AF_INET);
1577 
1578 	ip6 = mtod(m, struct ip6_hdr *);
1579 	if (ip6->ip6_vfc == IPV6_VERSION)
1580 		return (AF_INET6);
1581 
1582 	return (0);
1583 }
1584 
1585 #ifdef INET
1586 static struct ovpn_kpeer *
1587 ovpn_find_peer_by_ip(struct ovpn_softc *sc, const struct in_addr addr)
1588 {
1589 	struct ovpn_kpeer *peer = NULL;
1590 
1591 	OVPN_ASSERT(sc);
1592 
1593 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
1594 		if (sc->peers[i] == NULL)
1595 			continue;
1596 		if (addr.s_addr == sc->peers[i]->vpn4.s_addr) {
1597 			peer = sc->peers[i];
1598 			break;
1599 		}
1600 	}
1601 
1602 	return (peer);
1603 }
1604 #endif
1605 
1606 #ifdef INET6
1607 static struct ovpn_kpeer *
1608 ovpn_find_peer_by_ip6(struct ovpn_softc *sc, const struct in6_addr *addr)
1609 {
1610 	struct ovpn_kpeer *peer = NULL;
1611 
1612 	OVPN_ASSERT(sc);
1613 
1614 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
1615 		if (sc->peers[i] == NULL)
1616 			continue;
1617 		if (memcmp(addr, &sc->peers[i]->vpn6, sizeof(*addr)) == 0) {
1618 			peer = sc->peers[i];
1619 			break;
1620 		}
1621 	}
1622 
1623 	return (peer);
1624 }
1625 #endif
1626 
1627 static struct ovpn_kpeer *
1628 ovpn_route_peer(struct ovpn_softc *sc, struct mbuf **m0,
1629     const struct sockaddr *dst)
1630 {
1631 	struct ovpn_kpeer *peer = NULL;
1632 	int af;
1633 
1634 	NET_EPOCH_ASSERT();
1635 	OVPN_ASSERT(sc);
1636 
1637 	/* Shortcut if we're a client (or are a server and have only one client). */
1638 	if (sc->peercount == 1)
1639 		return (ovpn_find_only_peer(sc));
1640 
1641 	if (dst != NULL)
1642 		af = dst->sa_family;
1643 	else
1644 		af = ovpn_get_af(*m0);
1645 
1646 	switch (af) {
1647 #ifdef INET
1648 	case AF_INET: {
1649 		const struct sockaddr_in *sa = (const struct sockaddr_in *)dst;
1650 		struct nhop_object *nh;
1651 		const struct in_addr *ip_dst;
1652 
1653 		if (sa != NULL) {
1654 			ip_dst = &sa->sin_addr;
1655 		} else {
1656 			struct ip *ip;
1657 
1658 			*m0 = m_pullup(*m0, sizeof(struct ip));
1659 			if (*m0 == NULL)
1660 				return (NULL);
1661 			ip = mtod(*m0, struct ip *);
1662 			ip_dst = &ip->ip_dst;
1663 		}
1664 
1665 		peer = ovpn_find_peer_by_ip(sc, *ip_dst);
1666 		SDT_PROBE2(if_ovpn, tx, route, ip4, ip_dst, peer);
1667 		if (peer == NULL) {
1668 			nh = fib4_lookup(M_GETFIB(*m0), *ip_dst, 0,
1669 			    NHR_NONE, 0);
1670 			if (nh && (nh->nh_flags & NHF_GATEWAY)) {
1671 				peer = ovpn_find_peer_by_ip(sc,
1672 				    nh->gw4_sa.sin_addr);
1673 				SDT_PROBE2(if_ovpn, tx, route, ip4,
1674 				    &nh->gw4_sa.sin_addr, peer);
1675 			}
1676 		}
1677 		break;
1678 	}
1679 #endif
1680 #ifdef INET6
1681 	case AF_INET6: {
1682 		const struct sockaddr_in6 *sa6 =
1683 		    (const struct sockaddr_in6 *)dst;
1684 		struct nhop_object *nh;
1685 		const struct in6_addr *ip6_dst;
1686 
1687 		if (sa6 != NULL) {
1688 			ip6_dst = &sa6->sin6_addr;
1689 		} else {
1690 			struct ip6_hdr *ip6;
1691 
1692 			*m0 = m_pullup(*m0, sizeof(struct ip6_hdr));
1693 			if (*m0 == NULL)
1694 				return (NULL);
1695 			ip6 = mtod(*m0, struct ip6_hdr *);
1696 			ip6_dst = &ip6->ip6_dst;
1697 		}
1698 
1699 		peer = ovpn_find_peer_by_ip6(sc, ip6_dst);
1700 		SDT_PROBE2(if_ovpn, tx, route, ip6, ip6_dst, peer);
1701 		if (peer == NULL) {
1702 			nh = fib6_lookup(M_GETFIB(*m0), ip6_dst, 0,
1703 			    NHR_NONE, 0);
1704 			if (nh && (nh->nh_flags & NHF_GATEWAY)) {
1705 				peer = ovpn_find_peer_by_ip6(sc,
1706 				    &nh->gw6_sa.sin6_addr);
1707 				SDT_PROBE2(if_ovpn, tx, route, ip6,
1708 				    &nh->gw6_sa.sin6_addr, peer);
1709 			}
1710 		}
1711 		break;
1712 	}
1713 #endif
1714 	}
1715 
1716 	return (peer);
1717 }
1718 
1719 static int
1720 ovpn_transmit(struct ifnet *ifp, struct mbuf *m)
1721 {
1722 	return (ifp->if_output(ifp, m, NULL, NULL));
1723 }
1724 
1725 static int
1726 ovpn_transmit_to_peer(struct ifnet *ifp, struct mbuf *m,
1727     struct ovpn_kpeer *peer, struct rm_priotracker *_ovpn_lock_trackerp)
1728 {
1729 	struct ovpn_wire_header *ohdr;
1730 	struct ovpn_kkey *key;
1731 	struct ovpn_softc *sc;
1732 	struct cryptop *crp;
1733 	uint32_t af, seq;
1734 	size_t len, real_len, ovpn_hdr_len;
1735 	int tunnel_len;
1736 	int ret;
1737 
1738 	sc = ifp->if_softc;
1739 
1740 	OVPN_RASSERT(sc);
1741 
1742 	tunnel_len = m->m_pkthdr.len;
1743 
1744 	key = &peer->keys[OVPN_KEY_SLOT_PRIMARY];
1745 	if (key->encrypt == NULL) {
1746 		if (_ovpn_lock_trackerp != NULL)
1747 			OVPN_RUNLOCK(sc);
1748 		m_freem(m);
1749 		return (ENOLINK);
1750 	}
1751 
1752 	af = ovpn_get_af(m);
1753 	/* Don't capture control packets. */
1754 	if (af != 0)
1755 		BPF_MTAP2(ifp, &af, sizeof(af), m);
1756 
1757 	real_len = len = m->m_pkthdr.len;
1758 	MPASS(real_len <= ifp->if_mtu);
1759 
1760 	ovpn_hdr_len = sizeof(struct ovpn_wire_header);
1761 	if (key->encrypt->cipher == OVPN_CIPHER_ALG_NONE)
1762 		ovpn_hdr_len -= 16; /* No auth tag. */
1763 	else {
1764 		/* Round up the len to a multiple of our block size. */
1765 		len = roundup2(real_len, AES_BLOCK_LEN);
1766 
1767 		/* Now extend the mbuf. */
1768 		m_append(m, len - real_len, EMPTY_BUFFER);
1769 	}
1770 
1771 	M_PREPEND(m, ovpn_hdr_len, M_NOWAIT);
1772 	if (m == NULL) {
1773 		if (_ovpn_lock_trackerp != NULL)
1774 			OVPN_RUNLOCK(sc);
1775 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1776 		return (ENOBUFS);
1777 	}
1778 	ohdr = mtod(m, struct ovpn_wire_header *);
1779 	ohdr->opcode = (OVPN_OP_DATA_V2 << OVPN_OP_SHIFT) | key->keyid;
1780 	ohdr->opcode <<= 24;
1781 	ohdr->opcode |= key->peerid;
1782 	ohdr->opcode = htonl(ohdr->opcode);
1783 
1784 	seq = atomic_fetchadd_32(&peer->tx_seq, 1);
1785 	seq = htonl(seq);
1786 	ohdr->seq = seq;
1787 
1788 	if (key->encrypt->cipher == OVPN_CIPHER_ALG_NONE) {
1789 		ret = ovpn_encap(sc, peer->peerid, m);
1790 		if (_ovpn_lock_trackerp != NULL)
1791 			OVPN_RUNLOCK(sc);
1792 		if (ret == 0) {
1793 			OVPN_COUNTER_ADD(sc, sent_data_pkts, 1);
1794 			OVPN_COUNTER_ADD(sc, tunnel_bytes_sent, tunnel_len);
1795 		}
1796 		return (ret);
1797 	}
1798 
1799 	crp = crypto_getreq(key->encrypt->cryptoid, M_NOWAIT);
1800 	if (crp == NULL) {
1801 		if (_ovpn_lock_trackerp != NULL)
1802 			OVPN_RUNLOCK(sc);
1803 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1804 		m_freem(m);
1805 		return (ENOBUFS);
1806 	}
1807 
1808 	/* Encryption covers only the payload, not the header. */
1809 	crp->crp_payload_start = sizeof(*ohdr);
1810 	crp->crp_payload_length = len;
1811 	crp->crp_op = CRYPTO_OP_ENCRYPT;
1812 
1813 	/*
1814 	 * AAD data covers the ovpn_wire_header minus the auth
1815 	 * tag.
1816 	 */
1817 	crp->crp_aad_length = sizeof(*ohdr) - sizeof(ohdr->auth_tag);
1818 	crp->crp_aad = ohdr;
1819 	crp->crp_aad_start = 0;
1820 	crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
1821 	crp->crp_digest_start = offsetof(struct ovpn_wire_header, auth_tag);
1822 
1823 	crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
1824 	memcpy(crp->crp_iv, &seq, sizeof(seq));
1825 	memcpy(crp->crp_iv + sizeof(seq), key->encrypt->nonce,
1826 	    key->encrypt->noncelen);
1827 
1828 	crypto_use_mbuf(crp, m);
1829 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
1830 	crp->crp_callback = ovpn_encrypt_tx_cb;
1831 	crp->crp_opaque = peer;
1832 
1833 	atomic_add_int(&peer->refcount, 1);
1834 	if (_ovpn_lock_trackerp != NULL)
1835 		OVPN_RUNLOCK(sc);
1836 	ret = crypto_dispatch(crp);
1837 	if (ret) {
1838 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
1839 	}
1840 
1841 	return (ret);
1842 }
1843 
1844 /*
1845  * Note: Expects to hold the read lock on entry, and will release it itself.
1846  */
1847 static int
1848 ovpn_encap(struct ovpn_softc *sc, uint32_t peerid, struct mbuf *m)
1849 {
1850 	struct udphdr *udp;
1851 	struct ovpn_kpeer *peer;
1852 	int len;
1853 
1854 	OVPN_RLOCK_TRACKER;
1855 
1856 	OVPN_RLOCK(sc);
1857 	NET_EPOCH_ASSERT();
1858 
1859 	peer = ovpn_find_peer(sc, peerid);
1860 	if (peer == NULL || sc->ifp->if_link_state != LINK_STATE_UP) {
1861 		OVPN_RUNLOCK(sc);
1862 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
1863 		m_freem(m);
1864 		return (ENETDOWN);
1865 	}
1866 
1867 	len = m->m_pkthdr.len;
1868 
1869 	M_PREPEND(m, sizeof(struct udphdr), M_NOWAIT);
1870 	if (m == NULL) {
1871 		OVPN_RUNLOCK(sc);
1872 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1873 		m_freem(m);
1874 		return (ENOBUFS);
1875 	}
1876 	udp = mtod(m, struct udphdr *);
1877 
1878 	MPASS(peer->local.ss_family == peer->remote.ss_family);
1879 
1880 	udp->uh_sport = ovpn_get_port(&peer->local);
1881 	udp->uh_dport = ovpn_get_port(&peer->remote);
1882 	udp->uh_ulen = htons(sizeof(struct udphdr) + len);
1883 
1884 	switch (peer->remote.ss_family) {
1885 #ifdef INET
1886 	case AF_INET: {
1887 		struct sockaddr_in *in_local = TO_IN(&peer->local);
1888 		struct sockaddr_in *in_remote = TO_IN(&peer->remote);
1889 		struct ip *ip;
1890 
1891 		/*
1892 		 * This requires knowing the source IP, which we don't. Happily
1893 		 * we're allowed to keep this at 0, and the checksum won't do
1894 		 * anything the crypto won't already do.
1895 		 */
1896 		udp->uh_sum = 0;
1897 
1898 		/* Set the checksum flags so we recalculate checksums. */
1899 		m->m_pkthdr.csum_flags |= CSUM_IP;
1900 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1901 
1902 		M_PREPEND(m, sizeof(struct ip), M_NOWAIT);
1903 		if (m == NULL) {
1904 			OVPN_RUNLOCK(sc);
1905 			OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1906 			return (ENOBUFS);
1907 		}
1908 		ip = mtod(m, struct ip *);
1909 
1910 		ip->ip_tos = 0;
1911 		ip->ip_len = htons(sizeof(struct ip) + sizeof(struct udphdr) +
1912 		   len);
1913 		ip->ip_off = 0;
1914 		ip->ip_ttl = V_ip_defttl;
1915 		ip->ip_p = IPPROTO_UDP;
1916 		ip->ip_sum = 0;
1917 		if (in_local->sin_port != 0)
1918 			ip->ip_src = in_local->sin_addr;
1919 		else
1920 			ip->ip_src.s_addr = INADDR_ANY;
1921 		ip->ip_dst = in_remote->sin_addr;
1922 
1923 		OVPN_RUNLOCK(sc);
1924 		OVPN_COUNTER_ADD(sc, transport_bytes_sent, m->m_pkthdr.len);
1925 
1926 		return (ip_output(m, NULL, NULL, 0, NULL, NULL));
1927 	}
1928 #endif
1929 #ifdef INET6
1930 	case AF_INET6: {
1931 		struct sockaddr_in6 *in6_local = TO_IN6(&peer->local);
1932 		struct sockaddr_in6 *in6_remote = TO_IN6(&peer->remote);
1933 		struct ip6_hdr *ip6;
1934 
1935 		M_PREPEND(m, sizeof(struct ip6_hdr), M_NOWAIT);
1936 		if (m == NULL) {
1937 			OVPN_RUNLOCK(sc);
1938 			OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1939 			return (ENOBUFS);
1940 		}
1941 		m = m_pullup(m, sizeof(*ip6) + sizeof(*udp));
1942 		if (m == NULL) {
1943 			OVPN_RUNLOCK(sc);
1944 			OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1945 			return (ENOBUFS);
1946 		}
1947 
1948 		ip6 = mtod(m, struct ip6_hdr *);
1949 
1950 		ip6->ip6_vfc = IPV6_VERSION;
1951 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
1952 		ip6->ip6_plen = htons(sizeof(*ip6) + sizeof(struct udphdr) +
1953 		    len);
1954 		ip6->ip6_nxt = IPPROTO_UDP;
1955 		ip6->ip6_hlim = V_ip6_defhlim;
1956 
1957 		memcpy(&ip6->ip6_src, &in6_local->sin6_addr,
1958 		    sizeof(ip6->ip6_src));
1959 		memcpy(&ip6->ip6_dst, &in6_remote->sin6_addr,
1960 		    sizeof(ip6->ip6_dst));
1961 
1962 		udp = mtodo(m, sizeof(*ip6));
1963 		udp->uh_sum = in6_cksum_pseudo(ip6,
1964 		    m->m_pkthdr.len - sizeof(struct ip6_hdr),
1965 		    IPPROTO_UDP, 0);
1966 
1967 		m->m_pkthdr.csum_flags |= CSUM_UDP_IPV6;
1968 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1969 
1970 		OVPN_RUNLOCK(sc);
1971 		OVPN_COUNTER_ADD(sc, transport_bytes_sent, m->m_pkthdr.len);
1972 
1973 		return (ip6_output(m, NULL, NULL, IPV6_UNSPECSRC, NULL, NULL,
1974 		    NULL));
1975 	}
1976 #endif
1977 	default:
1978 		panic("Unsupported address family %d",
1979 		    peer->remote.ss_family);
1980 	}
1981 }
1982 
1983 static int
1984 ovpn_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
1985 	struct route *ro)
1986 {
1987 	struct ovpn_softc *sc;
1988 	struct ovpn_kpeer *peer;
1989 
1990 	OVPN_RLOCK_TRACKER;
1991 
1992 	sc = ifp->if_softc;
1993 
1994 	OVPN_RLOCK(sc);
1995 
1996 	SDT_PROBE1(if_ovpn, tx, transmit, start, m);
1997 
1998 	if (__predict_false(ifp->if_link_state != LINK_STATE_UP)) {
1999 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
2000 		OVPN_RUNLOCK(sc);
2001 		m_freem(m);
2002 		return (ENETDOWN);
2003 	}
2004 
2005 	/**
2006 	 * Only obey 'dst' (i.e. the gateway) if no route is supplied.
2007 	 * That's our indication that we're being called through pf's route-to,
2008 	 * and we should route according to 'dst' instead. We can't do so
2009 	 * consistently, because the usual openvpn configuration sets the first
2010 	 * non-server IP in the subnet as the gateway. If we always use that
2011 	 * one we'd end up routing all traffic to the first client.
2012 	 * tl;dr: 'ro == NULL' tells us pf is doing a route-to, and then but
2013 	 * only then, we should treat 'dst' as the destination. */
2014 	peer = ovpn_route_peer(sc, &m, ro == NULL ? dst : NULL);
2015 	if (peer == NULL) {
2016 		/* No destination. */
2017 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
2018 		OVPN_RUNLOCK(sc);
2019 		m_freem(m);
2020 		return (ENETDOWN);
2021 	}
2022 
2023 	return (ovpn_transmit_to_peer(ifp, m, peer, _ovpn_lock_trackerp));
2024 }
2025 
2026 static void
2027 ovpn_rcv_ctrl(struct ovpn_softc *sc, struct mbuf *m, int off)
2028 {
2029 	/* Lop off the IP and UDP headers */
2030 	m_adj_decap(m, off);
2031 
2032 	/* Keep in the local ring until userspace fetches it. */
2033 	if (buf_ring_enqueue(sc->rxring, m) != 0) {
2034 		OVPN_COUNTER_ADD(sc, lost_ctrl_pkts_in, 1);
2035 		m_freem(m);
2036 		return;
2037 	}
2038 
2039 	OVPN_COUNTER_ADD(sc, received_ctrl_pkts, 1);
2040 }
2041 
2042 static bool
2043 ovpn_check_replay(struct ovpn_kkey_dir *key, uint32_t seq)
2044 {
2045 	uint32_t d;
2046 
2047 	mtx_lock(&key->replay_mtx);
2048 
2049 	/* Sequence number must be strictly greater than rx_seq */
2050 	if (seq <= key->rx_seq) {
2051 		mtx_unlock(&key->replay_mtx);
2052 		return (false);
2053 	}
2054 
2055 	/* Large jump. The packet authenticated okay, so just accept that. */
2056 	if (seq > (key->rx_seq + (sizeof(key->rx_window) * 8))) {
2057 		key->rx_seq = seq;
2058 		key->rx_window = 0;
2059 		mtx_unlock(&key->replay_mtx);
2060 		return (true);
2061 	}
2062 
2063 	/* Happy case. */
2064 	if ((seq == key->rx_seq + 1) && key->rx_window == 0) {
2065 		key->rx_seq++;
2066 		mtx_unlock(&key->replay_mtx);
2067 		return (true);
2068 	}
2069 
2070 	d = seq - key->rx_seq - 1;
2071 
2072 	if (key->rx_window & ((uint64_t)1 << d)) {
2073 		/* Dupe! */
2074 		mtx_unlock(&key->replay_mtx);
2075 		return (false);
2076 	}
2077 
2078 	key->rx_window |= (uint64_t)1 << d;
2079 
2080 	while (key->rx_window & 1) {
2081 		key->rx_seq++;
2082 		key->rx_window >>= 1;
2083 	}
2084 
2085 	mtx_unlock(&key->replay_mtx);
2086 
2087 	return (true);
2088 }
2089 
2090 static struct ovpn_kpeer *
2091 ovpn_peer_from_mbuf(struct ovpn_softc *sc, struct mbuf *m, int off)
2092 {
2093 	struct ovpn_wire_header ohdr;
2094 	uint32_t peerid;
2095 	const size_t hdrlen = sizeof(ohdr) - sizeof(ohdr.auth_tag);
2096 
2097 	OVPN_RASSERT(sc);
2098 
2099 	if (m_length(m, NULL) < (off + sizeof(struct udphdr) + hdrlen))
2100 		return (NULL);
2101 
2102 	m_copydata(m, off + sizeof(struct udphdr), hdrlen, (caddr_t)&ohdr);
2103 
2104 	peerid = ntohl(ohdr.opcode) & 0x00ffffff;
2105 
2106 	return (ovpn_find_peer(sc, peerid));
2107 }
2108 
2109 static bool
2110 ovpn_udp_input(struct mbuf *m, int off, struct inpcb *inp,
2111     const struct sockaddr *sa, void *ctx)
2112 {
2113 	struct ovpn_softc *sc = ctx;
2114 	struct ovpn_wire_header *ohdr;
2115 	struct udphdr *uhdr;
2116 	struct ovpn_kkey *key;
2117 	struct cryptop *crp;
2118 	struct ovpn_kpeer *peer;
2119 	size_t ohdrlen;
2120 	int ret;
2121 	uint8_t op;
2122 
2123 	OVPN_RLOCK_TRACKER;
2124 
2125 	M_ASSERTPKTHDR(m);
2126 
2127 	OVPN_COUNTER_ADD(sc, transport_bytes_received, m->m_pkthdr.len - off);
2128 
2129 	ohdrlen = sizeof(*ohdr) - sizeof(ohdr->auth_tag);
2130 
2131 	OVPN_RLOCK(sc);
2132 
2133 	peer = ovpn_peer_from_mbuf(sc, m, off);
2134 	if (peer == NULL) {
2135 		OVPN_RUNLOCK(sc);
2136 		return (false);
2137 	}
2138 
2139 	m = m_pullup(m, off + sizeof(*uhdr) + ohdrlen);
2140 	if (m == NULL) {
2141 		OVPN_RUNLOCK(sc);
2142 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
2143 		return (true);
2144 	}
2145 	uhdr = mtodo(m, off);
2146 	ohdr = mtodo(m, off + sizeof(*uhdr));
2147 
2148 	op = ntohl(ohdr->opcode) >> 24 >> OVPN_OP_SHIFT;
2149 
2150 	/*
2151 	 * Simplify things by getting rid of the preceding headers, we don't
2152 	 * care about them.
2153 	 */
2154 	m_adj_decap(m, off);
2155 
2156 	uhdr = mtodo(m, 0);
2157 	ohdr = mtodo(m, sizeof(*uhdr));
2158 
2159 	if (op != OVPN_OP_DATA_V2) {
2160 		OVPN_RUNLOCK(sc);
2161 		ovpn_rcv_ctrl(sc, m, sizeof(struct udphdr));
2162 		INP_WLOCK(inp);
2163 		udp_notify(inp, EAGAIN);
2164 		INP_WUNLOCK(inp);
2165 		return (true);
2166 	}
2167 
2168 	key = ovpn_find_key(sc, peer, ohdr);
2169 	if (key == NULL || key->decrypt == NULL) {
2170 		OVPN_RUNLOCK(sc);
2171 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
2172 		m_freem(m);
2173 		return (true);
2174 	}
2175 
2176 	if (key->decrypt->cipher == OVPN_CIPHER_ALG_NONE) {
2177 		/* Now remove the outer headers */
2178 		m_adj_decap(m, sizeof(struct udphdr) + ohdrlen);
2179 
2180 		ohdr = mtodo(m, sizeof(*uhdr));
2181 
2182 		ovpn_finish_rx(sc, m, peer, key, ntohl(ohdr->seq),
2183 		    _ovpn_lock_trackerp);
2184 		OVPN_UNLOCK_ASSERT(sc);
2185 		return (true);
2186 	}
2187 
2188 	ohdrlen += sizeof(ohdr->auth_tag);
2189 
2190 	m = m_pullup(m, sizeof(*uhdr) + ohdrlen);
2191 	if (m == NULL) {
2192 		OVPN_RUNLOCK(sc);
2193 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
2194 		return (true);
2195 	}
2196 	uhdr = mtodo(m, 0);
2197 	ohdr = mtodo(m, sizeof(*uhdr));
2198 
2199 	/* Decrypt */
2200 	crp = crypto_getreq(key->decrypt->cryptoid, M_NOWAIT);
2201 	if (crp == NULL) {
2202 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
2203 		OVPN_RUNLOCK(sc);
2204 		m_freem(m);
2205 		return (true);
2206 	}
2207 
2208 	crp->crp_payload_start = sizeof(struct udphdr) + sizeof(*ohdr);
2209 	crp->crp_payload_length = ntohs(uhdr->uh_ulen) -
2210 	    sizeof(*uhdr) - sizeof(*ohdr);
2211 	crp->crp_op = CRYPTO_OP_DECRYPT;
2212 
2213 	/* AAD validation. */
2214 	crp->crp_aad_length = sizeof(*ohdr) - sizeof(ohdr->auth_tag);
2215 	crp->crp_aad = ohdr;
2216 	crp->crp_aad_start = 0;
2217 	crp->crp_op |= CRYPTO_OP_VERIFY_DIGEST;
2218 	crp->crp_digest_start = sizeof(struct udphdr) +
2219 	    offsetof(struct ovpn_wire_header, auth_tag);
2220 
2221 	crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
2222 	memcpy(crp->crp_iv, &ohdr->seq, sizeof(ohdr->seq));
2223 	memcpy(crp->crp_iv + sizeof(ohdr->seq), key->decrypt->nonce,
2224 	    key->decrypt->noncelen);
2225 
2226 	crypto_use_mbuf(crp, m);
2227 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
2228 	crp->crp_callback = ovpn_decrypt_rx_cb;
2229 	crp->crp_opaque = sc;
2230 
2231 	atomic_add_int(&sc->refcount, 1);
2232 	OVPN_RUNLOCK(sc);
2233 	ret = crypto_dispatch(crp);
2234 	if (ret != 0) {
2235 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
2236 	}
2237 
2238 	return (true);
2239 }
2240 
2241 static void
2242 ovpn_qflush(struct ifnet *ifp __unused)
2243 {
2244 
2245 }
2246 
2247 static void
2248 ovpn_flush_rxring(struct ovpn_softc *sc)
2249 {
2250 	struct mbuf *m;
2251 	struct ovpn_notification *n;
2252 
2253 	OVPN_WASSERT(sc);
2254 
2255 	while (! buf_ring_empty(sc->rxring)) {
2256 		m = buf_ring_dequeue_sc(sc->rxring);
2257 		m_freem(m);
2258 	}
2259 
2260 	while (! buf_ring_empty(sc->notifring)) {
2261 		n = buf_ring_dequeue_sc(sc->notifring);
2262 		free(n, M_OVPN);
2263 	}
2264 }
2265 
2266 #ifdef VIMAGE
2267 static void
2268 ovpn_reassign(struct ifnet *ifp, struct vnet *new_vnet __unused,
2269     char *unused __unused)
2270 {
2271 	struct ovpn_softc *sc = ifp->if_softc;
2272 	int i;
2273 	int ret __diagused;
2274 
2275 	i = 0;
2276 
2277 	OVPN_WLOCK(sc);
2278 
2279 	/* Flush keys & configuration. */
2280 	do {
2281 		if (sc->peers[i] != NULL) {
2282 			ret = _ovpn_del_peer(sc, sc->peers[i]->peerid);
2283 			MPASS(ret == 0);
2284 		}
2285 		i++;
2286 	} while (i < OVPN_MAX_PEERS);
2287 
2288 	ovpn_flush_rxring(sc);
2289 
2290 	OVPN_WUNLOCK(sc);
2291 }
2292 #endif
2293 
2294 static int
2295 ovpn_clone_match(struct if_clone *ifc, const char *name)
2296 {
2297 	/*
2298 	 * Allow all names that start with 'ovpn', specifically because pfSense
2299 	 * uses ovpnc1 / ovpns2
2300 	 */
2301 	return (strncmp(ovpnname, name, strlen(ovpnname)) == 0);
2302 }
2303 
2304 static int
2305 ovpn_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
2306 {
2307 	struct ovpn_softc *sc;
2308 	struct ifnet *ifp;
2309 	char *dp;
2310 	int error, unit, wildcard;
2311 
2312 	/* Try to see if a special unit was requested. */
2313 	error = ifc_name2unit(name, &unit);
2314 	if (error != 0)
2315 		return (error);
2316 	wildcard = (unit < 0);
2317 
2318 	error = ifc_alloc_unit(ifc, &unit);
2319 	if (error != 0)
2320 		return (error);
2321 
2322 	/*
2323 	 * If no unit had been given, we need to adjust the ifName.
2324 	 */
2325 	for (dp = name; *dp != '\0'; dp++);
2326 	if (wildcard) {
2327 		error = snprintf(dp, len - (dp - name), "%d", unit);
2328 		if (error > len - (dp - name)) {
2329 			/* ifName too long. */
2330 			ifc_free_unit(ifc, unit);
2331 			return (ENOSPC);
2332 		}
2333 		dp += error;
2334 	}
2335 
2336 	/* Make sure it doesn't already exist. */
2337 	if (ifunit(name) != NULL)
2338 		return (EEXIST);
2339 
2340 	sc = malloc(sizeof(struct ovpn_softc), M_OVPN, M_WAITOK | M_ZERO);
2341 	sc->ifp = if_alloc(IFT_ENC);
2342 	rm_init_flags(&sc->lock, "if_ovpn_lock", RM_RECURSE);
2343 	sc->refcount = 0;
2344 
2345 	sc->rxring = buf_ring_alloc(32, M_OVPN, M_WAITOK, NULL);
2346 	sc->notifring = buf_ring_alloc(32, M_OVPN, M_WAITOK, NULL);
2347 
2348 	COUNTER_ARRAY_ALLOC(sc->counters, OVPN_COUNTER_SIZE, M_WAITOK);
2349 
2350 	ifp = sc->ifp;
2351 	ifp->if_softc = sc;
2352 	strlcpy(ifp->if_xname, name, IFNAMSIZ);
2353 	ifp->if_dname = ovpngroupname;
2354 	ifp->if_dunit = unit;
2355 
2356 	ifp->if_addrlen = 0;
2357 	ifp->if_mtu = 1428;
2358 	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
2359 	ifp->if_ioctl = ovpn_ioctl;
2360 	ifp->if_transmit = ovpn_transmit;
2361 	ifp->if_output = ovpn_output;
2362 	ifp->if_qflush = ovpn_qflush;
2363 #ifdef VIMAGE
2364 	ifp->if_reassign = ovpn_reassign;
2365 #endif
2366 	ifp->if_capabilities |= IFCAP_LINKSTATE;
2367 	ifp->if_capenable |= IFCAP_LINKSTATE;
2368 
2369 	if_attach(ifp);
2370 	bpfattach(ifp, DLT_NULL, sizeof(uint32_t));
2371 
2372 	return (0);
2373 }
2374 
2375 static void
2376 ovpn_clone_destroy_cb(struct epoch_context *ctx)
2377 {
2378 	struct ovpn_softc *sc;
2379 
2380 	sc = __containerof(ctx, struct ovpn_softc, epoch_ctx);
2381 
2382 	MPASS(sc->peercount == 0);
2383 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
2384 		MPASS(sc->peers[i] == NULL);
2385 	}
2386 
2387 	COUNTER_ARRAY_FREE(sc->counters, OVPN_COUNTER_SIZE);
2388 
2389 	if_free(sc->ifp);
2390 	free(sc, M_OVPN);
2391 }
2392 
2393 static int
2394 ovpn_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
2395 {
2396 	struct ovpn_softc *sc;
2397 	int unit;
2398 	int i;
2399 	int ret __diagused;
2400 
2401 	sc = ifp->if_softc;
2402 	unit = ifp->if_dunit;
2403 
2404 	OVPN_WLOCK(sc);
2405 
2406 	if (atomic_load_int(&sc->refcount) > 0) {
2407 		OVPN_WUNLOCK(sc);
2408 		return (EBUSY);
2409 	}
2410 
2411 	i = 0;
2412 	do {
2413 		if (sc->peers[i] != NULL) {
2414 			ret = _ovpn_del_peer(sc, sc->peers[i]->peerid);
2415 			MPASS(ret == 0);
2416 		}
2417 		i++;
2418 	} while (i < OVPN_MAX_PEERS);
2419 
2420 	ovpn_flush_rxring(sc);
2421 	buf_ring_free(sc->rxring, M_OVPN);
2422 	buf_ring_free(sc->notifring, M_OVPN);
2423 
2424 	OVPN_WUNLOCK(sc);
2425 
2426 	bpfdetach(ifp);
2427 	if_detach(ifp);
2428 	ifp->if_softc = NULL;
2429 
2430 	NET_EPOCH_CALL(ovpn_clone_destroy_cb, &sc->epoch_ctx);
2431 
2432 	if (unit != IF_DUNIT_NONE)
2433 		ifc_free_unit(ifc, unit);
2434 
2435 	return (0);
2436 }
2437 
2438 static void
2439 vnet_ovpn_init(const void *unused __unused)
2440 {
2441 	V_ovpn_cloner = if_clone_advanced(ovpngroupname, 0, ovpn_clone_match,
2442 	    ovpn_clone_create, ovpn_clone_destroy);
2443 }
2444 VNET_SYSINIT(vnet_ovpn_init, SI_SUB_PSEUDO, SI_ORDER_ANY,
2445     vnet_ovpn_init, NULL);
2446 
2447 static void
2448 vnet_ovpn_uninit(const void *unused __unused)
2449 {
2450 	if_clone_detach(V_ovpn_cloner);
2451 }
2452 VNET_SYSUNINIT(vnet_ovpn_uninit, SI_SUB_PSEUDO, SI_ORDER_ANY,
2453     vnet_ovpn_uninit, NULL);
2454 
2455 static int
2456 ovpnmodevent(module_t mod, int type, void *data)
2457 {
2458 	switch (type) {
2459 	case MOD_LOAD:
2460 		/* Done in vnet_ovpn_init() */
2461 		break;
2462 	case MOD_UNLOAD:
2463 		/* Done in vnet_ovpn_uninit() */
2464 		break;
2465 	default:
2466 		return (EOPNOTSUPP);
2467 	}
2468 
2469 	return (0);
2470 }
2471 
2472 static moduledata_t ovpn_mod = {
2473 	"if_ovpn",
2474 	ovpnmodevent,
2475 	0
2476 };
2477 
2478 DECLARE_MODULE(if_ovpn, ovpn_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
2479 MODULE_VERSION(if_ovpn, 1);
2480