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