xref: /freebsd/sys/net/if_ovpn.c (revision c7046f76)
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 uint8_t EMPTY_BUFFER[AES_BLOCK_LEN];
1561 
1562 static int
1563 ovpn_get_af(struct mbuf *m)
1564 {
1565 	struct ip *ip;
1566 	struct ip6_hdr *ip6;
1567 
1568 	/*
1569 	 * We should pullup, but we're only interested in the first byte, so
1570 	 * that'll always be contiguous.
1571 	 */
1572 	ip = mtod(m, struct ip *);
1573 	if (ip->ip_v == IPVERSION)
1574 		return (AF_INET);
1575 
1576 	ip6 = mtod(m, struct ip6_hdr *);
1577 	if (ip6->ip6_vfc == IPV6_VERSION)
1578 		return (AF_INET6);
1579 
1580 	return (0);
1581 }
1582 
1583 #ifdef INET
1584 static struct ovpn_kpeer *
1585 ovpn_find_peer_by_ip(struct ovpn_softc *sc, const struct in_addr addr)
1586 {
1587 	struct ovpn_kpeer *peer = NULL;
1588 
1589 	OVPN_ASSERT(sc);
1590 
1591 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
1592 		if (sc->peers[i] == NULL)
1593 			continue;
1594 		if (addr.s_addr == sc->peers[i]->vpn4.s_addr) {
1595 			peer = sc->peers[i];
1596 			break;
1597 		}
1598 	}
1599 
1600 	return (peer);
1601 }
1602 #endif
1603 
1604 #ifdef INET6
1605 static struct ovpn_kpeer *
1606 ovpn_find_peer_by_ip6(struct ovpn_softc *sc, const struct in6_addr *addr)
1607 {
1608 	struct ovpn_kpeer *peer = NULL;
1609 
1610 	OVPN_ASSERT(sc);
1611 
1612 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
1613 		if (sc->peers[i] == NULL)
1614 			continue;
1615 		if (memcmp(addr, &sc->peers[i]->vpn6, sizeof(*addr)) == 0) {
1616 			peer = sc->peers[i];
1617 			break;
1618 		}
1619 	}
1620 
1621 	return (peer);
1622 }
1623 #endif
1624 
1625 static struct ovpn_kpeer *
1626 ovpn_route_peer(struct ovpn_softc *sc, struct mbuf **m0,
1627     const struct sockaddr *dst)
1628 {
1629 	struct ovpn_kpeer *peer = NULL;
1630 	int af;
1631 
1632 	NET_EPOCH_ASSERT();
1633 	OVPN_ASSERT(sc);
1634 
1635 	/* Shortcut if we're a client (or are a server and have only one client). */
1636 	if (sc->peercount == 1)
1637 		return (ovpn_find_only_peer(sc));
1638 
1639 	if (dst != NULL)
1640 		af = dst->sa_family;
1641 	else
1642 		af = ovpn_get_af(*m0);
1643 
1644 	switch (af) {
1645 #ifdef INET
1646 	case AF_INET: {
1647 		const struct sockaddr_in *sa = (const struct sockaddr_in *)dst;
1648 		struct nhop_object *nh;
1649 		const struct in_addr *ip_dst;
1650 
1651 		if (sa != NULL) {
1652 			ip_dst = &sa->sin_addr;
1653 		} else {
1654 			struct ip *ip;
1655 
1656 			*m0 = m_pullup(*m0, sizeof(struct ip));
1657 			if (*m0 == NULL)
1658 				return (NULL);
1659 			ip = mtod(*m0, struct ip *);
1660 			ip_dst = &ip->ip_dst;
1661 		}
1662 
1663 		peer = ovpn_find_peer_by_ip(sc, *ip_dst);
1664 		SDT_PROBE2(if_ovpn, tx, route, ip4, ip_dst, peer);
1665 		if (peer == NULL) {
1666 			nh = fib4_lookup(M_GETFIB(*m0), *ip_dst, 0,
1667 			    NHR_NONE, 0);
1668 			if (nh && (nh->nh_flags & NHF_GATEWAY)) {
1669 				peer = ovpn_find_peer_by_ip(sc,
1670 				    nh->gw4_sa.sin_addr);
1671 				SDT_PROBE2(if_ovpn, tx, route, ip4,
1672 				    &nh->gw4_sa.sin_addr, peer);
1673 			}
1674 		}
1675 		break;
1676 	}
1677 #endif
1678 #ifdef INET6
1679 	case AF_INET6: {
1680 		const struct sockaddr_in6 *sa6 =
1681 		    (const struct sockaddr_in6 *)dst;
1682 		struct nhop_object *nh;
1683 		const struct in6_addr *ip6_dst;
1684 
1685 		if (sa6 != NULL) {
1686 			ip6_dst = &sa6->sin6_addr;
1687 		} else {
1688 			struct ip6_hdr *ip6;
1689 
1690 			*m0 = m_pullup(*m0, sizeof(struct ip6_hdr));
1691 			if (*m0 == NULL)
1692 				return (NULL);
1693 			ip6 = mtod(*m0, struct ip6_hdr *);
1694 			ip6_dst = &ip6->ip6_dst;
1695 		}
1696 
1697 		peer = ovpn_find_peer_by_ip6(sc, ip6_dst);
1698 		SDT_PROBE2(if_ovpn, tx, route, ip6, ip6_dst, peer);
1699 		if (peer == NULL) {
1700 			nh = fib6_lookup(M_GETFIB(*m0), ip6_dst, 0,
1701 			    NHR_NONE, 0);
1702 			if (nh && (nh->nh_flags & NHF_GATEWAY)) {
1703 				peer = ovpn_find_peer_by_ip6(sc,
1704 				    &nh->gw6_sa.sin6_addr);
1705 				SDT_PROBE2(if_ovpn, tx, route, ip6,
1706 				    &nh->gw6_sa.sin6_addr, peer);
1707 			}
1708 		}
1709 		break;
1710 	}
1711 #endif
1712 	}
1713 
1714 	return (peer);
1715 }
1716 
1717 static int
1718 ovpn_transmit(struct ifnet *ifp, struct mbuf *m)
1719 {
1720 	return (ifp->if_output(ifp, m, NULL, NULL));
1721 }
1722 
1723 static int
1724 ovpn_transmit_to_peer(struct ifnet *ifp, struct mbuf *m,
1725     struct ovpn_kpeer *peer, struct rm_priotracker *_ovpn_lock_trackerp)
1726 {
1727 	struct ovpn_wire_header *ohdr;
1728 	struct ovpn_kkey *key;
1729 	struct ovpn_softc *sc;
1730 	struct cryptop *crp;
1731 	uint32_t af, seq;
1732 	size_t len, real_len, ovpn_hdr_len;
1733 	int tunnel_len;
1734 	int ret;
1735 
1736 	sc = ifp->if_softc;
1737 
1738 	OVPN_RASSERT(sc);
1739 
1740 	tunnel_len = m->m_pkthdr.len;
1741 
1742 	key = &peer->keys[OVPN_KEY_SLOT_PRIMARY];
1743 	if (key->encrypt == NULL) {
1744 		if (_ovpn_lock_trackerp != NULL)
1745 			OVPN_RUNLOCK(sc);
1746 		m_freem(m);
1747 		return (ENOLINK);
1748 	}
1749 
1750 	af = ovpn_get_af(m);
1751 	/* Don't capture control packets. */
1752 	if (af != 0)
1753 		BPF_MTAP2(ifp, &af, sizeof(af), m);
1754 
1755 	real_len = len = m->m_pkthdr.len;
1756 	MPASS(real_len <= ifp->if_mtu);
1757 
1758 	ovpn_hdr_len = sizeof(struct ovpn_wire_header);
1759 	if (key->encrypt->cipher == OVPN_CIPHER_ALG_NONE)
1760 		ovpn_hdr_len -= 16; /* No auth tag. */
1761 	else {
1762 		/* Round up the len to a multiple of our block size. */
1763 		len = roundup2(real_len, AES_BLOCK_LEN);
1764 
1765 		/* Now extend the mbuf. */
1766 		m_append(m, len - real_len, EMPTY_BUFFER);
1767 	}
1768 
1769 	M_PREPEND(m, ovpn_hdr_len, M_NOWAIT);
1770 	if (m == NULL) {
1771 		if (_ovpn_lock_trackerp != NULL)
1772 			OVPN_RUNLOCK(sc);
1773 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1774 		return (ENOBUFS);
1775 	}
1776 	ohdr = mtod(m, struct ovpn_wire_header *);
1777 	ohdr->opcode = (OVPN_OP_DATA_V2 << OVPN_OP_SHIFT) | key->keyid;
1778 	ohdr->opcode <<= 24;
1779 	ohdr->opcode |= key->peerid;
1780 	ohdr->opcode = htonl(ohdr->opcode);
1781 
1782 	seq = atomic_fetchadd_32(&peer->tx_seq, 1);
1783 	seq = htonl(seq);
1784 	ohdr->seq = seq;
1785 
1786 	if (key->encrypt->cipher == OVPN_CIPHER_ALG_NONE) {
1787 		ret = ovpn_encap(sc, peer->peerid, m);
1788 		if (_ovpn_lock_trackerp != NULL)
1789 			OVPN_RUNLOCK(sc);
1790 		if (ret == 0) {
1791 			OVPN_COUNTER_ADD(sc, sent_data_pkts, 1);
1792 			OVPN_COUNTER_ADD(sc, tunnel_bytes_sent, tunnel_len);
1793 		}
1794 		return (ret);
1795 	}
1796 
1797 	crp = crypto_getreq(key->encrypt->cryptoid, M_NOWAIT);
1798 	if (crp == NULL) {
1799 		if (_ovpn_lock_trackerp != NULL)
1800 			OVPN_RUNLOCK(sc);
1801 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1802 		m_freem(m);
1803 		return (ENOBUFS);
1804 	}
1805 
1806 	/* Encryption covers only the payload, not the header. */
1807 	crp->crp_payload_start = sizeof(*ohdr);
1808 	crp->crp_payload_length = len;
1809 	crp->crp_op = CRYPTO_OP_ENCRYPT;
1810 
1811 	/*
1812 	 * AAD data covers the ovpn_wire_header minus the auth
1813 	 * tag.
1814 	 */
1815 	crp->crp_aad_length = sizeof(*ohdr) - sizeof(ohdr->auth_tag);
1816 	crp->crp_aad = ohdr;
1817 	crp->crp_aad_start = 0;
1818 	crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
1819 	crp->crp_digest_start = offsetof(struct ovpn_wire_header, auth_tag);
1820 
1821 	crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
1822 	memcpy(crp->crp_iv, &seq, sizeof(seq));
1823 	memcpy(crp->crp_iv + sizeof(seq), key->encrypt->nonce,
1824 	    key->encrypt->noncelen);
1825 
1826 	crypto_use_mbuf(crp, m);
1827 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
1828 	crp->crp_callback = ovpn_encrypt_tx_cb;
1829 	crp->crp_opaque = peer;
1830 
1831 	atomic_add_int(&peer->refcount, 1);
1832 	if (_ovpn_lock_trackerp != NULL)
1833 		OVPN_RUNLOCK(sc);
1834 	ret = crypto_dispatch(crp);
1835 	if (ret) {
1836 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
1837 	}
1838 
1839 	return (ret);
1840 }
1841 
1842 /*
1843  * Note: Expects to hold the read lock on entry, and will release it itself.
1844  */
1845 static int
1846 ovpn_encap(struct ovpn_softc *sc, uint32_t peerid, struct mbuf *m)
1847 {
1848 	struct udphdr *udp;
1849 	struct ovpn_kpeer *peer;
1850 	int len;
1851 
1852 	OVPN_RLOCK_TRACKER;
1853 
1854 	OVPN_RLOCK(sc);
1855 	NET_EPOCH_ASSERT();
1856 
1857 	peer = ovpn_find_peer(sc, peerid);
1858 	if (peer == NULL || sc->ifp->if_link_state != LINK_STATE_UP) {
1859 		OVPN_RUNLOCK(sc);
1860 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
1861 		m_freem(m);
1862 		return (ENETDOWN);
1863 	}
1864 
1865 	len = m->m_pkthdr.len;
1866 
1867 	M_PREPEND(m, sizeof(struct udphdr), M_NOWAIT);
1868 	if (m == NULL) {
1869 		OVPN_RUNLOCK(sc);
1870 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1871 		m_freem(m);
1872 		return (ENOBUFS);
1873 	}
1874 	udp = mtod(m, struct udphdr *);
1875 
1876 	MPASS(peer->local.ss_family == peer->remote.ss_family);
1877 
1878 	udp->uh_sport = ovpn_get_port(&peer->local);
1879 	udp->uh_dport = ovpn_get_port(&peer->remote);
1880 	udp->uh_ulen = htons(sizeof(struct udphdr) + len);
1881 
1882 	switch (peer->remote.ss_family) {
1883 #ifdef INET
1884 	case AF_INET: {
1885 		struct sockaddr_in *in_local = TO_IN(&peer->local);
1886 		struct sockaddr_in *in_remote = TO_IN(&peer->remote);
1887 		struct ip *ip;
1888 
1889 		/*
1890 		 * This requires knowing the source IP, which we don't. Happily
1891 		 * we're allowed to keep this at 0, and the checksum won't do
1892 		 * anything the crypto won't already do.
1893 		 */
1894 		udp->uh_sum = 0;
1895 
1896 		/* Set the checksum flags so we recalculate checksums. */
1897 		m->m_pkthdr.csum_flags |= CSUM_IP;
1898 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1899 
1900 		M_PREPEND(m, sizeof(struct ip), M_NOWAIT);
1901 		if (m == NULL) {
1902 			OVPN_RUNLOCK(sc);
1903 			OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1904 			return (ENOBUFS);
1905 		}
1906 		ip = mtod(m, struct ip *);
1907 
1908 		ip->ip_tos = 0;
1909 		ip->ip_len = htons(sizeof(struct ip) + sizeof(struct udphdr) +
1910 		   len);
1911 		ip->ip_off = 0;
1912 		ip->ip_ttl = V_ip_defttl;
1913 		ip->ip_p = IPPROTO_UDP;
1914 		ip->ip_sum = 0;
1915 		if (in_local->sin_port != 0)
1916 			ip->ip_src = in_local->sin_addr;
1917 		else
1918 			ip->ip_src.s_addr = INADDR_ANY;
1919 		ip->ip_dst = in_remote->sin_addr;
1920 
1921 		OVPN_RUNLOCK(sc);
1922 		OVPN_COUNTER_ADD(sc, transport_bytes_sent, m->m_pkthdr.len);
1923 
1924 		return (ip_output(m, NULL, NULL, 0, NULL, NULL));
1925 	}
1926 #endif
1927 #ifdef INET6
1928 	case AF_INET6: {
1929 		struct sockaddr_in6 *in6_local = TO_IN6(&peer->local);
1930 		struct sockaddr_in6 *in6_remote = TO_IN6(&peer->remote);
1931 		struct ip6_hdr *ip6;
1932 
1933 		M_PREPEND(m, sizeof(struct ip6_hdr), M_NOWAIT);
1934 		if (m == NULL) {
1935 			OVPN_RUNLOCK(sc);
1936 			OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1937 			return (ENOBUFS);
1938 		}
1939 		m = m_pullup(m, sizeof(*ip6) + sizeof(*udp));
1940 		if (m == NULL) {
1941 			OVPN_RUNLOCK(sc);
1942 			OVPN_COUNTER_ADD(sc, nomem_data_pkts_out, 1);
1943 			return (ENOBUFS);
1944 		}
1945 
1946 		ip6 = mtod(m, struct ip6_hdr *);
1947 
1948 		ip6->ip6_vfc = IPV6_VERSION;
1949 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
1950 		ip6->ip6_plen = htons(sizeof(*ip6) + sizeof(struct udphdr) +
1951 		    len);
1952 		ip6->ip6_nxt = IPPROTO_UDP;
1953 		ip6->ip6_hlim = V_ip6_defhlim;
1954 
1955 		memcpy(&ip6->ip6_src, &in6_local->sin6_addr,
1956 		    sizeof(ip6->ip6_src));
1957 		memcpy(&ip6->ip6_dst, &in6_remote->sin6_addr,
1958 		    sizeof(ip6->ip6_dst));
1959 
1960 		udp = mtodo(m, sizeof(*ip6));
1961 		udp->uh_sum = in6_cksum_pseudo(ip6,
1962 		    m->m_pkthdr.len - sizeof(struct ip6_hdr),
1963 		    IPPROTO_UDP, 0);
1964 
1965 		m->m_pkthdr.csum_flags |= CSUM_UDP_IPV6;
1966 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1967 
1968 		OVPN_RUNLOCK(sc);
1969 		OVPN_COUNTER_ADD(sc, transport_bytes_sent, m->m_pkthdr.len);
1970 
1971 		return (ip6_output(m, NULL, NULL, IPV6_UNSPECSRC, NULL, NULL,
1972 		    NULL));
1973 	}
1974 #endif
1975 	default:
1976 		panic("Unsupported address family %d",
1977 		    peer->remote.ss_family);
1978 	}
1979 }
1980 
1981 static int
1982 ovpn_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
1983 	struct route *ro)
1984 {
1985 	struct ovpn_softc *sc;
1986 	struct ovpn_kpeer *peer;
1987 
1988 	OVPN_RLOCK_TRACKER;
1989 
1990 	sc = ifp->if_softc;
1991 
1992 	OVPN_RLOCK(sc);
1993 
1994 	SDT_PROBE1(if_ovpn, tx, transmit, start, m);
1995 
1996 	if (__predict_false(ifp->if_link_state != LINK_STATE_UP)) {
1997 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
1998 		OVPN_RUNLOCK(sc);
1999 		m_freem(m);
2000 		return (ENETDOWN);
2001 	}
2002 
2003 	/**
2004 	 * Only obey 'dst' (i.e. the gateway) if no route is supplied.
2005 	 * That's our indication that we're being called through pf's route-to,
2006 	 * and we should route according to 'dst' instead. We can't do so
2007 	 * consistently, because the usual openvpn configuration sets the first
2008 	 * non-server IP in the subnet as the gateway. If we always use that
2009 	 * one we'd end up routing all traffic to the first client.
2010 	 * tl;dr: 'ro == NULL' tells us pf is doing a route-to, and then but
2011 	 * only then, we should treat 'dst' as the destination. */
2012 	peer = ovpn_route_peer(sc, &m, ro == NULL ? dst : NULL);
2013 	if (peer == NULL) {
2014 		/* No destination. */
2015 		OVPN_COUNTER_ADD(sc, lost_data_pkts_out, 1);
2016 		OVPN_RUNLOCK(sc);
2017 		m_freem(m);
2018 		return (ENETDOWN);
2019 	}
2020 
2021 	return (ovpn_transmit_to_peer(ifp, m, peer, _ovpn_lock_trackerp));
2022 }
2023 
2024 static void
2025 ovpn_rcv_ctrl(struct ovpn_softc *sc, struct mbuf *m, int off)
2026 {
2027 	/* Lop off the IP and UDP headers */
2028 	m_adj_decap(m, off);
2029 
2030 	/* Keep in the local ring until userspace fetches it. */
2031 	if (buf_ring_enqueue(sc->rxring, m) != 0) {
2032 		OVPN_COUNTER_ADD(sc, lost_ctrl_pkts_in, 1);
2033 		m_freem(m);
2034 		return;
2035 	}
2036 
2037 	OVPN_COUNTER_ADD(sc, received_ctrl_pkts, 1);
2038 }
2039 
2040 static bool
2041 ovpn_check_replay(struct ovpn_kkey_dir *key, uint32_t seq)
2042 {
2043 	uint32_t d;
2044 
2045 	mtx_lock(&key->replay_mtx);
2046 
2047 	/* Sequence number must be strictly greater than rx_seq */
2048 	if (seq <= key->rx_seq) {
2049 		mtx_unlock(&key->replay_mtx);
2050 		return (false);
2051 	}
2052 
2053 	/* Large jump. The packet authenticated okay, so just accept that. */
2054 	if (seq > (key->rx_seq + (sizeof(key->rx_window) * 8))) {
2055 		key->rx_seq = seq;
2056 		key->rx_window = 0;
2057 		mtx_unlock(&key->replay_mtx);
2058 		return (true);
2059 	}
2060 
2061 	/* Happy case. */
2062 	if ((seq == key->rx_seq + 1) && key->rx_window == 0) {
2063 		key->rx_seq++;
2064 		mtx_unlock(&key->replay_mtx);
2065 		return (true);
2066 	}
2067 
2068 	d = seq - key->rx_seq - 1;
2069 
2070 	if (key->rx_window & ((uint64_t)1 << d)) {
2071 		/* Dupe! */
2072 		mtx_unlock(&key->replay_mtx);
2073 		return (false);
2074 	}
2075 
2076 	key->rx_window |= (uint64_t)1 << d;
2077 
2078 	while (key->rx_window & 1) {
2079 		key->rx_seq++;
2080 		key->rx_window >>= 1;
2081 	}
2082 
2083 	mtx_unlock(&key->replay_mtx);
2084 
2085 	return (true);
2086 }
2087 
2088 static struct ovpn_kpeer *
2089 ovpn_peer_from_mbuf(struct ovpn_softc *sc, struct mbuf *m, int off)
2090 {
2091 	struct ovpn_wire_header ohdr;
2092 	uint32_t peerid;
2093 	const size_t hdrlen = sizeof(ohdr) - sizeof(ohdr.auth_tag);
2094 
2095 	OVPN_RASSERT(sc);
2096 
2097 	if (m_length(m, NULL) < (off + sizeof(struct udphdr) + hdrlen))
2098 		return (NULL);
2099 
2100 	m_copydata(m, off + sizeof(struct udphdr), hdrlen, (caddr_t)&ohdr);
2101 
2102 	peerid = ntohl(ohdr.opcode) & 0x00ffffff;
2103 
2104 	return (ovpn_find_peer(sc, peerid));
2105 }
2106 
2107 static bool
2108 ovpn_udp_input(struct mbuf *m, int off, struct inpcb *inp,
2109     const struct sockaddr *sa, void *ctx)
2110 {
2111 	struct ovpn_softc *sc = ctx;
2112 	struct ovpn_wire_header *ohdr;
2113 	struct udphdr *uhdr;
2114 	struct ovpn_kkey *key;
2115 	struct cryptop *crp;
2116 	struct ovpn_kpeer *peer;
2117 	size_t ohdrlen;
2118 	int ret;
2119 	uint8_t op;
2120 
2121 	OVPN_RLOCK_TRACKER;
2122 
2123 	M_ASSERTPKTHDR(m);
2124 
2125 	OVPN_COUNTER_ADD(sc, transport_bytes_received, m->m_pkthdr.len - off);
2126 
2127 	ohdrlen = sizeof(*ohdr) - sizeof(ohdr->auth_tag);
2128 
2129 	OVPN_RLOCK(sc);
2130 
2131 	peer = ovpn_peer_from_mbuf(sc, m, off);
2132 	if (peer == NULL) {
2133 		OVPN_RUNLOCK(sc);
2134 		return (false);
2135 	}
2136 
2137 	m = m_pullup(m, off + sizeof(*uhdr) + ohdrlen);
2138 	if (m == NULL) {
2139 		OVPN_RUNLOCK(sc);
2140 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
2141 		return (true);
2142 	}
2143 	uhdr = mtodo(m, off);
2144 	ohdr = mtodo(m, off + sizeof(*uhdr));
2145 
2146 	op = ntohl(ohdr->opcode) >> 24 >> OVPN_OP_SHIFT;
2147 
2148 	/*
2149 	 * Simplify things by getting rid of the preceding headers, we don't
2150 	 * care about them.
2151 	 */
2152 	m_adj_decap(m, off);
2153 
2154 	uhdr = mtodo(m, 0);
2155 	ohdr = mtodo(m, sizeof(*uhdr));
2156 
2157 	if (op != OVPN_OP_DATA_V2) {
2158 		OVPN_RUNLOCK(sc);
2159 		ovpn_rcv_ctrl(sc, m, sizeof(struct udphdr));
2160 		INP_WLOCK(inp);
2161 		udp_notify(inp, EAGAIN);
2162 		INP_WUNLOCK(inp);
2163 		return (true);
2164 	}
2165 
2166 	key = ovpn_find_key(sc, peer, ohdr);
2167 	if (key == NULL || key->decrypt == NULL) {
2168 		OVPN_RUNLOCK(sc);
2169 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
2170 		m_freem(m);
2171 		return (true);
2172 	}
2173 
2174 	if (key->decrypt->cipher == OVPN_CIPHER_ALG_NONE) {
2175 		/* Now remove the outer headers */
2176 		m_adj_decap(m, sizeof(struct udphdr) + ohdrlen);
2177 
2178 		ohdr = mtodo(m, sizeof(*uhdr));
2179 
2180 		ovpn_finish_rx(sc, m, peer, key, ntohl(ohdr->seq),
2181 		    _ovpn_lock_trackerp);
2182 		OVPN_UNLOCK_ASSERT(sc);
2183 		return (true);
2184 	}
2185 
2186 	ohdrlen += sizeof(ohdr->auth_tag);
2187 
2188 	m = m_pullup(m, sizeof(*uhdr) + ohdrlen);
2189 	if (m == NULL) {
2190 		OVPN_RUNLOCK(sc);
2191 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
2192 		return (true);
2193 	}
2194 	uhdr = mtodo(m, 0);
2195 	ohdr = mtodo(m, sizeof(*uhdr));
2196 
2197 	/* Decrypt */
2198 	crp = crypto_getreq(key->decrypt->cryptoid, M_NOWAIT);
2199 	if (crp == NULL) {
2200 		OVPN_COUNTER_ADD(sc, nomem_data_pkts_in, 1);
2201 		OVPN_RUNLOCK(sc);
2202 		m_freem(m);
2203 		return (true);
2204 	}
2205 
2206 	crp->crp_payload_start = sizeof(struct udphdr) + sizeof(*ohdr);
2207 	crp->crp_payload_length = ntohs(uhdr->uh_ulen) -
2208 	    sizeof(*uhdr) - sizeof(*ohdr);
2209 	crp->crp_op = CRYPTO_OP_DECRYPT;
2210 
2211 	/* AAD validation. */
2212 	crp->crp_aad_length = sizeof(*ohdr) - sizeof(ohdr->auth_tag);
2213 	crp->crp_aad = ohdr;
2214 	crp->crp_aad_start = 0;
2215 	crp->crp_op |= CRYPTO_OP_VERIFY_DIGEST;
2216 	crp->crp_digest_start = sizeof(struct udphdr) +
2217 	    offsetof(struct ovpn_wire_header, auth_tag);
2218 
2219 	crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
2220 	memcpy(crp->crp_iv, &ohdr->seq, sizeof(ohdr->seq));
2221 	memcpy(crp->crp_iv + sizeof(ohdr->seq), key->decrypt->nonce,
2222 	    key->decrypt->noncelen);
2223 
2224 	crypto_use_mbuf(crp, m);
2225 	crp->crp_flags |= CRYPTO_F_CBIFSYNC;
2226 	crp->crp_callback = ovpn_decrypt_rx_cb;
2227 	crp->crp_opaque = sc;
2228 
2229 	atomic_add_int(&sc->refcount, 1);
2230 	OVPN_RUNLOCK(sc);
2231 	ret = crypto_dispatch(crp);
2232 	if (ret != 0) {
2233 		OVPN_COUNTER_ADD(sc, lost_data_pkts_in, 1);
2234 	}
2235 
2236 	return (true);
2237 }
2238 
2239 static void
2240 ovpn_qflush(struct ifnet *ifp __unused)
2241 {
2242 
2243 }
2244 
2245 static void
2246 ovpn_flush_rxring(struct ovpn_softc *sc)
2247 {
2248 	struct mbuf *m;
2249 	struct ovpn_notification *n;
2250 
2251 	OVPN_WASSERT(sc);
2252 
2253 	while (! buf_ring_empty(sc->rxring)) {
2254 		m = buf_ring_dequeue_sc(sc->rxring);
2255 		m_freem(m);
2256 	}
2257 
2258 	while (! buf_ring_empty(sc->notifring)) {
2259 		n = buf_ring_dequeue_sc(sc->notifring);
2260 		free(n, M_OVPN);
2261 	}
2262 }
2263 
2264 #ifdef VIMAGE
2265 static void
2266 ovpn_reassign(struct ifnet *ifp, struct vnet *new_vnet __unused,
2267     char *unused __unused)
2268 {
2269 	struct ovpn_softc *sc = ifp->if_softc;
2270 	int i;
2271 	int ret __diagused;
2272 
2273 	i = 0;
2274 
2275 	OVPN_WLOCK(sc);
2276 
2277 	/* Flush keys & configuration. */
2278 	do {
2279 		if (sc->peers[i] != NULL) {
2280 			ret = _ovpn_del_peer(sc, sc->peers[i]->peerid);
2281 			MPASS(ret == 0);
2282 		}
2283 		i++;
2284 	} while (i < OVPN_MAX_PEERS);
2285 
2286 	ovpn_flush_rxring(sc);
2287 
2288 	OVPN_WUNLOCK(sc);
2289 }
2290 #endif
2291 
2292 static int
2293 ovpn_clone_match(struct if_clone *ifc, const char *name)
2294 {
2295 	/*
2296 	 * Allow all names that start with 'ovpn', specifically because pfSense
2297 	 * uses ovpnc1 / ovpns2
2298 	 */
2299 	return (strncmp(ovpnname, name, strlen(ovpnname)) == 0);
2300 }
2301 
2302 static int
2303 ovpn_clone_create(struct if_clone *ifc, char *name, size_t len, caddr_t params)
2304 {
2305 	struct ovpn_softc *sc;
2306 	struct ifnet *ifp;
2307 	char *dp;
2308 	int error, unit, wildcard;
2309 
2310 	/* Try to see if a special unit was requested. */
2311 	error = ifc_name2unit(name, &unit);
2312 	if (error != 0)
2313 		return (error);
2314 	wildcard = (unit < 0);
2315 
2316 	error = ifc_alloc_unit(ifc, &unit);
2317 	if (error != 0)
2318 		return (error);
2319 
2320 	/*
2321 	 * If no unit had been given, we need to adjust the ifName.
2322 	 */
2323 	for (dp = name; *dp != '\0'; dp++);
2324 	if (wildcard) {
2325 		error = snprintf(dp, len - (dp - name), "%d", unit);
2326 		if (error > len - (dp - name)) {
2327 			/* ifName too long. */
2328 			ifc_free_unit(ifc, unit);
2329 			return (ENOSPC);
2330 		}
2331 		dp += error;
2332 	}
2333 
2334 	/* Make sure it doesn't already exist. */
2335 	if (ifunit(name) != NULL)
2336 		return (EEXIST);
2337 
2338 	sc = malloc(sizeof(struct ovpn_softc), M_OVPN, M_WAITOK | M_ZERO);
2339 	sc->ifp = if_alloc(IFT_ENC);
2340 	rm_init_flags(&sc->lock, "if_ovpn_lock", RM_RECURSE);
2341 	sc->refcount = 0;
2342 
2343 	sc->rxring = buf_ring_alloc(32, M_OVPN, M_WAITOK, NULL);
2344 	sc->notifring = buf_ring_alloc(32, M_OVPN, M_WAITOK, NULL);
2345 
2346 	COUNTER_ARRAY_ALLOC(sc->counters, OVPN_COUNTER_SIZE, M_WAITOK);
2347 
2348 	ifp = sc->ifp;
2349 	ifp->if_softc = sc;
2350 	strlcpy(ifp->if_xname, name, IFNAMSIZ);
2351 	ifp->if_dname = ovpngroupname;
2352 	ifp->if_dunit = unit;
2353 
2354 	ifp->if_addrlen = 0;
2355 	ifp->if_mtu = 1428;
2356 	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
2357 	ifp->if_ioctl = ovpn_ioctl;
2358 	ifp->if_transmit = ovpn_transmit;
2359 	ifp->if_output = ovpn_output;
2360 	ifp->if_qflush = ovpn_qflush;
2361 #ifdef VIMAGE
2362 	ifp->if_reassign = ovpn_reassign;
2363 #endif
2364 	ifp->if_capabilities |= IFCAP_LINKSTATE;
2365 	ifp->if_capenable |= IFCAP_LINKSTATE;
2366 
2367 	if_attach(ifp);
2368 	bpfattach(ifp, DLT_NULL, sizeof(uint32_t));
2369 
2370 	return (0);
2371 }
2372 
2373 static void
2374 ovpn_clone_destroy_cb(struct epoch_context *ctx)
2375 {
2376 	struct ovpn_softc *sc;
2377 
2378 	sc = __containerof(ctx, struct ovpn_softc, epoch_ctx);
2379 
2380 	MPASS(sc->peercount == 0);
2381 	for (int i = 0; i < OVPN_MAX_PEERS; i++) {
2382 		MPASS(sc->peers[i] == NULL);
2383 	}
2384 
2385 	COUNTER_ARRAY_FREE(sc->counters, OVPN_COUNTER_SIZE);
2386 
2387 	if_free(sc->ifp);
2388 	free(sc, M_OVPN);
2389 }
2390 
2391 static int
2392 ovpn_clone_destroy(struct if_clone *ifc, struct ifnet *ifp)
2393 {
2394 	struct ovpn_softc *sc;
2395 	int unit;
2396 	int i;
2397 	int ret __diagused;
2398 
2399 	sc = ifp->if_softc;
2400 	unit = ifp->if_dunit;
2401 
2402 	OVPN_WLOCK(sc);
2403 
2404 	if (atomic_load_int(&sc->refcount) > 0) {
2405 		OVPN_WUNLOCK(sc);
2406 		return (EBUSY);
2407 	}
2408 
2409 	i = 0;
2410 	do {
2411 		if (sc->peers[i] != NULL) {
2412 			ret = _ovpn_del_peer(sc, sc->peers[i]->peerid);
2413 			MPASS(ret == 0);
2414 		}
2415 		i++;
2416 	} while (i < OVPN_MAX_PEERS);
2417 
2418 	ovpn_flush_rxring(sc);
2419 	buf_ring_free(sc->rxring, M_OVPN);
2420 	buf_ring_free(sc->notifring, M_OVPN);
2421 
2422 	OVPN_WUNLOCK(sc);
2423 
2424 	bpfdetach(ifp);
2425 	if_detach(ifp);
2426 	ifp->if_softc = NULL;
2427 
2428 	NET_EPOCH_CALL(ovpn_clone_destroy_cb, &sc->epoch_ctx);
2429 
2430 	if (unit != IF_DUNIT_NONE)
2431 		ifc_free_unit(ifc, unit);
2432 
2433 	return (0);
2434 }
2435 
2436 static void
2437 vnet_ovpn_init(const void *unused __unused)
2438 {
2439 	V_ovpn_cloner = if_clone_advanced(ovpngroupname, 0, ovpn_clone_match,
2440 	    ovpn_clone_create, ovpn_clone_destroy);
2441 }
2442 VNET_SYSINIT(vnet_ovpn_init, SI_SUB_PSEUDO, SI_ORDER_ANY,
2443     vnet_ovpn_init, NULL);
2444 
2445 static void
2446 vnet_ovpn_uninit(const void *unused __unused)
2447 {
2448 	if_clone_detach(V_ovpn_cloner);
2449 }
2450 VNET_SYSUNINIT(vnet_ovpn_uninit, SI_SUB_PSEUDO, SI_ORDER_ANY,
2451     vnet_ovpn_uninit, NULL);
2452 
2453 static int
2454 ovpnmodevent(module_t mod, int type, void *data)
2455 {
2456 	switch (type) {
2457 	case MOD_LOAD:
2458 		/* Done in vnet_ovpn_init() */
2459 		break;
2460 	case MOD_UNLOAD:
2461 		/* Done in vnet_ovpn_uninit() */
2462 		break;
2463 	default:
2464 		return (EOPNOTSUPP);
2465 	}
2466 
2467 	return (0);
2468 }
2469 
2470 static moduledata_t ovpn_mod = {
2471 	"if_ovpn",
2472 	ovpnmodevent,
2473 	0
2474 };
2475 
2476 DECLARE_MODULE(if_ovpn, ovpn_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
2477 MODULE_VERSION(if_ovpn, 1);
2478