xref: /freebsd/sys/netpfil/pf/if_pfsync.c (revision edc307eca9a9a9b0ce7445cff513b48f6489e5c6)
1 /*-
2  * SPDX-License-Identifier: (BSD-2-Clause AND ISC)
3  *
4  * Copyright (c) 2002 Michael Shalayeff
5  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
21  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
26  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*-
31  * Copyright (c) 2009 David Gwynne <dlg@openbsd.org>
32  *
33  * Permission to use, copy, modify, and distribute this software for any
34  * purpose with or without fee is hereby granted, provided that the above
35  * copyright notice and this permission notice appear in all copies.
36  *
37  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
38  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
39  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
40  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
41  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
42  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
43  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
44  */
45 
46 /*
47  * $OpenBSD: if_pfsync.c,v 1.110 2009/02/24 05:39:19 dlg Exp $
48  *
49  * Revisions picked from OpenBSD after revision 1.110 import:
50  * 1.119 - don't m_copydata() beyond the len of mbuf in pfsync_input()
51  * 1.118, 1.124, 1.148, 1.149, 1.151, 1.171 - fixes to bulk updates
52  * 1.120, 1.175 - use monotonic time_uptime
53  * 1.122 - reduce number of updates for non-TCP sessions
54  * 1.125, 1.127 - rewrite merge or stale processing
55  * 1.128 - cleanups
56  * 1.146 - bzero() mbuf before sparsely filling it with data
57  * 1.170 - SIOCSIFMTU checks
58  * 1.126, 1.142 - deferred packets processing
59  * 1.173 - correct expire time processing
60  */
61 
62 #include <sys/cdefs.h>
63 #include "opt_inet.h"
64 #include "opt_inet6.h"
65 #include "opt_pf.h"
66 
67 #include <sys/param.h>
68 #include <sys/bus.h>
69 #include <sys/endian.h>
70 #include <sys/interrupt.h>
71 #include <sys/kernel.h>
72 #include <sys/lock.h>
73 #include <sys/mbuf.h>
74 #include <sys/module.h>
75 #include <sys/mutex.h>
76 #include <sys/nv.h>
77 #include <sys/priv.h>
78 #include <sys/smp.h>
79 #include <sys/socket.h>
80 #include <sys/sockio.h>
81 #include <sys/sysctl.h>
82 #include <sys/syslog.h>
83 
84 #include <net/bpf.h>
85 #include <net/if.h>
86 #include <net/if_var.h>
87 #include <net/if_clone.h>
88 #include <net/if_private.h>
89 #include <net/if_types.h>
90 #include <net/vnet.h>
91 #include <net/pfvar.h>
92 #include <net/route.h>
93 #include <net/if_pfsync.h>
94 
95 #include <netinet/if_ether.h>
96 #include <netinet/in.h>
97 #include <netinet/in_var.h>
98 #include <netinet6/in6_var.h>
99 #include <netinet/ip.h>
100 #include <netinet/ip6.h>
101 #include <netinet/ip_carp.h>
102 #include <netinet/ip_var.h>
103 #include <netinet/tcp.h>
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 
107 #include <netinet/ip6.h>
108 #include <netinet6/ip6_var.h>
109 #include <netinet6/scope6_var.h>
110 
111 #include <netpfil/pf/pfsync_nv.h>
112 
113 #define	DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
114 
115 struct pfsync_bucket;
116 struct pfsync_softc;
117 
118 union inet_template {
119 	struct ip	ipv4;
120 	struct ip6_hdr	ipv6;
121 };
122 
123 #define PFSYNC_MINPKT ( \
124 	sizeof(union inet_template) + \
125 	sizeof(struct pfsync_header) + \
126 	sizeof(struct pfsync_subheader) )
127 
128 static int	pfsync_upd_tcp(struct pf_kstate *, struct pfsync_state_peer *,
129 		    struct pfsync_state_peer *);
130 static int	pfsync_in_clr(struct mbuf *, int, int, int, int);
131 static int	pfsync_in_ins(struct mbuf *, int, int, int, int);
132 static int	pfsync_in_iack(struct mbuf *, int, int, int, int);
133 static int	pfsync_in_upd(struct mbuf *, int, int, int, int);
134 static int	pfsync_in_upd_c(struct mbuf *, int, int, int, int);
135 static int	pfsync_in_ureq(struct mbuf *, int, int, int, int);
136 static int	pfsync_in_del_c(struct mbuf *, int, int, int, int);
137 static int	pfsync_in_bus(struct mbuf *, int, int, int, int);
138 static int	pfsync_in_tdb(struct mbuf *, int, int, int, int);
139 static int	pfsync_in_eof(struct mbuf *, int, int, int, int);
140 static int	pfsync_in_error(struct mbuf *, int, int, int, int);
141 
142 static int (*pfsync_acts[])(struct mbuf *, int, int, int, int) = {
143 	pfsync_in_clr,			/* PFSYNC_ACT_CLR */
144 	pfsync_in_ins,			/* PFSYNC_ACT_INS_1301 */
145 	pfsync_in_iack,			/* PFSYNC_ACT_INS_ACK */
146 	pfsync_in_upd,			/* PFSYNC_ACT_UPD_1301 */
147 	pfsync_in_upd_c,		/* PFSYNC_ACT_UPD_C */
148 	pfsync_in_ureq,			/* PFSYNC_ACT_UPD_REQ */
149 	pfsync_in_error,		/* PFSYNC_ACT_DEL */
150 	pfsync_in_del_c,		/* PFSYNC_ACT_DEL_C */
151 	pfsync_in_error,		/* PFSYNC_ACT_INS_F */
152 	pfsync_in_error,		/* PFSYNC_ACT_DEL_F */
153 	pfsync_in_bus,			/* PFSYNC_ACT_BUS */
154 	pfsync_in_tdb,			/* PFSYNC_ACT_TDB */
155 	pfsync_in_eof,			/* PFSYNC_ACT_EOF */
156 	pfsync_in_ins,			/* PFSYNC_ACT_INS_1400 */
157 	pfsync_in_upd,			/* PFSYNC_ACT_UPD_1400 */
158 };
159 
160 struct pfsync_q {
161 	void		(*write)(struct pf_kstate *, void *);
162 	size_t		len;
163 	u_int8_t	action;
164 };
165 
166 /* We have the following sync queues */
167 enum pfsync_q_id {
168 	PFSYNC_Q_INS_1301,
169 	PFSYNC_Q_INS_1400,
170 	PFSYNC_Q_IACK,
171 	PFSYNC_Q_UPD_1301,
172 	PFSYNC_Q_UPD_1400,
173 	PFSYNC_Q_UPD_C,
174 	PFSYNC_Q_DEL_C,
175 	PFSYNC_Q_COUNT,
176 };
177 
178 /* Functions for building messages for given queue */
179 static void	pfsync_out_state_1301(struct pf_kstate *, void *);
180 static void	pfsync_out_state_1400(struct pf_kstate *, void *);
181 static void	pfsync_out_iack(struct pf_kstate *, void *);
182 static void	pfsync_out_upd_c(struct pf_kstate *, void *);
183 static void	pfsync_out_del_c(struct pf_kstate *, void *);
184 
185 /* Attach those functions to queue */
186 static struct pfsync_q pfsync_qs[] = {
187 	{ pfsync_out_state_1301, sizeof(struct pfsync_state_1301), PFSYNC_ACT_INS_1301 },
188 	{ pfsync_out_state_1400, sizeof(struct pfsync_state_1400), PFSYNC_ACT_INS_1400 },
189 	{ pfsync_out_iack,       sizeof(struct pfsync_ins_ack),    PFSYNC_ACT_INS_ACK },
190 	{ pfsync_out_state_1301, sizeof(struct pfsync_state_1301), PFSYNC_ACT_UPD_1301 },
191 	{ pfsync_out_state_1400, sizeof(struct pfsync_state_1400), PFSYNC_ACT_UPD_1400 },
192 	{ pfsync_out_upd_c,      sizeof(struct pfsync_upd_c),      PFSYNC_ACT_UPD_C },
193 	{ pfsync_out_del_c,      sizeof(struct pfsync_del_c),      PFSYNC_ACT_DEL_C }
194 };
195 
196 /* Map queue to pf_kstate->sync_state */
197 static u_int8_t pfsync_qid_sstate[] = {
198 	PFSYNC_S_INS,   /* PFSYNC_Q_INS_1301 */
199 	PFSYNC_S_INS,   /* PFSYNC_Q_INS_1400 */
200 	PFSYNC_S_IACK,  /* PFSYNC_Q_IACK */
201 	PFSYNC_S_UPD,   /* PFSYNC_Q_UPD_1301 */
202 	PFSYNC_S_UPD,   /* PFSYNC_Q_UPD_1400 */
203 	PFSYNC_S_UPD_C, /* PFSYNC_Q_UPD_C */
204 	PFSYNC_S_DEL_C, /* PFSYNC_Q_DEL_C */
205 };
206 
207 /* Map pf_kstate->sync_state to queue */
208 static enum pfsync_q_id pfsync_sstate_to_qid(u_int8_t);
209 
210 static void	pfsync_q_ins(struct pf_kstate *, int sync_state, bool);
211 static void	pfsync_q_del(struct pf_kstate *, bool, struct pfsync_bucket *);
212 
213 static void	pfsync_update_state(struct pf_kstate *);
214 static void	pfsync_tx(struct pfsync_softc *, struct mbuf *);
215 
216 struct pfsync_upd_req_item {
217 	TAILQ_ENTRY(pfsync_upd_req_item)	ur_entry;
218 	struct pfsync_upd_req			ur_msg;
219 };
220 
221 struct pfsync_deferral {
222 	struct pfsync_softc		*pd_sc;
223 	TAILQ_ENTRY(pfsync_deferral)	pd_entry;
224 	struct callout			pd_tmo;
225 
226 	struct pf_kstate		*pd_st;
227 	struct mbuf			*pd_m;
228 };
229 
230 struct pfsync_bucket
231 {
232 	int			b_id;
233 	struct pfsync_softc	*b_sc;
234 	struct mtx		b_mtx;
235 	struct callout		b_tmo;
236 	int			b_flags;
237 #define	PFSYNCF_BUCKET_PUSH	0x00000001
238 
239 	size_t			b_len;
240 	TAILQ_HEAD(, pf_kstate)			b_qs[PFSYNC_Q_COUNT];
241 	TAILQ_HEAD(, pfsync_upd_req_item)	b_upd_req_list;
242 	TAILQ_HEAD(, pfsync_deferral)		b_deferrals;
243 	u_int			b_deferred;
244 	uint8_t			*b_plus;
245 	size_t			b_pluslen;
246 
247 	struct  ifaltq b_snd;
248 };
249 
250 struct pfsync_softc {
251 	/* Configuration */
252 	struct ifnet		*sc_ifp;
253 	struct ifnet		*sc_sync_if;
254 	struct ip_moptions	sc_imo;
255 	struct ip6_moptions	sc_im6o;
256 	struct sockaddr_storage	sc_sync_peer;
257 	uint32_t		sc_flags;
258 	uint8_t			sc_maxupdates;
259 	union inet_template     sc_template;
260 	struct mtx		sc_mtx;
261 	uint32_t		sc_version;
262 
263 	/* Queued data */
264 	struct pfsync_bucket	*sc_buckets;
265 
266 	/* Bulk update info */
267 	struct mtx		sc_bulk_mtx;
268 	uint32_t		sc_ureq_sent;
269 	int			sc_bulk_tries;
270 	uint32_t		sc_ureq_received;
271 	int			sc_bulk_hashid;
272 	uint64_t		sc_bulk_stateid;
273 	uint32_t		sc_bulk_creatorid;
274 	struct callout		sc_bulk_tmo;
275 	struct callout		sc_bulkfail_tmo;
276 };
277 
278 #define	PFSYNC_LOCK(sc)		mtx_lock(&(sc)->sc_mtx)
279 #define	PFSYNC_UNLOCK(sc)	mtx_unlock(&(sc)->sc_mtx)
280 #define	PFSYNC_LOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_mtx, MA_OWNED)
281 
282 #define PFSYNC_BUCKET_LOCK(b)		mtx_lock(&(b)->b_mtx)
283 #define PFSYNC_BUCKET_UNLOCK(b)		mtx_unlock(&(b)->b_mtx)
284 #define PFSYNC_BUCKET_LOCK_ASSERT(b)	mtx_assert(&(b)->b_mtx, MA_OWNED)
285 
286 #define	PFSYNC_BLOCK(sc)	mtx_lock(&(sc)->sc_bulk_mtx)
287 #define	PFSYNC_BUNLOCK(sc)	mtx_unlock(&(sc)->sc_bulk_mtx)
288 #define	PFSYNC_BLOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_bulk_mtx, MA_OWNED)
289 
290 #define PFSYNC_DEFER_TIMEOUT	20
291 
292 static const char pfsyncname[] = "pfsync";
293 static MALLOC_DEFINE(M_PFSYNC, pfsyncname, "pfsync(4) data");
294 VNET_DEFINE_STATIC(struct pfsync_softc	*, pfsyncif) = NULL;
295 #define	V_pfsyncif		VNET(pfsyncif)
296 VNET_DEFINE_STATIC(void *, pfsync_swi_cookie) = NULL;
297 #define	V_pfsync_swi_cookie	VNET(pfsync_swi_cookie)
298 VNET_DEFINE_STATIC(struct intr_event *, pfsync_swi_ie);
299 #define	V_pfsync_swi_ie		VNET(pfsync_swi_ie)
300 VNET_DEFINE_STATIC(struct pfsyncstats, pfsyncstats);
301 #define	V_pfsyncstats		VNET(pfsyncstats)
302 VNET_DEFINE_STATIC(int, pfsync_carp_adj) = CARP_MAXSKEW;
303 #define	V_pfsync_carp_adj	VNET(pfsync_carp_adj)
304 VNET_DEFINE_STATIC(unsigned int, pfsync_defer_timeout) = PFSYNC_DEFER_TIMEOUT;
305 #define	V_pfsync_defer_timeout	VNET(pfsync_defer_timeout)
306 
307 static void	pfsync_timeout(void *);
308 static void	pfsync_push(struct pfsync_bucket *);
309 static void	pfsync_push_all(struct pfsync_softc *);
310 static void	pfsyncintr(void *);
311 static int	pfsync_multicast_setup(struct pfsync_softc *, struct ifnet *,
312 		    struct in_mfilter *, struct in6_mfilter *);
313 static void	pfsync_multicast_cleanup(struct pfsync_softc *);
314 static void	pfsync_pointers_init(void);
315 static void	pfsync_pointers_uninit(void);
316 static int	pfsync_init(void);
317 static void	pfsync_uninit(void);
318 
319 static unsigned long pfsync_buckets;
320 
321 SYSCTL_NODE(_net, OID_AUTO, pfsync, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
322     "PFSYNC");
323 SYSCTL_STRUCT(_net_pfsync, OID_AUTO, stats, CTLFLAG_VNET | CTLFLAG_RW,
324     &VNET_NAME(pfsyncstats), pfsyncstats,
325     "PFSYNC statistics (struct pfsyncstats, net/if_pfsync.h)");
326 SYSCTL_INT(_net_pfsync, OID_AUTO, carp_demotion_factor, CTLFLAG_VNET | CTLFLAG_RW,
327     &VNET_NAME(pfsync_carp_adj), 0, "pfsync's CARP demotion factor adjustment");
328 SYSCTL_ULONG(_net_pfsync, OID_AUTO, pfsync_buckets, CTLFLAG_RDTUN,
329     &pfsync_buckets, 0, "Number of pfsync hash buckets");
330 SYSCTL_UINT(_net_pfsync, OID_AUTO, defer_delay, CTLFLAG_VNET | CTLFLAG_RW,
331     &VNET_NAME(pfsync_defer_timeout), 0, "Deferred packet timeout (in ms)");
332 
333 static int	pfsync_clone_create(struct if_clone *, int, caddr_t);
334 static void	pfsync_clone_destroy(struct ifnet *);
335 static int	pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
336 		    struct pf_state_peer *);
337 static int	pfsyncoutput(struct ifnet *, struct mbuf *,
338 		    const struct sockaddr *, struct route *);
339 static int	pfsyncioctl(struct ifnet *, u_long, caddr_t);
340 
341 static int	pfsync_defer(struct pf_kstate *, struct mbuf *);
342 static void	pfsync_undefer(struct pfsync_deferral *, int);
343 static void	pfsync_undefer_state_locked(struct pf_kstate *, int);
344 static void	pfsync_undefer_state(struct pf_kstate *, int);
345 static void	pfsync_defer_tmo(void *);
346 
347 static void	pfsync_request_update(u_int32_t, u_int64_t);
348 static bool	pfsync_update_state_req(struct pf_kstate *);
349 
350 static void	pfsync_drop_all(struct pfsync_softc *);
351 static void	pfsync_drop(struct pfsync_softc *, int);
352 static void	pfsync_sendout(int, int);
353 static void	pfsync_send_plus(void *, size_t);
354 
355 static void	pfsync_bulk_start(void);
356 static void	pfsync_bulk_status(u_int8_t);
357 static void	pfsync_bulk_update(void *);
358 static void	pfsync_bulk_fail(void *);
359 
360 static void	pfsync_detach_ifnet(struct ifnet *);
361 
362 static int pfsync_pfsyncreq_to_kstatus(struct pfsyncreq *,
363     struct pfsync_kstatus *);
364 static int pfsync_kstatus_to_softc(struct pfsync_kstatus *,
365     struct pfsync_softc *);
366 
367 #ifdef IPSEC
368 static void	pfsync_update_net_tdb(struct pfsync_tdb *);
369 #endif
370 static struct pfsync_bucket	*pfsync_get_bucket(struct pfsync_softc *,
371 		    struct pf_kstate *);
372 
373 #define PFSYNC_MAX_BULKTRIES	12
374 
375 VNET_DEFINE(struct if_clone *, pfsync_cloner);
376 #define	V_pfsync_cloner	VNET(pfsync_cloner)
377 
378 const struct in6_addr in6addr_linklocal_pfsync_group =
379 	{{{ 0xff, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
380 	    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0 }}};
381 static int
pfsync_clone_create(struct if_clone * ifc,int unit,caddr_t param)382 pfsync_clone_create(struct if_clone *ifc, int unit, caddr_t param)
383 {
384 	struct pfsync_softc *sc;
385 	struct ifnet *ifp;
386 	struct pfsync_bucket *b;
387 	int c;
388 	enum pfsync_q_id q;
389 
390 	if (unit != 0)
391 		return (EINVAL);
392 
393 	if (! pfsync_buckets)
394 		pfsync_buckets = mp_ncpus * 2;
395 
396 	sc = malloc(sizeof(struct pfsync_softc), M_PFSYNC, M_WAITOK | M_ZERO);
397 	sc->sc_flags |= PFSYNCF_OK;
398 	sc->sc_maxupdates = 128;
399 	sc->sc_version = PFSYNC_MSG_VERSION_DEFAULT;
400 	sc->sc_buckets = mallocarray(pfsync_buckets, sizeof(*sc->sc_buckets),
401 	    M_PFSYNC, M_ZERO | M_WAITOK);
402 	for (c = 0; c < pfsync_buckets; c++) {
403 		b = &sc->sc_buckets[c];
404 		mtx_init(&b->b_mtx, "pfsync bucket", NULL, MTX_DEF);
405 
406 		b->b_id = c;
407 		b->b_sc = sc;
408 		b->b_len = PFSYNC_MINPKT;
409 
410 		for (q = 0; q < PFSYNC_Q_COUNT; q++)
411 			TAILQ_INIT(&b->b_qs[q]);
412 
413 		TAILQ_INIT(&b->b_upd_req_list);
414 		TAILQ_INIT(&b->b_deferrals);
415 
416 		callout_init(&b->b_tmo, 1);
417 
418 		b->b_snd.ifq_maxlen = ifqmaxlen;
419 	}
420 
421 	ifp = sc->sc_ifp = if_alloc(IFT_PFSYNC);
422 	if_initname(ifp, pfsyncname, unit);
423 	ifp->if_softc = sc;
424 	ifp->if_ioctl = pfsyncioctl;
425 	ifp->if_output = pfsyncoutput;
426 	ifp->if_hdrlen = sizeof(struct pfsync_header);
427 	ifp->if_mtu = ETHERMTU;
428 	mtx_init(&sc->sc_mtx, pfsyncname, NULL, MTX_DEF);
429 	mtx_init(&sc->sc_bulk_mtx, "pfsync bulk", NULL, MTX_DEF);
430 	callout_init_mtx(&sc->sc_bulk_tmo, &sc->sc_bulk_mtx, 0);
431 	callout_init_mtx(&sc->sc_bulkfail_tmo, &sc->sc_bulk_mtx, 0);
432 
433 	if_attach(ifp);
434 
435 	bpfattach(ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
436 
437 	V_pfsyncif = sc;
438 
439 	return (0);
440 }
441 
442 static void
pfsync_clone_destroy(struct ifnet * ifp)443 pfsync_clone_destroy(struct ifnet *ifp)
444 {
445 	struct pfsync_softc *sc = ifp->if_softc;
446 	struct pfsync_bucket *b;
447 	int c, ret;
448 
449 	for (c = 0; c < pfsync_buckets; c++) {
450 		b = &sc->sc_buckets[c];
451 		/*
452 		 * At this stage, everything should have already been
453 		 * cleared by pfsync_uninit(), and we have only to
454 		 * drain callouts.
455 		 */
456 		PFSYNC_BUCKET_LOCK(b);
457 		while (b->b_deferred > 0) {
458 			struct pfsync_deferral *pd =
459 			    TAILQ_FIRST(&b->b_deferrals);
460 
461 			ret = callout_stop(&pd->pd_tmo);
462 			PFSYNC_BUCKET_UNLOCK(b);
463 			if (ret > 0) {
464 				pfsync_undefer(pd, 1);
465 			} else {
466 				callout_drain(&pd->pd_tmo);
467 			}
468 			PFSYNC_BUCKET_LOCK(b);
469 		}
470 		MPASS(b->b_deferred == 0);
471 		MPASS(TAILQ_EMPTY(&b->b_deferrals));
472 		PFSYNC_BUCKET_UNLOCK(b);
473 
474 		free(b->b_plus, M_PFSYNC);
475 		b->b_plus = NULL;
476 		b->b_pluslen = 0;
477 
478 		callout_drain(&b->b_tmo);
479 	}
480 
481 	callout_drain(&sc->sc_bulkfail_tmo);
482 	callout_drain(&sc->sc_bulk_tmo);
483 
484 	if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
485 		(*carp_demote_adj_p)(-V_pfsync_carp_adj, "pfsync destroy");
486 	bpfdetach(ifp);
487 	if_detach(ifp);
488 
489 	pfsync_drop_all(sc);
490 
491 	if_free(ifp);
492 	pfsync_multicast_cleanup(sc);
493 	mtx_destroy(&sc->sc_mtx);
494 	mtx_destroy(&sc->sc_bulk_mtx);
495 
496 	for (c = 0; c < pfsync_buckets; c++) {
497 		b = &sc->sc_buckets[c];
498 		mtx_destroy(&b->b_mtx);
499 	}
500 	free(sc->sc_buckets, M_PFSYNC);
501 	free(sc, M_PFSYNC);
502 
503 	V_pfsyncif = NULL;
504 }
505 
506 static int
pfsync_alloc_scrub_memory(struct pfsync_state_peer * s,struct pf_state_peer * d)507 pfsync_alloc_scrub_memory(struct pfsync_state_peer *s,
508     struct pf_state_peer *d)
509 {
510 	if (s->scrub.scrub_flag && d->scrub == NULL) {
511 		d->scrub = uma_zalloc(V_pf_state_scrub_z, M_NOWAIT | M_ZERO);
512 		if (d->scrub == NULL)
513 			return (ENOMEM);
514 	}
515 
516 	return (0);
517 }
518 
519 static int
pfsync_state_import(union pfsync_state_union * sp,int flags,int msg_version)520 pfsync_state_import(union pfsync_state_union *sp, int flags, int msg_version)
521 {
522 	struct pfsync_softc *sc = V_pfsyncif;
523 #ifndef	__NO_STRICT_ALIGNMENT
524 	struct pfsync_state_key key[2];
525 #endif
526 	struct pfsync_state_key *kw, *ks;
527 	struct pf_kstate	*st = NULL;
528 	struct pf_state_key	*skw = NULL, *sks = NULL;
529 	struct pf_krule		*r = NULL;
530 	struct pfi_kkif		*kif;
531 	struct pfi_kkif		*rt_kif = NULL;
532 	struct pf_kpooladdr	*rpool_first;
533 	int			 error;
534 	uint8_t			 rt = 0;
535 
536 	PF_RULES_RASSERT();
537 
538 	if (sp->pfs_1301.creatorid == 0) {
539 		if (V_pf_status.debug >= PF_DEBUG_MISC)
540 			printf("%s: invalid creator id: %08x\n", __func__,
541 			    ntohl(sp->pfs_1301.creatorid));
542 		return (EINVAL);
543 	}
544 
545 	if ((kif = pfi_kkif_find(sp->pfs_1301.ifname)) == NULL) {
546 		if (V_pf_status.debug >= PF_DEBUG_MISC)
547 			printf("%s: unknown interface: %s\n", __func__,
548 			    sp->pfs_1301.ifname);
549 		if (flags & PFSYNC_SI_IOCTL)
550 			return (EINVAL);
551 		return (0);	/* skip this state */
552 	}
553 
554 	/*
555 	 * If the ruleset checksums match or the state is coming from the ioctl,
556 	 * it's safe to associate the state with the rule of that number.
557 	 */
558 	if (sp->pfs_1301.rule != htonl(-1) && sp->pfs_1301.anchor == htonl(-1) &&
559 	    (flags & (PFSYNC_SI_IOCTL | PFSYNC_SI_CKSUM)) && ntohl(sp->pfs_1301.rule) <
560 	    pf_main_ruleset.rules[PF_RULESET_FILTER].active.rcount)
561 		r = pf_main_ruleset.rules[
562 		    PF_RULESET_FILTER].active.ptr_array[ntohl(sp->pfs_1301.rule)];
563 	else
564 		r = &V_pf_default_rule;
565 
566 	/*
567 	 * Check routing interface early on. Do it before allocating memory etc.
568 	 * because there is a high chance there will be a lot more such states.
569 	 */
570 	switch (msg_version) {
571 	case PFSYNC_MSG_VERSION_1301:
572 		/*
573 		 * On FreeBSD <= 13 the routing interface and routing operation
574 		 * are not sent over pfsync. If the ruleset is identical,
575 		 * though, we might be able to recover the routing information
576 		 * from the local ruleset.
577 		 */
578 		if (r != &V_pf_default_rule) {
579 			struct pf_kpool		*pool = &r->route;
580 
581 			/* Backwards compatibility. */
582 			if (TAILQ_EMPTY(&pool->list))
583 				pool = &r->rdr;
584 
585 			/*
586 			 * The ruleset is identical, try to recover. If the rule
587 			 * has a redirection pool with a single interface, there
588 			 * is a chance that this interface is identical as on
589 			 * the pfsync peer. If there's more than one interface,
590 			 * give up, as we can't be sure that we will pick the
591 			 * same one as the pfsync peer did.
592 			 */
593 			rpool_first = TAILQ_FIRST(&(pool->list));
594 			if ((rpool_first == NULL) ||
595 			    (TAILQ_NEXT(rpool_first, entries) != NULL)) {
596 				DPFPRINTF(PF_DEBUG_MISC,
597 				    ("%s: can't recover routing information "
598 				    "because of empty or bad redirection pool\n",
599 				    __func__));
600 				return ((flags & PFSYNC_SI_IOCTL) ? EINVAL : 0);
601 			}
602 			rt = r->rt;
603 			rt_kif = rpool_first->kif;
604 		} else if (!PF_AZERO(&sp->pfs_1301.rt_addr, sp->pfs_1301.af)) {
605 			/*
606 			 * Ruleset different, routing *supposedly* requested,
607 			 * give up on recovering.
608 			 */
609 			DPFPRINTF(PF_DEBUG_MISC,
610 			    ("%s: can't recover routing information "
611 			    "because of different ruleset\n", __func__));
612 			return ((flags & PFSYNC_SI_IOCTL) ? EINVAL : 0);
613 		}
614 	break;
615 	case PFSYNC_MSG_VERSION_1400:
616 		/*
617 		 * On FreeBSD 14 and above we're not taking any chances.
618 		 * We use the information synced to us.
619 		 */
620 		if (sp->pfs_1400.rt) {
621 			rt_kif = pfi_kkif_find(sp->pfs_1400.rt_ifname);
622 			if (rt_kif == NULL) {
623 				DPFPRINTF(PF_DEBUG_MISC,
624 				    ("%s: unknown route interface: %s\n",
625 				    __func__, sp->pfs_1400.rt_ifname));
626 				return ((flags & PFSYNC_SI_IOCTL) ? EINVAL : 0);
627 			}
628 			rt = sp->pfs_1400.rt;
629 		}
630 	break;
631 	}
632 
633 	if ((r->max_states &&
634 	    counter_u64_fetch(r->states_cur) >= r->max_states))
635 		goto cleanup;
636 
637 	/*
638 	 * XXXGL: consider M_WAITOK in ioctl path after.
639 	 */
640 	st = pf_alloc_state(M_NOWAIT);
641 	if (__predict_false(st == NULL))
642 		goto cleanup;
643 
644 	if ((skw = uma_zalloc(V_pf_state_key_z, M_NOWAIT)) == NULL)
645 		goto cleanup;
646 
647 #ifndef	__NO_STRICT_ALIGNMENT
648 	bcopy(&sp->pfs_1301.key, key, sizeof(struct pfsync_state_key) * 2);
649 	kw = &key[PF_SK_WIRE];
650 	ks = &key[PF_SK_STACK];
651 #else
652 	kw = &sp->pfs_1301.key[PF_SK_WIRE];
653 	ks = &sp->pfs_1301.key[PF_SK_STACK];
654 #endif
655 
656 	if (PF_ANEQ(&kw->addr[0], &ks->addr[0], sp->pfs_1301.af) ||
657 	    PF_ANEQ(&kw->addr[1], &ks->addr[1], sp->pfs_1301.af) ||
658 	    kw->port[0] != ks->port[0] ||
659 	    kw->port[1] != ks->port[1]) {
660 		sks = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
661 		if (sks == NULL)
662 			goto cleanup;
663 	} else
664 		sks = skw;
665 
666 	/* allocate memory for scrub info */
667 	if (pfsync_alloc_scrub_memory(&sp->pfs_1301.src, &st->src) ||
668 	    pfsync_alloc_scrub_memory(&sp->pfs_1301.dst, &st->dst))
669 		goto cleanup;
670 
671 	/* Copy to state key(s). */
672 	skw->addr[0] = kw->addr[0];
673 	skw->addr[1] = kw->addr[1];
674 	skw->port[0] = kw->port[0];
675 	skw->port[1] = kw->port[1];
676 	skw->proto = sp->pfs_1301.proto;
677 	skw->af = sp->pfs_1301.af;
678 	if (sks != skw) {
679 		sks->addr[0] = ks->addr[0];
680 		sks->addr[1] = ks->addr[1];
681 		sks->port[0] = ks->port[0];
682 		sks->port[1] = ks->port[1];
683 		sks->proto = sp->pfs_1301.proto;
684 		sks->af = sp->pfs_1301.af;
685 	}
686 
687 	/* copy to state */
688 	bcopy(&sp->pfs_1301.rt_addr, &st->act.rt_addr, sizeof(st->act.rt_addr));
689 	st->creation = (time_uptime - ntohl(sp->pfs_1301.creation)) * 1000;
690 	st->expire = pf_get_uptime();
691 	if (sp->pfs_1301.expire) {
692 		uint32_t timeout;
693 
694 		timeout = r->timeout[sp->pfs_1301.timeout];
695 		if (!timeout)
696 			timeout = V_pf_default_rule.timeout[sp->pfs_1301.timeout];
697 
698 		/* sp->expire may have been adaptively scaled by export. */
699 		st->expire -= (timeout - ntohl(sp->pfs_1301.expire)) * 1000;
700 	}
701 
702 	st->direction = sp->pfs_1301.direction;
703 	st->act.log = sp->pfs_1301.log;
704 	st->timeout = sp->pfs_1301.timeout;
705 
706 	st->act.rt = rt;
707 	st->act.rt_kif = rt_kif;
708 
709 	switch (msg_version) {
710 		case PFSYNC_MSG_VERSION_1301:
711 			st->state_flags = sp->pfs_1301.state_flags;
712 			/*
713 			 * In FreeBSD 13 pfsync lacks many attributes. Copy them
714 			 * from the rule if possible. If rule can't be matched
715 			 * clear any set options as we can't recover their
716 			 * parameters.
717 			*/
718 			if (r == &V_pf_default_rule) {
719 				st->state_flags &= ~PFSTATE_SETMASK;
720 			} else {
721 				/*
722 				 * Similar to pf_rule_to_actions(). This code
723 				 * won't set the actions properly if they come
724 				 * from multiple "match" rules as only rule
725 				 * creating the state is send over pfsync.
726 				 */
727 				st->act.qid = r->qid;
728 				st->act.pqid = r->pqid;
729 				st->act.rtableid = r->rtableid;
730 				if (r->scrub_flags & PFSTATE_SETTOS)
731 					st->act.set_tos = r->set_tos;
732 				st->act.min_ttl = r->min_ttl;
733 				st->act.max_mss = r->max_mss;
734 				st->state_flags |= (r->scrub_flags &
735 				    (PFSTATE_NODF|PFSTATE_RANDOMID|
736 				    PFSTATE_SETTOS|PFSTATE_SCRUB_TCP|
737 				    PFSTATE_SETPRIO));
738 				if (r->dnpipe || r->dnrpipe) {
739 					if (r->free_flags & PFRULE_DN_IS_PIPE)
740 						st->state_flags |= PFSTATE_DN_IS_PIPE;
741 					else
742 						st->state_flags &= ~PFSTATE_DN_IS_PIPE;
743 				}
744 				st->act.dnpipe = r->dnpipe;
745 				st->act.dnrpipe = r->dnrpipe;
746 			}
747 			break;
748 		case PFSYNC_MSG_VERSION_1400:
749 			st->state_flags = ntohs(sp->pfs_1400.state_flags);
750 			st->act.qid = ntohs(sp->pfs_1400.qid);
751 			st->act.pqid = ntohs(sp->pfs_1400.pqid);
752 			st->act.dnpipe = ntohs(sp->pfs_1400.dnpipe);
753 			st->act.dnrpipe = ntohs(sp->pfs_1400.dnrpipe);
754 			st->act.rtableid = ntohl(sp->pfs_1400.rtableid);
755 			st->act.min_ttl = sp->pfs_1400.min_ttl;
756 			st->act.set_tos = sp->pfs_1400.set_tos;
757 			st->act.max_mss = ntohs(sp->pfs_1400.max_mss);
758 			st->act.set_prio[0] = sp->pfs_1400.set_prio[0];
759 			st->act.set_prio[1] = sp->pfs_1400.set_prio[1];
760 			break;
761 		default:
762 			panic("%s: Unsupported pfsync_msg_version %d",
763 			    __func__, msg_version);
764 	}
765 
766 	st->id = sp->pfs_1301.id;
767 	st->creatorid = sp->pfs_1301.creatorid;
768 	pf_state_peer_ntoh(&sp->pfs_1301.src, &st->src);
769 	pf_state_peer_ntoh(&sp->pfs_1301.dst, &st->dst);
770 
771 	st->rule = r;
772 	st->nat_rule = NULL;
773 	st->anchor = NULL;
774 
775 	st->pfsync_time = time_uptime;
776 	st->sync_state = PFSYNC_S_NONE;
777 
778 	if (!(flags & PFSYNC_SI_IOCTL))
779 		st->state_flags |= PFSTATE_NOSYNC;
780 
781 	if ((error = pf_state_insert(kif, kif, skw, sks, st)) != 0)
782 		goto cleanup_state;
783 
784 	/* XXX when we have nat_rule/anchors, use STATE_INC_COUNTERS */
785 	counter_u64_add(r->states_cur, 1);
786 	counter_u64_add(r->states_tot, 1);
787 
788 	if (!(flags & PFSYNC_SI_IOCTL)) {
789 		st->state_flags &= ~PFSTATE_NOSYNC;
790 		if (st->state_flags & PFSTATE_ACK) {
791 			struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
792 			PFSYNC_BUCKET_LOCK(b);
793 			pfsync_q_ins(st, PFSYNC_S_IACK, true);
794 			PFSYNC_BUCKET_UNLOCK(b);
795 
796 			pfsync_push_all(sc);
797 		}
798 	}
799 	st->state_flags &= ~PFSTATE_ACK;
800 	PF_STATE_UNLOCK(st);
801 
802 	return (0);
803 
804 cleanup:
805 	error = ENOMEM;
806 
807 	if (skw == sks)
808 		sks = NULL;
809 	uma_zfree(V_pf_state_key_z, skw);
810 	uma_zfree(V_pf_state_key_z, sks);
811 
812 cleanup_state:	/* pf_state_insert() frees the state keys. */
813 	if (st) {
814 		st->timeout = PFTM_UNLINKED; /* appease an assert */
815 		pf_free_state(st);
816 	}
817 	return (error);
818 }
819 
820 #ifdef INET
821 static int
pfsync_input(struct mbuf ** mp,int * offp __unused,int proto __unused)822 pfsync_input(struct mbuf **mp, int *offp __unused, int proto __unused)
823 {
824 	struct pfsync_softc *sc = V_pfsyncif;
825 	struct mbuf *m = *mp;
826 	struct ip *ip = mtod(m, struct ip *);
827 	struct pfsync_header *ph;
828 	struct pfsync_subheader subh;
829 
830 	int offset, len, flags = 0;
831 	int rv;
832 	uint16_t count;
833 
834 	PF_RULES_RLOCK_TRACKER;
835 
836 	*mp = NULL;
837 	V_pfsyncstats.pfsyncs_ipackets++;
838 
839 	/* Verify that we have a sync interface configured. */
840 	if (!sc || !sc->sc_sync_if || !V_pf_status.running ||
841 	    (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
842 		goto done;
843 
844 	/* verify that the packet came in on the right interface */
845 	if (sc->sc_sync_if != m->m_pkthdr.rcvif) {
846 		V_pfsyncstats.pfsyncs_badif++;
847 		goto done;
848 	}
849 
850 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IPACKETS, 1);
851 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
852 	/* verify that the IP TTL is 255. */
853 	if (ip->ip_ttl != PFSYNC_DFLTTL) {
854 		V_pfsyncstats.pfsyncs_badttl++;
855 		goto done;
856 	}
857 
858 	offset = ip->ip_hl << 2;
859 	if (m->m_pkthdr.len < offset + sizeof(*ph)) {
860 		V_pfsyncstats.pfsyncs_hdrops++;
861 		goto done;
862 	}
863 
864 	if (offset + sizeof(*ph) > m->m_len) {
865 		if (m_pullup(m, offset + sizeof(*ph)) == NULL) {
866 			V_pfsyncstats.pfsyncs_hdrops++;
867 			return (IPPROTO_DONE);
868 		}
869 		ip = mtod(m, struct ip *);
870 	}
871 	ph = (struct pfsync_header *)((char *)ip + offset);
872 
873 	/* verify the version */
874 	if (ph->version != PFSYNC_VERSION) {
875 		V_pfsyncstats.pfsyncs_badver++;
876 		goto done;
877 	}
878 
879 	len = ntohs(ph->len) + offset;
880 	if (m->m_pkthdr.len < len) {
881 		V_pfsyncstats.pfsyncs_badlen++;
882 		goto done;
883 	}
884 
885 	/*
886 	 * Trusting pf_chksum during packet processing, as well as seeking
887 	 * in interface name tree, require holding PF_RULES_RLOCK().
888 	 */
889 	PF_RULES_RLOCK();
890 	if (!bcmp(&ph->pfcksum, &V_pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
891 		flags = PFSYNC_SI_CKSUM;
892 
893 	offset += sizeof(*ph);
894 	while (offset <= len - sizeof(subh)) {
895 		m_copydata(m, offset, sizeof(subh), (caddr_t)&subh);
896 		offset += sizeof(subh);
897 
898 		if (subh.action >= PFSYNC_ACT_MAX) {
899 			V_pfsyncstats.pfsyncs_badact++;
900 			PF_RULES_RUNLOCK();
901 			goto done;
902 		}
903 
904 		count = ntohs(subh.count);
905 		V_pfsyncstats.pfsyncs_iacts[subh.action] += count;
906 		rv = (*pfsync_acts[subh.action])(m, offset, count, flags, subh.action);
907 		if (rv == -1) {
908 			PF_RULES_RUNLOCK();
909 			return (IPPROTO_DONE);
910 		}
911 
912 		offset += rv;
913 	}
914 	PF_RULES_RUNLOCK();
915 
916 done:
917 	m_freem(m);
918 	return (IPPROTO_DONE);
919 }
920 #endif
921 
922 #ifdef INET6
923 static int
pfsync6_input(struct mbuf ** mp,int * offp __unused,int proto __unused)924 pfsync6_input(struct mbuf **mp, int *offp __unused, int proto __unused)
925 {
926 	struct pfsync_softc *sc = V_pfsyncif;
927 	struct mbuf *m = *mp;
928 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
929 	struct pfsync_header *ph;
930 	struct pfsync_subheader subh;
931 
932 	int offset, len, flags = 0;
933 	int rv;
934 	uint16_t count;
935 
936 	PF_RULES_RLOCK_TRACKER;
937 
938 	*mp = NULL;
939 	V_pfsyncstats.pfsyncs_ipackets++;
940 
941 	/* Verify that we have a sync interface configured. */
942 	if (!sc || !sc->sc_sync_if || !V_pf_status.running ||
943 	    (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
944 		goto done;
945 
946 	/* verify that the packet came in on the right interface */
947 	if (sc->sc_sync_if != m->m_pkthdr.rcvif) {
948 		V_pfsyncstats.pfsyncs_badif++;
949 		goto done;
950 	}
951 
952 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IPACKETS, 1);
953 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
954 	/* verify that the IP TTL is 255. */
955 	if (ip6->ip6_hlim != PFSYNC_DFLTTL) {
956 		V_pfsyncstats.pfsyncs_badttl++;
957 		goto done;
958 	}
959 
960 
961 	offset = sizeof(*ip6);
962 	if (m->m_pkthdr.len < offset + sizeof(*ph)) {
963 		V_pfsyncstats.pfsyncs_hdrops++;
964 		goto done;
965 	}
966 
967 	if (offset + sizeof(*ph) > m->m_len) {
968 		if (m_pullup(m, offset + sizeof(*ph)) == NULL) {
969 			V_pfsyncstats.pfsyncs_hdrops++;
970 			return (IPPROTO_DONE);
971 		}
972 		ip6 = mtod(m, struct ip6_hdr *);
973 	}
974 	ph = (struct pfsync_header *)((char *)ip6 + offset);
975 
976 	/* verify the version */
977 	if (ph->version != PFSYNC_VERSION) {
978 		V_pfsyncstats.pfsyncs_badver++;
979 		goto done;
980 	}
981 
982 	len = ntohs(ph->len) + offset;
983 	if (m->m_pkthdr.len < len) {
984 		V_pfsyncstats.pfsyncs_badlen++;
985 		goto done;
986 	}
987 
988 	/*
989 	 * Trusting pf_chksum during packet processing, as well as seeking
990 	 * in interface name tree, require holding PF_RULES_RLOCK().
991 	 */
992 	PF_RULES_RLOCK();
993 	if (!bcmp(&ph->pfcksum, &V_pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
994 		flags = PFSYNC_SI_CKSUM;
995 
996 	offset += sizeof(*ph);
997 	while (offset <= len - sizeof(subh)) {
998 		m_copydata(m, offset, sizeof(subh), (caddr_t)&subh);
999 		offset += sizeof(subh);
1000 
1001 		if (subh.action >= PFSYNC_ACT_MAX) {
1002 			V_pfsyncstats.pfsyncs_badact++;
1003 			PF_RULES_RUNLOCK();
1004 			goto done;
1005 		}
1006 
1007 		count = ntohs(subh.count);
1008 		V_pfsyncstats.pfsyncs_iacts[subh.action] += count;
1009 		rv = (*pfsync_acts[subh.action])(m, offset, count, flags, subh.action);
1010 		if (rv == -1) {
1011 			PF_RULES_RUNLOCK();
1012 			return (IPPROTO_DONE);
1013 		}
1014 
1015 		offset += rv;
1016 	}
1017 	PF_RULES_RUNLOCK();
1018 
1019 done:
1020 	m_freem(m);
1021 	return (IPPROTO_DONE);
1022 }
1023 #endif
1024 
1025 static int
pfsync_in_clr(struct mbuf * m,int offset,int count,int flags,int action)1026 pfsync_in_clr(struct mbuf *m, int offset, int count, int flags, int action)
1027 {
1028 	struct pfsync_clr *clr;
1029 	struct mbuf *mp;
1030 	int len = sizeof(*clr) * count;
1031 	int i, offp;
1032 	u_int32_t creatorid;
1033 
1034 	mp = m_pulldown(m, offset, len, &offp);
1035 	if (mp == NULL) {
1036 		V_pfsyncstats.pfsyncs_badlen++;
1037 		return (-1);
1038 	}
1039 	clr = (struct pfsync_clr *)(mp->m_data + offp);
1040 
1041 	for (i = 0; i < count; i++) {
1042 		creatorid = clr[i].creatorid;
1043 
1044 		if (clr[i].ifname[0] != '\0' &&
1045 		    pfi_kkif_find(clr[i].ifname) == NULL)
1046 			continue;
1047 
1048 		for (int i = 0; i <= V_pf_hashmask; i++) {
1049 			struct pf_idhash *ih = &V_pf_idhash[i];
1050 			struct pf_kstate *s;
1051 relock:
1052 			PF_HASHROW_LOCK(ih);
1053 			LIST_FOREACH(s, &ih->states, entry) {
1054 				if (s->creatorid == creatorid) {
1055 					s->state_flags |= PFSTATE_NOSYNC;
1056 					pf_remove_state(s);
1057 					goto relock;
1058 				}
1059 			}
1060 			PF_HASHROW_UNLOCK(ih);
1061 		}
1062 	}
1063 
1064 	return (len);
1065 }
1066 
1067 static int
pfsync_in_ins(struct mbuf * m,int offset,int count,int flags,int action)1068 pfsync_in_ins(struct mbuf *m, int offset, int count, int flags, int action)
1069 {
1070 	struct mbuf *mp;
1071 	union pfsync_state_union *sa, *sp;
1072 	int i, offp, total_len, msg_version, msg_len;
1073 
1074 	switch (action) {
1075 		case PFSYNC_ACT_INS_1301:
1076 			msg_len = sizeof(struct pfsync_state_1301);
1077 			total_len = msg_len * count;
1078 			msg_version = PFSYNC_MSG_VERSION_1301;
1079 			break;
1080 		case PFSYNC_ACT_INS_1400:
1081 			msg_len = sizeof(struct pfsync_state_1400);
1082 			total_len = msg_len * count;
1083 			msg_version = PFSYNC_MSG_VERSION_1400;
1084 			break;
1085 		default:
1086 			V_pfsyncstats.pfsyncs_badact++;
1087 			return (-1);
1088 	}
1089 
1090 	mp = m_pulldown(m, offset, total_len, &offp);
1091 	if (mp == NULL) {
1092 		V_pfsyncstats.pfsyncs_badlen++;
1093 		return (-1);
1094 	}
1095 	sa = (union pfsync_state_union *)(mp->m_data + offp);
1096 
1097 	for (i = 0; i < count; i++) {
1098 		sp = (union pfsync_state_union *)((char *)sa + msg_len * i);
1099 
1100 		/* Check for invalid values. */
1101 		if (sp->pfs_1301.timeout >= PFTM_MAX ||
1102 		    sp->pfs_1301.src.state > PF_TCPS_PROXY_DST ||
1103 		    sp->pfs_1301.dst.state > PF_TCPS_PROXY_DST ||
1104 		    sp->pfs_1301.direction > PF_OUT ||
1105 		    (sp->pfs_1301.af != AF_INET &&
1106 		    sp->pfs_1301.af != AF_INET6)) {
1107 			if (V_pf_status.debug >= PF_DEBUG_MISC)
1108 				printf("%s: invalid value\n", __func__);
1109 			V_pfsyncstats.pfsyncs_badval++;
1110 			continue;
1111 		}
1112 
1113 		if (pfsync_state_import(sp, flags, msg_version) == ENOMEM)
1114 			/* Drop out, but process the rest of the actions. */
1115 			break;
1116 	}
1117 
1118 	return (total_len);
1119 }
1120 
1121 static int
pfsync_in_iack(struct mbuf * m,int offset,int count,int flags,int action)1122 pfsync_in_iack(struct mbuf *m, int offset, int count, int flags, int action)
1123 {
1124 	struct pfsync_ins_ack *ia, *iaa;
1125 	struct pf_kstate *st;
1126 
1127 	struct mbuf *mp;
1128 	int len = count * sizeof(*ia);
1129 	int offp, i;
1130 
1131 	mp = m_pulldown(m, offset, len, &offp);
1132 	if (mp == NULL) {
1133 		V_pfsyncstats.pfsyncs_badlen++;
1134 		return (-1);
1135 	}
1136 	iaa = (struct pfsync_ins_ack *)(mp->m_data + offp);
1137 
1138 	for (i = 0; i < count; i++) {
1139 		ia = &iaa[i];
1140 
1141 		st = pf_find_state_byid(ia->id, ia->creatorid);
1142 		if (st == NULL)
1143 			continue;
1144 
1145 		if (st->state_flags & PFSTATE_ACK) {
1146 			pfsync_undefer_state(st, 0);
1147 		}
1148 		PF_STATE_UNLOCK(st);
1149 	}
1150 	/*
1151 	 * XXX this is not yet implemented, but we know the size of the
1152 	 * message so we can skip it.
1153 	 */
1154 
1155 	return (count * sizeof(struct pfsync_ins_ack));
1156 }
1157 
1158 static int
pfsync_upd_tcp(struct pf_kstate * st,struct pfsync_state_peer * src,struct pfsync_state_peer * dst)1159 pfsync_upd_tcp(struct pf_kstate *st, struct pfsync_state_peer *src,
1160     struct pfsync_state_peer *dst)
1161 {
1162 	int sync = 0;
1163 
1164 	PF_STATE_LOCK_ASSERT(st);
1165 
1166 	/*
1167 	 * The state should never go backwards except
1168 	 * for syn-proxy states.  Neither should the
1169 	 * sequence window slide backwards.
1170 	 */
1171 	if ((st->src.state > src->state &&
1172 	    (st->src.state < PF_TCPS_PROXY_SRC ||
1173 	    src->state >= PF_TCPS_PROXY_SRC)) ||
1174 
1175 	    (st->src.state == src->state &&
1176 	    SEQ_GT(st->src.seqlo, ntohl(src->seqlo))))
1177 		sync++;
1178 	else
1179 		pf_state_peer_ntoh(src, &st->src);
1180 
1181 	if ((st->dst.state > dst->state) ||
1182 
1183 	    (st->dst.state >= TCPS_SYN_SENT &&
1184 	    SEQ_GT(st->dst.seqlo, ntohl(dst->seqlo))))
1185 		sync++;
1186 	else
1187 		pf_state_peer_ntoh(dst, &st->dst);
1188 
1189 	return (sync);
1190 }
1191 
1192 static int
pfsync_in_upd(struct mbuf * m,int offset,int count,int flags,int action)1193 pfsync_in_upd(struct mbuf *m, int offset, int count, int flags, int action)
1194 {
1195 	struct pfsync_softc *sc = V_pfsyncif;
1196 	union pfsync_state_union *sa, *sp;
1197 	struct pf_kstate *st;
1198 	struct mbuf *mp;
1199 	int sync, offp, i, total_len, msg_len, msg_version;
1200 
1201 	switch (action) {
1202 		case PFSYNC_ACT_UPD_1301:
1203 			msg_len = sizeof(struct pfsync_state_1301);
1204 			total_len = msg_len * count;
1205 			msg_version = PFSYNC_MSG_VERSION_1301;
1206 			break;
1207 		case PFSYNC_ACT_UPD_1400:
1208 			msg_len = sizeof(struct pfsync_state_1400);
1209 			total_len = msg_len * count;
1210 			msg_version = PFSYNC_MSG_VERSION_1400;
1211 			break;
1212 		default:
1213 			V_pfsyncstats.pfsyncs_badact++;
1214 			return (-1);
1215 	}
1216 
1217 	mp = m_pulldown(m, offset, total_len, &offp);
1218 	if (mp == NULL) {
1219 		V_pfsyncstats.pfsyncs_badlen++;
1220 		return (-1);
1221 	}
1222 	sa = (union pfsync_state_union *)(mp->m_data + offp);
1223 
1224 	for (i = 0; i < count; i++) {
1225 		sp = (union pfsync_state_union *)((char *)sa + msg_len * i);
1226 
1227 		/* check for invalid values */
1228 		if (sp->pfs_1301.timeout >= PFTM_MAX ||
1229 		    sp->pfs_1301.src.state > PF_TCPS_PROXY_DST ||
1230 		    sp->pfs_1301.dst.state > PF_TCPS_PROXY_DST) {
1231 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1232 				printf("pfsync_input: PFSYNC_ACT_UPD: "
1233 				    "invalid value\n");
1234 			}
1235 			V_pfsyncstats.pfsyncs_badval++;
1236 			continue;
1237 		}
1238 
1239 		st = pf_find_state_byid(sp->pfs_1301.id, sp->pfs_1301.creatorid);
1240 		if (st == NULL) {
1241 			/* insert the update */
1242 			if (pfsync_state_import(sp, flags, msg_version))
1243 				V_pfsyncstats.pfsyncs_badstate++;
1244 			continue;
1245 		}
1246 
1247 		if (st->state_flags & PFSTATE_ACK) {
1248 			pfsync_undefer_state(st, 1);
1249 		}
1250 
1251 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
1252 			sync = pfsync_upd_tcp(st, &sp->pfs_1301.src, &sp->pfs_1301.dst);
1253 		else {
1254 			sync = 0;
1255 
1256 			/*
1257 			 * Non-TCP protocol state machine always go
1258 			 * forwards
1259 			 */
1260 			if (st->src.state > sp->pfs_1301.src.state)
1261 				sync++;
1262 			else
1263 				pf_state_peer_ntoh(&sp->pfs_1301.src, &st->src);
1264 			if (st->dst.state > sp->pfs_1301.dst.state)
1265 				sync++;
1266 			else
1267 				pf_state_peer_ntoh(&sp->pfs_1301.dst, &st->dst);
1268 		}
1269 		if (sync < 2) {
1270 			pfsync_alloc_scrub_memory(&sp->pfs_1301.dst, &st->dst);
1271 			pf_state_peer_ntoh(&sp->pfs_1301.dst, &st->dst);
1272 			st->expire = pf_get_uptime();
1273 			st->timeout = sp->pfs_1301.timeout;
1274 		}
1275 		st->pfsync_time = time_uptime;
1276 
1277 		if (sync) {
1278 			V_pfsyncstats.pfsyncs_stale++;
1279 
1280 			pfsync_update_state(st);
1281 			PF_STATE_UNLOCK(st);
1282 			pfsync_push_all(sc);
1283 			continue;
1284 		}
1285 		PF_STATE_UNLOCK(st);
1286 	}
1287 
1288 	return (total_len);
1289 }
1290 
1291 static int
pfsync_in_upd_c(struct mbuf * m,int offset,int count,int flags,int action)1292 pfsync_in_upd_c(struct mbuf *m, int offset, int count, int flags, int action)
1293 {
1294 	struct pfsync_softc *sc = V_pfsyncif;
1295 	struct pfsync_upd_c *ua, *up;
1296 	struct pf_kstate *st;
1297 	int len = count * sizeof(*up);
1298 	int sync;
1299 	struct mbuf *mp;
1300 	int offp, i;
1301 
1302 	mp = m_pulldown(m, offset, len, &offp);
1303 	if (mp == NULL) {
1304 		V_pfsyncstats.pfsyncs_badlen++;
1305 		return (-1);
1306 	}
1307 	ua = (struct pfsync_upd_c *)(mp->m_data + offp);
1308 
1309 	for (i = 0; i < count; i++) {
1310 		up = &ua[i];
1311 
1312 		/* check for invalid values */
1313 		if (up->timeout >= PFTM_MAX ||
1314 		    up->src.state > PF_TCPS_PROXY_DST ||
1315 		    up->dst.state > PF_TCPS_PROXY_DST) {
1316 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1317 				printf("pfsync_input: "
1318 				    "PFSYNC_ACT_UPD_C: "
1319 				    "invalid value\n");
1320 			}
1321 			V_pfsyncstats.pfsyncs_badval++;
1322 			continue;
1323 		}
1324 
1325 		st = pf_find_state_byid(up->id, up->creatorid);
1326 		if (st == NULL) {
1327 			/* We don't have this state. Ask for it. */
1328 			PFSYNC_BUCKET_LOCK(&sc->sc_buckets[0]);
1329 			pfsync_request_update(up->creatorid, up->id);
1330 			PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[0]);
1331 			continue;
1332 		}
1333 
1334 		if (st->state_flags & PFSTATE_ACK) {
1335 			pfsync_undefer_state(st, 1);
1336 		}
1337 
1338 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
1339 			sync = pfsync_upd_tcp(st, &up->src, &up->dst);
1340 		else {
1341 			sync = 0;
1342 
1343 			/*
1344 			 * Non-TCP protocol state machine always go
1345 			 * forwards
1346 			 */
1347 			if (st->src.state > up->src.state)
1348 				sync++;
1349 			else
1350 				pf_state_peer_ntoh(&up->src, &st->src);
1351 			if (st->dst.state > up->dst.state)
1352 				sync++;
1353 			else
1354 				pf_state_peer_ntoh(&up->dst, &st->dst);
1355 		}
1356 		if (sync < 2) {
1357 			pfsync_alloc_scrub_memory(&up->dst, &st->dst);
1358 			pf_state_peer_ntoh(&up->dst, &st->dst);
1359 			st->expire = pf_get_uptime();
1360 			st->timeout = up->timeout;
1361 		}
1362 		st->pfsync_time = time_uptime;
1363 
1364 		if (sync) {
1365 			V_pfsyncstats.pfsyncs_stale++;
1366 
1367 			pfsync_update_state(st);
1368 			PF_STATE_UNLOCK(st);
1369 			pfsync_push_all(sc);
1370 			continue;
1371 		}
1372 		PF_STATE_UNLOCK(st);
1373 	}
1374 
1375 	return (len);
1376 }
1377 
1378 static int
pfsync_in_ureq(struct mbuf * m,int offset,int count,int flags,int action)1379 pfsync_in_ureq(struct mbuf *m, int offset, int count, int flags, int action)
1380 {
1381 	struct pfsync_upd_req *ur, *ura;
1382 	struct mbuf *mp;
1383 	int len = count * sizeof(*ur);
1384 	int i, offp;
1385 
1386 	struct pf_kstate *st;
1387 
1388 	mp = m_pulldown(m, offset, len, &offp);
1389 	if (mp == NULL) {
1390 		V_pfsyncstats.pfsyncs_badlen++;
1391 		return (-1);
1392 	}
1393 	ura = (struct pfsync_upd_req *)(mp->m_data + offp);
1394 
1395 	for (i = 0; i < count; i++) {
1396 		ur = &ura[i];
1397 
1398 		if (ur->id == 0 && ur->creatorid == 0)
1399 			pfsync_bulk_start();
1400 		else {
1401 			st = pf_find_state_byid(ur->id, ur->creatorid);
1402 			if (st == NULL) {
1403 				V_pfsyncstats.pfsyncs_badstate++;
1404 				continue;
1405 			}
1406 			if (st->state_flags & PFSTATE_NOSYNC) {
1407 				PF_STATE_UNLOCK(st);
1408 				continue;
1409 			}
1410 
1411 			pfsync_update_state_req(st);
1412 			PF_STATE_UNLOCK(st);
1413 		}
1414 	}
1415 
1416 	return (len);
1417 }
1418 
1419 static int
pfsync_in_del_c(struct mbuf * m,int offset,int count,int flags,int action)1420 pfsync_in_del_c(struct mbuf *m, int offset, int count, int flags, int action)
1421 {
1422 	struct mbuf *mp;
1423 	struct pfsync_del_c *sa, *sp;
1424 	struct pf_kstate *st;
1425 	int len = count * sizeof(*sp);
1426 	int offp, i;
1427 
1428 	mp = m_pulldown(m, offset, len, &offp);
1429 	if (mp == NULL) {
1430 		V_pfsyncstats.pfsyncs_badlen++;
1431 		return (-1);
1432 	}
1433 	sa = (struct pfsync_del_c *)(mp->m_data + offp);
1434 
1435 	for (i = 0; i < count; i++) {
1436 		sp = &sa[i];
1437 
1438 		st = pf_find_state_byid(sp->id, sp->creatorid);
1439 		if (st == NULL) {
1440 			V_pfsyncstats.pfsyncs_badstate++;
1441 			continue;
1442 		}
1443 
1444 		st->state_flags |= PFSTATE_NOSYNC;
1445 		pf_remove_state(st);
1446 	}
1447 
1448 	return (len);
1449 }
1450 
1451 static int
pfsync_in_bus(struct mbuf * m,int offset,int count,int flags,int action)1452 pfsync_in_bus(struct mbuf *m, int offset, int count, int flags, int action)
1453 {
1454 	struct pfsync_softc *sc = V_pfsyncif;
1455 	struct pfsync_bus *bus;
1456 	struct mbuf *mp;
1457 	int len = count * sizeof(*bus);
1458 	int offp;
1459 
1460 	PFSYNC_BLOCK(sc);
1461 
1462 	/* If we're not waiting for a bulk update, who cares. */
1463 	if (sc->sc_ureq_sent == 0) {
1464 		PFSYNC_BUNLOCK(sc);
1465 		return (len);
1466 	}
1467 
1468 	mp = m_pulldown(m, offset, len, &offp);
1469 	if (mp == NULL) {
1470 		PFSYNC_BUNLOCK(sc);
1471 		V_pfsyncstats.pfsyncs_badlen++;
1472 		return (-1);
1473 	}
1474 	bus = (struct pfsync_bus *)(mp->m_data + offp);
1475 
1476 	switch (bus->status) {
1477 	case PFSYNC_BUS_START:
1478 		callout_reset(&sc->sc_bulkfail_tmo, 4 * hz +
1479 		    V_pf_limits[PF_LIMIT_STATES].limit /
1480 		    ((sc->sc_ifp->if_mtu - PFSYNC_MINPKT) /
1481 		    sizeof(union pfsync_state_union)),
1482 		    pfsync_bulk_fail, sc);
1483 		if (V_pf_status.debug >= PF_DEBUG_MISC)
1484 			printf("pfsync: received bulk update start\n");
1485 		break;
1486 
1487 	case PFSYNC_BUS_END:
1488 		if (time_uptime - ntohl(bus->endtime) >=
1489 		    sc->sc_ureq_sent) {
1490 			/* that's it, we're happy */
1491 			sc->sc_ureq_sent = 0;
1492 			sc->sc_bulk_tries = 0;
1493 			callout_stop(&sc->sc_bulkfail_tmo);
1494 			if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
1495 				(*carp_demote_adj_p)(-V_pfsync_carp_adj,
1496 				    "pfsync bulk done");
1497 			sc->sc_flags |= PFSYNCF_OK;
1498 			if (V_pf_status.debug >= PF_DEBUG_MISC)
1499 				printf("pfsync: received valid "
1500 				    "bulk update end\n");
1501 		} else {
1502 			if (V_pf_status.debug >= PF_DEBUG_MISC)
1503 				printf("pfsync: received invalid "
1504 				    "bulk update end: bad timestamp\n");
1505 		}
1506 		break;
1507 	}
1508 	PFSYNC_BUNLOCK(sc);
1509 
1510 	return (len);
1511 }
1512 
1513 static int
pfsync_in_tdb(struct mbuf * m,int offset,int count,int flags,int action)1514 pfsync_in_tdb(struct mbuf *m, int offset, int count, int flags, int action)
1515 {
1516 	int len = count * sizeof(struct pfsync_tdb);
1517 
1518 #if defined(IPSEC)
1519 	struct pfsync_tdb *tp;
1520 	struct mbuf *mp;
1521 	int offp;
1522 	int i;
1523 	int s;
1524 
1525 	mp = m_pulldown(m, offset, len, &offp);
1526 	if (mp == NULL) {
1527 		V_pfsyncstats.pfsyncs_badlen++;
1528 		return (-1);
1529 	}
1530 	tp = (struct pfsync_tdb *)(mp->m_data + offp);
1531 
1532 	for (i = 0; i < count; i++)
1533 		pfsync_update_net_tdb(&tp[i]);
1534 #endif
1535 
1536 	return (len);
1537 }
1538 
1539 #if defined(IPSEC)
1540 /* Update an in-kernel tdb. Silently fail if no tdb is found. */
1541 static void
pfsync_update_net_tdb(struct pfsync_tdb * pt)1542 pfsync_update_net_tdb(struct pfsync_tdb *pt)
1543 {
1544 	struct tdb		*tdb;
1545 	int			 s;
1546 
1547 	/* check for invalid values */
1548 	if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
1549 	    (pt->dst.sa.sa_family != AF_INET &&
1550 	    pt->dst.sa.sa_family != AF_INET6))
1551 		goto bad;
1552 
1553 	tdb = gettdb(pt->spi, &pt->dst, pt->sproto);
1554 	if (tdb) {
1555 		pt->rpl = ntohl(pt->rpl);
1556 		pt->cur_bytes = (unsigned long long)be64toh(pt->cur_bytes);
1557 
1558 		/* Neither replay nor byte counter should ever decrease. */
1559 		if (pt->rpl < tdb->tdb_rpl ||
1560 		    pt->cur_bytes < tdb->tdb_cur_bytes) {
1561 			goto bad;
1562 		}
1563 
1564 		tdb->tdb_rpl = pt->rpl;
1565 		tdb->tdb_cur_bytes = pt->cur_bytes;
1566 	}
1567 	return;
1568 
1569 bad:
1570 	if (V_pf_status.debug >= PF_DEBUG_MISC)
1571 		printf("pfsync_insert: PFSYNC_ACT_TDB_UPD: "
1572 		    "invalid value\n");
1573 	V_pfsyncstats.pfsyncs_badstate++;
1574 	return;
1575 }
1576 #endif
1577 
1578 static int
pfsync_in_eof(struct mbuf * m,int offset,int count,int flags,int action)1579 pfsync_in_eof(struct mbuf *m, int offset, int count, int flags, int action)
1580 {
1581 	/* check if we are at the right place in the packet */
1582 	if (offset != m->m_pkthdr.len)
1583 		V_pfsyncstats.pfsyncs_badlen++;
1584 
1585 	/* we're done. free and let the caller return */
1586 	m_freem(m);
1587 	return (-1);
1588 }
1589 
1590 static int
pfsync_in_error(struct mbuf * m,int offset,int count,int flags,int action)1591 pfsync_in_error(struct mbuf *m, int offset, int count, int flags, int action)
1592 {
1593 	V_pfsyncstats.pfsyncs_badact++;
1594 
1595 	m_freem(m);
1596 	return (-1);
1597 }
1598 
1599 static int
pfsyncoutput(struct ifnet * ifp,struct mbuf * m,const struct sockaddr * dst,struct route * rt)1600 pfsyncoutput(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
1601 	struct route *rt)
1602 {
1603 	m_freem(m);
1604 	return (0);
1605 }
1606 
1607 /* ARGSUSED */
1608 static int
pfsyncioctl(struct ifnet * ifp,u_long cmd,caddr_t data)1609 pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1610 {
1611 	struct pfsync_softc *sc = ifp->if_softc;
1612 	struct ifreq *ifr = (struct ifreq *)data;
1613 	struct pfsyncreq pfsyncr;
1614 	size_t nvbuflen;
1615 	int error;
1616 	int c;
1617 
1618 	switch (cmd) {
1619 	case SIOCSIFFLAGS:
1620 		PFSYNC_LOCK(sc);
1621 		if (ifp->if_flags & IFF_UP) {
1622 			ifp->if_drv_flags |= IFF_DRV_RUNNING;
1623 			PFSYNC_UNLOCK(sc);
1624 			pfsync_pointers_init();
1625 		} else {
1626 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1627 			PFSYNC_UNLOCK(sc);
1628 			pfsync_pointers_uninit();
1629 		}
1630 		break;
1631 	case SIOCSIFMTU:
1632 		if (!sc->sc_sync_if ||
1633 		    ifr->ifr_mtu <= PFSYNC_MINPKT ||
1634 		    ifr->ifr_mtu > sc->sc_sync_if->if_mtu)
1635 			return (EINVAL);
1636 		if (ifr->ifr_mtu < ifp->if_mtu) {
1637 			for (c = 0; c < pfsync_buckets; c++) {
1638 				PFSYNC_BUCKET_LOCK(&sc->sc_buckets[c]);
1639 				if (sc->sc_buckets[c].b_len > PFSYNC_MINPKT)
1640 					pfsync_sendout(1, c);
1641 				PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[c]);
1642 			}
1643 		}
1644 		ifp->if_mtu = ifr->ifr_mtu;
1645 		break;
1646 	case SIOCGETPFSYNC:
1647 		bzero(&pfsyncr, sizeof(pfsyncr));
1648 		PFSYNC_LOCK(sc);
1649 		if (sc->sc_sync_if) {
1650 			strlcpy(pfsyncr.pfsyncr_syncdev,
1651 			    sc->sc_sync_if->if_xname, IFNAMSIZ);
1652 		}
1653 		pfsyncr.pfsyncr_syncpeer = ((struct sockaddr_in *)&sc->sc_sync_peer)->sin_addr;
1654 		pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
1655 		pfsyncr.pfsyncr_defer = sc->sc_flags;
1656 		PFSYNC_UNLOCK(sc);
1657 		return (copyout(&pfsyncr, ifr_data_get_ptr(ifr),
1658 		    sizeof(pfsyncr)));
1659 
1660 	case SIOCGETPFSYNCNV:
1661 	    {
1662 		nvlist_t *nvl_syncpeer;
1663 		nvlist_t *nvl = nvlist_create(0);
1664 
1665 		if (nvl == NULL)
1666 			return (ENOMEM);
1667 
1668 		if (sc->sc_sync_if)
1669 			nvlist_add_string(nvl, "syncdev", sc->sc_sync_if->if_xname);
1670 		nvlist_add_number(nvl, "maxupdates", sc->sc_maxupdates);
1671 		nvlist_add_number(nvl, "flags", sc->sc_flags);
1672 		nvlist_add_number(nvl, "version", sc->sc_version);
1673 		if ((nvl_syncpeer = pfsync_sockaddr_to_syncpeer_nvlist(&sc->sc_sync_peer)) != NULL)
1674 			nvlist_add_nvlist(nvl, "syncpeer", nvl_syncpeer);
1675 
1676 		void *packed = NULL;
1677 		packed = nvlist_pack(nvl, &nvbuflen);
1678 		if (packed == NULL) {
1679 			free(packed, M_NVLIST);
1680 			nvlist_destroy(nvl);
1681 			return (ENOMEM);
1682 		}
1683 
1684 		if (nvbuflen > ifr->ifr_cap_nv.buf_length) {
1685 			ifr->ifr_cap_nv.length = nvbuflen;
1686 			ifr->ifr_cap_nv.buffer = NULL;
1687 			free(packed, M_NVLIST);
1688 			nvlist_destroy(nvl);
1689 			return (EFBIG);
1690 		}
1691 
1692 		ifr->ifr_cap_nv.length = nvbuflen;
1693 		error = copyout(packed, ifr->ifr_cap_nv.buffer, nvbuflen);
1694 
1695 		nvlist_destroy(nvl);
1696 		nvlist_destroy(nvl_syncpeer);
1697 		free(packed, M_NVLIST);
1698 		break;
1699 	    }
1700 
1701 	case SIOCSETPFSYNC:
1702 	    {
1703 		struct pfsync_kstatus status;
1704 
1705 		if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
1706 			return (error);
1707 		if ((error = copyin(ifr_data_get_ptr(ifr), &pfsyncr,
1708 		    sizeof(pfsyncr))))
1709 			return (error);
1710 
1711 		memset((char *)&status, 0, sizeof(struct pfsync_kstatus));
1712 		pfsync_pfsyncreq_to_kstatus(&pfsyncr, &status);
1713 
1714 		error = pfsync_kstatus_to_softc(&status, sc);
1715 		return (error);
1716 	    }
1717 	case SIOCSETPFSYNCNV:
1718 	    {
1719 		struct pfsync_kstatus status;
1720 		void *data;
1721 		nvlist_t *nvl;
1722 
1723 		if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
1724 			return (error);
1725 		if (ifr->ifr_cap_nv.length > IFR_CAP_NV_MAXBUFSIZE)
1726 			return (EINVAL);
1727 
1728 		data = malloc(ifr->ifr_cap_nv.length, M_TEMP, M_WAITOK);
1729 
1730 		if ((error = copyin(ifr->ifr_cap_nv.buffer, data,
1731 		    ifr->ifr_cap_nv.length)) != 0) {
1732 			free(data, M_TEMP);
1733 			return (error);
1734 		}
1735 
1736 		if ((nvl = nvlist_unpack(data, ifr->ifr_cap_nv.length, 0)) == NULL) {
1737 			free(data, M_TEMP);
1738 			return (EINVAL);
1739 		}
1740 
1741 		memset((char *)&status, 0, sizeof(struct pfsync_kstatus));
1742 		pfsync_nvstatus_to_kstatus(nvl, &status);
1743 
1744 		nvlist_destroy(nvl);
1745 		free(data, M_TEMP);
1746 
1747 		error = pfsync_kstatus_to_softc(&status, sc);
1748 		return (error);
1749 	    }
1750 	default:
1751 		return (ENOTTY);
1752 	}
1753 
1754 	return (0);
1755 }
1756 
1757 static void
pfsync_out_state_1301(struct pf_kstate * st,void * buf)1758 pfsync_out_state_1301(struct pf_kstate *st, void *buf)
1759 {
1760 	union pfsync_state_union *sp = buf;
1761 
1762 	pfsync_state_export(sp, st, PFSYNC_MSG_VERSION_1301);
1763 }
1764 
1765 static void
pfsync_out_state_1400(struct pf_kstate * st,void * buf)1766 pfsync_out_state_1400(struct pf_kstate *st, void *buf)
1767 {
1768 	union pfsync_state_union *sp = buf;
1769 
1770 	pfsync_state_export(sp, st, PFSYNC_MSG_VERSION_1400);
1771 }
1772 
1773 static void
pfsync_out_iack(struct pf_kstate * st,void * buf)1774 pfsync_out_iack(struct pf_kstate *st, void *buf)
1775 {
1776 	struct pfsync_ins_ack *iack = buf;
1777 
1778 	iack->id = st->id;
1779 	iack->creatorid = st->creatorid;
1780 }
1781 
1782 static void
pfsync_out_upd_c(struct pf_kstate * st,void * buf)1783 pfsync_out_upd_c(struct pf_kstate *st, void *buf)
1784 {
1785 	struct pfsync_upd_c *up = buf;
1786 
1787 	bzero(up, sizeof(*up));
1788 	up->id = st->id;
1789 	pf_state_peer_hton(&st->src, &up->src);
1790 	pf_state_peer_hton(&st->dst, &up->dst);
1791 	up->creatorid = st->creatorid;
1792 	up->timeout = st->timeout;
1793 }
1794 
1795 static void
pfsync_out_del_c(struct pf_kstate * st,void * buf)1796 pfsync_out_del_c(struct pf_kstate *st, void *buf)
1797 {
1798 	struct pfsync_del_c *dp = buf;
1799 
1800 	dp->id = st->id;
1801 	dp->creatorid = st->creatorid;
1802 	st->state_flags |= PFSTATE_NOSYNC;
1803 }
1804 
1805 static void
pfsync_drop_all(struct pfsync_softc * sc)1806 pfsync_drop_all(struct pfsync_softc *sc)
1807 {
1808 	struct pfsync_bucket *b;
1809 	int c;
1810 
1811 	for (c = 0; c < pfsync_buckets; c++) {
1812 		b = &sc->sc_buckets[c];
1813 
1814 		PFSYNC_BUCKET_LOCK(b);
1815 		pfsync_drop(sc, c);
1816 		PFSYNC_BUCKET_UNLOCK(b);
1817 	}
1818 }
1819 
1820 static void
pfsync_drop(struct pfsync_softc * sc,int c)1821 pfsync_drop(struct pfsync_softc *sc, int c)
1822 {
1823 	struct pf_kstate *st, *next;
1824 	struct pfsync_upd_req_item *ur;
1825 	struct pfsync_bucket *b;
1826 	enum pfsync_q_id q;
1827 
1828 	b = &sc->sc_buckets[c];
1829 	PFSYNC_BUCKET_LOCK_ASSERT(b);
1830 
1831 	for (q = 0; q < PFSYNC_Q_COUNT; q++) {
1832 		if (TAILQ_EMPTY(&b->b_qs[q]))
1833 			continue;
1834 
1835 		TAILQ_FOREACH_SAFE(st, &b->b_qs[q], sync_list, next) {
1836 			KASSERT(st->sync_state == pfsync_qid_sstate[q],
1837 				("%s: st->sync_state %d == q %d",
1838 					__func__, st->sync_state, q));
1839 			st->sync_state = PFSYNC_S_NONE;
1840 			pf_release_state(st);
1841 		}
1842 		TAILQ_INIT(&b->b_qs[q]);
1843 	}
1844 
1845 	while ((ur = TAILQ_FIRST(&b->b_upd_req_list)) != NULL) {
1846 		TAILQ_REMOVE(&b->b_upd_req_list, ur, ur_entry);
1847 		free(ur, M_PFSYNC);
1848 	}
1849 
1850 	b->b_len = PFSYNC_MINPKT;
1851 	free(b->b_plus, M_PFSYNC);
1852 	b->b_plus = NULL;
1853 	b->b_pluslen = 0;
1854 }
1855 
1856 static void
pfsync_sendout(int schedswi,int c)1857 pfsync_sendout(int schedswi, int c)
1858 {
1859 	struct pfsync_softc *sc = V_pfsyncif;
1860 	struct ifnet *ifp = sc->sc_ifp;
1861 	struct mbuf *m;
1862 	struct pfsync_header *ph;
1863 	struct pfsync_subheader *subh;
1864 	struct pf_kstate *st, *st_next;
1865 	struct pfsync_upd_req_item *ur;
1866 	struct pfsync_bucket *b = &sc->sc_buckets[c];
1867 	size_t len;
1868 	int aflen, offset, count = 0;
1869 	enum pfsync_q_id q;
1870 
1871 	KASSERT(sc != NULL, ("%s: null sc", __func__));
1872 	KASSERT(b->b_len > PFSYNC_MINPKT,
1873 	    ("%s: sc_len %zu", __func__, b->b_len));
1874 	PFSYNC_BUCKET_LOCK_ASSERT(b);
1875 
1876 	if (!bpf_peers_present(ifp->if_bpf) && sc->sc_sync_if == NULL) {
1877 		pfsync_drop(sc, c);
1878 		return;
1879 	}
1880 
1881 	m = m_get2(max_linkhdr + b->b_len, M_NOWAIT, MT_DATA, M_PKTHDR);
1882 	if (m == NULL) {
1883 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OERRORS, 1);
1884 		V_pfsyncstats.pfsyncs_onomem++;
1885 		return;
1886 	}
1887 	m->m_data += max_linkhdr;
1888 	bzero(m->m_data, b->b_len);
1889 
1890 	len = b->b_len;
1891 
1892 	/* build the ip header */
1893 	switch (sc->sc_sync_peer.ss_family) {
1894 #ifdef INET
1895 	case AF_INET:
1896 	    {
1897 		struct ip *ip;
1898 
1899 		ip = mtod(m, struct ip *);
1900 		bcopy(&sc->sc_template.ipv4, ip, sizeof(*ip));
1901 		aflen = offset = sizeof(*ip);
1902 
1903 		len -= sizeof(union inet_template) - sizeof(struct ip);
1904 		ip->ip_len = htons(len);
1905 		ip_fillid(ip, V_ip_random_id);
1906 		break;
1907 	    }
1908 #endif
1909 #ifdef INET6
1910 	case AF_INET6:
1911 		{
1912 		struct ip6_hdr *ip6;
1913 
1914 		ip6 = mtod(m, struct ip6_hdr *);
1915 		bcopy(&sc->sc_template.ipv6, ip6, sizeof(*ip6));
1916 		aflen = offset = sizeof(*ip6);
1917 
1918 		len -= sizeof(union inet_template) - sizeof(struct ip6_hdr);
1919 		ip6->ip6_plen = htons(len);
1920 		break;
1921 		}
1922 #endif
1923 	default:
1924 		m_freem(m);
1925 		pfsync_drop(sc, c);
1926 		return;
1927 	}
1928 	m->m_len = m->m_pkthdr.len = len;
1929 
1930 	/* build the pfsync header */
1931 	ph = (struct pfsync_header *)(m->m_data + offset);
1932 	offset += sizeof(*ph);
1933 
1934 	ph->version = PFSYNC_VERSION;
1935 	ph->len = htons(len - aflen);
1936 	bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
1937 
1938 	/* walk the queues */
1939 	for (q = 0; q < PFSYNC_Q_COUNT; q++) {
1940 		if (TAILQ_EMPTY(&b->b_qs[q]))
1941 			continue;
1942 
1943 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1944 		offset += sizeof(*subh);
1945 
1946 		count = 0;
1947 		TAILQ_FOREACH_SAFE(st, &b->b_qs[q], sync_list, st_next) {
1948 			KASSERT(st->sync_state == pfsync_qid_sstate[q],
1949 				("%s: st->sync_state == q",
1950 					__func__));
1951 			/*
1952 			 * XXXGL: some of write methods do unlocked reads
1953 			 * of state data :(
1954 			 */
1955 			pfsync_qs[q].write(st, m->m_data + offset);
1956 			offset += pfsync_qs[q].len;
1957 			st->sync_state = PFSYNC_S_NONE;
1958 			pf_release_state(st);
1959 			count++;
1960 		}
1961 		TAILQ_INIT(&b->b_qs[q]);
1962 
1963 		subh->action = pfsync_qs[q].action;
1964 		subh->count = htons(count);
1965 		V_pfsyncstats.pfsyncs_oacts[pfsync_qs[q].action] += count;
1966 	}
1967 
1968 	if (!TAILQ_EMPTY(&b->b_upd_req_list)) {
1969 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1970 		offset += sizeof(*subh);
1971 
1972 		count = 0;
1973 		while ((ur = TAILQ_FIRST(&b->b_upd_req_list)) != NULL) {
1974 			TAILQ_REMOVE(&b->b_upd_req_list, ur, ur_entry);
1975 
1976 			bcopy(&ur->ur_msg, m->m_data + offset,
1977 			    sizeof(ur->ur_msg));
1978 			offset += sizeof(ur->ur_msg);
1979 			free(ur, M_PFSYNC);
1980 			count++;
1981 		}
1982 
1983 		subh->action = PFSYNC_ACT_UPD_REQ;
1984 		subh->count = htons(count);
1985 		V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_UPD_REQ] += count;
1986 	}
1987 
1988 	/* has someone built a custom region for us to add? */
1989 	if (b->b_plus != NULL) {
1990 		bcopy(b->b_plus, m->m_data + offset, b->b_pluslen);
1991 		offset += b->b_pluslen;
1992 
1993 		free(b->b_plus, M_PFSYNC);
1994 		b->b_plus = NULL;
1995 		b->b_pluslen = 0;
1996 	}
1997 
1998 	subh = (struct pfsync_subheader *)(m->m_data + offset);
1999 	offset += sizeof(*subh);
2000 
2001 	subh->action = PFSYNC_ACT_EOF;
2002 	subh->count = htons(1);
2003 	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_EOF]++;
2004 
2005 	/* we're done, let's put it on the wire */
2006 	if (bpf_peers_present(ifp->if_bpf)) {
2007 		m->m_data += aflen;
2008 		m->m_len = m->m_pkthdr.len = len - aflen;
2009 		bpf_mtap(ifp->if_bpf, m);
2010 		m->m_data -= aflen;
2011 		m->m_len = m->m_pkthdr.len = len;
2012 	}
2013 
2014 	if (sc->sc_sync_if == NULL) {
2015 		b->b_len = PFSYNC_MINPKT;
2016 		m_freem(m);
2017 		return;
2018 	}
2019 
2020 	if_inc_counter(sc->sc_ifp, IFCOUNTER_OPACKETS, 1);
2021 	if_inc_counter(sc->sc_ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len);
2022 	b->b_len = PFSYNC_MINPKT;
2023 
2024 	if (!_IF_QFULL(&b->b_snd))
2025 		_IF_ENQUEUE(&b->b_snd, m);
2026 	else {
2027 		m_freem(m);
2028 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OQDROPS, 1);
2029 	}
2030 	if (schedswi)
2031 		swi_sched(V_pfsync_swi_cookie, 0);
2032 }
2033 
2034 static void
pfsync_insert_state(struct pf_kstate * st)2035 pfsync_insert_state(struct pf_kstate *st)
2036 {
2037 	struct pfsync_softc *sc = V_pfsyncif;
2038 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2039 
2040 	if (st->state_flags & PFSTATE_NOSYNC)
2041 		return;
2042 
2043 	if ((st->rule->rule_flag & PFRULE_NOSYNC) ||
2044 	    st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
2045 		st->state_flags |= PFSTATE_NOSYNC;
2046 		return;
2047 	}
2048 
2049 	KASSERT(st->sync_state == PFSYNC_S_NONE,
2050 		("%s: st->sync_state %u", __func__, st->sync_state));
2051 
2052 	PFSYNC_BUCKET_LOCK(b);
2053 	if (b->b_len == PFSYNC_MINPKT)
2054 		callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
2055 
2056 	pfsync_q_ins(st, PFSYNC_S_INS, true);
2057 	PFSYNC_BUCKET_UNLOCK(b);
2058 
2059 	st->sync_updates = 0;
2060 }
2061 
2062 static int
pfsync_defer(struct pf_kstate * st,struct mbuf * m)2063 pfsync_defer(struct pf_kstate *st, struct mbuf *m)
2064 {
2065 	struct pfsync_softc *sc = V_pfsyncif;
2066 	struct pfsync_deferral *pd;
2067 	struct pfsync_bucket *b;
2068 
2069 	if (m->m_flags & (M_BCAST|M_MCAST))
2070 		return (0);
2071 
2072 	if (sc == NULL)
2073 		return (0);
2074 
2075 	b = pfsync_get_bucket(sc, st);
2076 
2077 	PFSYNC_LOCK(sc);
2078 
2079 	if (!(sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) ||
2080 	    !(sc->sc_flags & PFSYNCF_DEFER)) {
2081 		PFSYNC_UNLOCK(sc);
2082 		return (0);
2083 	}
2084 
2085 	PFSYNC_BUCKET_LOCK(b);
2086 	PFSYNC_UNLOCK(sc);
2087 
2088 	if (b->b_deferred >= 128)
2089 		pfsync_undefer(TAILQ_FIRST(&b->b_deferrals), 0);
2090 
2091 	pd = malloc(sizeof(*pd), M_PFSYNC, M_NOWAIT);
2092 	if (pd == NULL) {
2093 		PFSYNC_BUCKET_UNLOCK(b);
2094 		return (0);
2095 	}
2096 	b->b_deferred++;
2097 
2098 	m->m_flags |= M_SKIP_FIREWALL;
2099 	st->state_flags |= PFSTATE_ACK;
2100 
2101 	pd->pd_sc = sc;
2102 	pd->pd_st = st;
2103 	pf_ref_state(st);
2104 	pd->pd_m = m;
2105 
2106 	TAILQ_INSERT_TAIL(&b->b_deferrals, pd, pd_entry);
2107 	callout_init_mtx(&pd->pd_tmo, &b->b_mtx, CALLOUT_RETURNUNLOCKED);
2108 	callout_reset(&pd->pd_tmo, (V_pfsync_defer_timeout * hz) / 1000,
2109 	    pfsync_defer_tmo, pd);
2110 
2111 	pfsync_push(b);
2112 	PFSYNC_BUCKET_UNLOCK(b);
2113 
2114 	return (1);
2115 }
2116 
2117 static void
pfsync_undefer(struct pfsync_deferral * pd,int drop)2118 pfsync_undefer(struct pfsync_deferral *pd, int drop)
2119 {
2120 	struct pfsync_softc *sc = pd->pd_sc;
2121 	struct mbuf *m = pd->pd_m;
2122 	struct pf_kstate *st = pd->pd_st;
2123 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2124 
2125 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2126 
2127 	TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
2128 	b->b_deferred--;
2129 	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
2130 	free(pd, M_PFSYNC);
2131 	pf_release_state(st);
2132 
2133 	if (drop)
2134 		m_freem(m);
2135 	else {
2136 		_IF_ENQUEUE(&b->b_snd, m);
2137 		pfsync_push(b);
2138 	}
2139 }
2140 
2141 static void
pfsync_defer_tmo(void * arg)2142 pfsync_defer_tmo(void *arg)
2143 {
2144 	struct epoch_tracker et;
2145 	struct pfsync_deferral *pd = arg;
2146 	struct pfsync_softc *sc = pd->pd_sc;
2147 	struct mbuf *m = pd->pd_m;
2148 	struct pf_kstate *st = pd->pd_st;
2149 	struct pfsync_bucket *b;
2150 
2151 	CURVNET_SET(sc->sc_ifp->if_vnet);
2152 
2153 	b = pfsync_get_bucket(sc, st);
2154 
2155 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2156 
2157 	TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
2158 	b->b_deferred--;
2159 	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
2160 	PFSYNC_BUCKET_UNLOCK(b);
2161 	free(pd, M_PFSYNC);
2162 
2163 	if (sc->sc_sync_if == NULL) {
2164 		pf_release_state(st);
2165 		m_freem(m);
2166 		CURVNET_RESTORE();
2167 		return;
2168 	}
2169 
2170 	NET_EPOCH_ENTER(et);
2171 
2172 	pfsync_tx(sc, m);
2173 
2174 	pf_release_state(st);
2175 
2176 	CURVNET_RESTORE();
2177 	NET_EPOCH_EXIT(et);
2178 }
2179 
2180 static void
pfsync_undefer_state_locked(struct pf_kstate * st,int drop)2181 pfsync_undefer_state_locked(struct pf_kstate *st, int drop)
2182 {
2183 	struct pfsync_softc *sc = V_pfsyncif;
2184 	struct pfsync_deferral *pd;
2185 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2186 
2187 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2188 
2189 	TAILQ_FOREACH(pd, &b->b_deferrals, pd_entry) {
2190 		 if (pd->pd_st == st) {
2191 			if (callout_stop(&pd->pd_tmo) > 0)
2192 				pfsync_undefer(pd, drop);
2193 
2194 			return;
2195 		}
2196 	}
2197 
2198 	panic("%s: unable to find deferred state", __func__);
2199 }
2200 
2201 static void
pfsync_undefer_state(struct pf_kstate * st,int drop)2202 pfsync_undefer_state(struct pf_kstate *st, int drop)
2203 {
2204 	struct pfsync_softc *sc = V_pfsyncif;
2205 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2206 
2207 	PFSYNC_BUCKET_LOCK(b);
2208 	pfsync_undefer_state_locked(st, drop);
2209 	PFSYNC_BUCKET_UNLOCK(b);
2210 }
2211 
2212 static struct pfsync_bucket*
pfsync_get_bucket(struct pfsync_softc * sc,struct pf_kstate * st)2213 pfsync_get_bucket(struct pfsync_softc *sc, struct pf_kstate *st)
2214 {
2215 	int c = PF_IDHASH(st) % pfsync_buckets;
2216 	return &sc->sc_buckets[c];
2217 }
2218 
2219 static void
pfsync_update_state(struct pf_kstate * st)2220 pfsync_update_state(struct pf_kstate *st)
2221 {
2222 	struct pfsync_softc *sc = V_pfsyncif;
2223 	bool sync = false, ref = true;
2224 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2225 
2226 	PF_STATE_LOCK_ASSERT(st);
2227 	PFSYNC_BUCKET_LOCK(b);
2228 
2229 	if (st->state_flags & PFSTATE_ACK)
2230 		pfsync_undefer_state_locked(st, 0);
2231 	if (st->state_flags & PFSTATE_NOSYNC) {
2232 		if (st->sync_state != PFSYNC_S_NONE)
2233 			pfsync_q_del(st, true, b);
2234 		PFSYNC_BUCKET_UNLOCK(b);
2235 		return;
2236 	}
2237 
2238 	if (b->b_len == PFSYNC_MINPKT)
2239 		callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
2240 
2241 	switch (st->sync_state) {
2242 	case PFSYNC_S_UPD_C:
2243 	case PFSYNC_S_UPD:
2244 	case PFSYNC_S_INS:
2245 		/* we're already handling it */
2246 
2247 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
2248 			st->sync_updates++;
2249 			if (st->sync_updates >= sc->sc_maxupdates)
2250 				sync = true;
2251 		}
2252 		break;
2253 
2254 	case PFSYNC_S_IACK:
2255 		pfsync_q_del(st, false, b);
2256 		ref = false;
2257 		/* FALLTHROUGH */
2258 
2259 	case PFSYNC_S_NONE:
2260 		pfsync_q_ins(st, PFSYNC_S_UPD_C, ref);
2261 		st->sync_updates = 0;
2262 		break;
2263 
2264 	default:
2265 		panic("%s: unexpected sync state %d", __func__, st->sync_state);
2266 	}
2267 
2268 	if (sync || (time_uptime - st->pfsync_time) < 2)
2269 		pfsync_push(b);
2270 
2271 	PFSYNC_BUCKET_UNLOCK(b);
2272 }
2273 
2274 static void
pfsync_request_update(u_int32_t creatorid,u_int64_t id)2275 pfsync_request_update(u_int32_t creatorid, u_int64_t id)
2276 {
2277 	struct pfsync_softc *sc = V_pfsyncif;
2278 	struct pfsync_bucket *b = &sc->sc_buckets[0];
2279 	struct pfsync_upd_req_item *item;
2280 	size_t nlen = sizeof(struct pfsync_upd_req);
2281 
2282 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2283 
2284 	/*
2285 	 * This code does a bit to prevent multiple update requests for the
2286 	 * same state being generated. It searches current subheader queue,
2287 	 * but it doesn't lookup into queue of already packed datagrams.
2288 	 */
2289 	TAILQ_FOREACH(item, &b->b_upd_req_list, ur_entry)
2290 		if (item->ur_msg.id == id &&
2291 		    item->ur_msg.creatorid == creatorid)
2292 			return;
2293 
2294 	item = malloc(sizeof(*item), M_PFSYNC, M_NOWAIT);
2295 	if (item == NULL)
2296 		return; /* XXX stats */
2297 
2298 	item->ur_msg.id = id;
2299 	item->ur_msg.creatorid = creatorid;
2300 
2301 	if (TAILQ_EMPTY(&b->b_upd_req_list))
2302 		nlen += sizeof(struct pfsync_subheader);
2303 
2304 	if (b->b_len + nlen > sc->sc_ifp->if_mtu) {
2305 		pfsync_sendout(0, 0);
2306 
2307 		nlen = sizeof(struct pfsync_subheader) +
2308 		    sizeof(struct pfsync_upd_req);
2309 	}
2310 
2311 	TAILQ_INSERT_TAIL(&b->b_upd_req_list, item, ur_entry);
2312 	b->b_len += nlen;
2313 
2314 	pfsync_push(b);
2315 }
2316 
2317 static bool
pfsync_update_state_req(struct pf_kstate * st)2318 pfsync_update_state_req(struct pf_kstate *st)
2319 {
2320 	struct pfsync_softc *sc = V_pfsyncif;
2321 	bool ref = true, full = false;
2322 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2323 
2324 	PF_STATE_LOCK_ASSERT(st);
2325 	PFSYNC_BUCKET_LOCK(b);
2326 
2327 	if (st->state_flags & PFSTATE_NOSYNC) {
2328 		if (st->sync_state != PFSYNC_S_NONE)
2329 			pfsync_q_del(st, true, b);
2330 		PFSYNC_BUCKET_UNLOCK(b);
2331 		return (full);
2332 	}
2333 
2334 	switch (st->sync_state) {
2335 	case PFSYNC_S_UPD_C:
2336 	case PFSYNC_S_IACK:
2337 		pfsync_q_del(st, false, b);
2338 		ref = false;
2339 		/* FALLTHROUGH */
2340 
2341 	case PFSYNC_S_NONE:
2342 		pfsync_q_ins(st, PFSYNC_S_UPD, ref);
2343 		pfsync_push(b);
2344 		break;
2345 
2346 	case PFSYNC_S_INS:
2347 	case PFSYNC_S_UPD:
2348 	case PFSYNC_S_DEL_C:
2349 		/* we're already handling it */
2350 		break;
2351 
2352 	default:
2353 		panic("%s: unexpected sync state %d", __func__, st->sync_state);
2354 	}
2355 
2356 	if ((sc->sc_ifp->if_mtu - b->b_len) < sizeof(union pfsync_state_union))
2357 		full = true;
2358 
2359 	PFSYNC_BUCKET_UNLOCK(b);
2360 
2361 	return (full);
2362 }
2363 
2364 static void
pfsync_delete_state(struct pf_kstate * st)2365 pfsync_delete_state(struct pf_kstate *st)
2366 {
2367 	struct pfsync_softc *sc = V_pfsyncif;
2368 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2369 	bool ref = true;
2370 
2371 	PFSYNC_BUCKET_LOCK(b);
2372 	if (st->state_flags & PFSTATE_ACK)
2373 		pfsync_undefer_state_locked(st, 1);
2374 	if (st->state_flags & PFSTATE_NOSYNC) {
2375 		if (st->sync_state != PFSYNC_S_NONE)
2376 			pfsync_q_del(st, true, b);
2377 		PFSYNC_BUCKET_UNLOCK(b);
2378 		return;
2379 	}
2380 
2381 	if (b->b_len == PFSYNC_MINPKT)
2382 		callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
2383 
2384 	switch (st->sync_state) {
2385 	case PFSYNC_S_INS:
2386 		/* We never got to tell the world so just forget about it. */
2387 		pfsync_q_del(st, true, b);
2388 		break;
2389 
2390 	case PFSYNC_S_UPD_C:
2391 	case PFSYNC_S_UPD:
2392 	case PFSYNC_S_IACK:
2393 		pfsync_q_del(st, false, b);
2394 		ref = false;
2395 		/* FALLTHROUGH */
2396 
2397 	case PFSYNC_S_NONE:
2398 		pfsync_q_ins(st, PFSYNC_S_DEL_C, ref);
2399 		break;
2400 
2401 	default:
2402 		panic("%s: unexpected sync state %d", __func__, st->sync_state);
2403 	}
2404 
2405 	PFSYNC_BUCKET_UNLOCK(b);
2406 }
2407 
2408 static void
pfsync_clear_states(u_int32_t creatorid,const char * ifname)2409 pfsync_clear_states(u_int32_t creatorid, const char *ifname)
2410 {
2411 	struct {
2412 		struct pfsync_subheader subh;
2413 		struct pfsync_clr clr;
2414 	} __packed r;
2415 
2416 	bzero(&r, sizeof(r));
2417 
2418 	r.subh.action = PFSYNC_ACT_CLR;
2419 	r.subh.count = htons(1);
2420 	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_CLR]++;
2421 
2422 	strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
2423 	r.clr.creatorid = creatorid;
2424 
2425 	pfsync_send_plus(&r, sizeof(r));
2426 }
2427 
2428 static enum pfsync_q_id
pfsync_sstate_to_qid(u_int8_t sync_state)2429 pfsync_sstate_to_qid(u_int8_t sync_state)
2430 {
2431 	struct pfsync_softc *sc = V_pfsyncif;
2432 
2433 	switch (sync_state) {
2434 		case PFSYNC_S_INS:
2435 			switch (sc->sc_version) {
2436 				case PFSYNC_MSG_VERSION_1301:
2437 					return PFSYNC_Q_INS_1301;
2438 				case PFSYNC_MSG_VERSION_1400:
2439 					return PFSYNC_Q_INS_1400;
2440 			}
2441 			break;
2442 		case PFSYNC_S_IACK:
2443 			return PFSYNC_Q_IACK;
2444 		case PFSYNC_S_UPD:
2445 			switch (sc->sc_version) {
2446 				case PFSYNC_MSG_VERSION_1301:
2447 					return PFSYNC_Q_UPD_1301;
2448 				case PFSYNC_MSG_VERSION_1400:
2449 					return PFSYNC_Q_UPD_1400;
2450 			}
2451 			break;
2452 		case PFSYNC_S_UPD_C:
2453 			return PFSYNC_Q_UPD_C;
2454 		case PFSYNC_S_DEL_C:
2455 			return PFSYNC_Q_DEL_C;
2456 		default:
2457 			panic("%s: Unsupported st->sync_state 0x%02x",
2458 			__func__, sync_state);
2459 	}
2460 
2461 	panic("%s: Unsupported pfsync_msg_version %d",
2462 	    __func__, sc->sc_version);
2463 }
2464 
2465 static void
pfsync_q_ins(struct pf_kstate * st,int sync_state,bool ref)2466 pfsync_q_ins(struct pf_kstate *st, int sync_state, bool ref)
2467 {
2468 	enum pfsync_q_id q = pfsync_sstate_to_qid(sync_state);
2469 	struct pfsync_softc *sc = V_pfsyncif;
2470 	size_t nlen = pfsync_qs[q].len;
2471 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2472 
2473 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2474 
2475 	KASSERT(st->sync_state == PFSYNC_S_NONE,
2476 		("%s: st->sync_state %u", __func__, st->sync_state));
2477 	KASSERT(b->b_len >= PFSYNC_MINPKT, ("pfsync pkt len is too low %zu",
2478 	    b->b_len));
2479 
2480 	if (TAILQ_EMPTY(&b->b_qs[q]))
2481 		nlen += sizeof(struct pfsync_subheader);
2482 
2483 	if (b->b_len + nlen > sc->sc_ifp->if_mtu) {
2484 		pfsync_sendout(1, b->b_id);
2485 
2486 		nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
2487 	}
2488 
2489 	b->b_len += nlen;
2490 	st->sync_state = pfsync_qid_sstate[q];
2491 	TAILQ_INSERT_TAIL(&b->b_qs[q], st, sync_list);
2492 	if (ref)
2493 		pf_ref_state(st);
2494 }
2495 
2496 static void
pfsync_q_del(struct pf_kstate * st,bool unref,struct pfsync_bucket * b)2497 pfsync_q_del(struct pf_kstate *st, bool unref, struct pfsync_bucket *b)
2498 {
2499 	enum pfsync_q_id q;
2500 
2501 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2502 	KASSERT(st->sync_state != PFSYNC_S_NONE,
2503 		("%s: st->sync_state != PFSYNC_S_NONE", __func__));
2504 
2505 	q =  pfsync_sstate_to_qid(st->sync_state);
2506 	b->b_len -= pfsync_qs[q].len;
2507 	TAILQ_REMOVE(&b->b_qs[q], st, sync_list);
2508 	st->sync_state = PFSYNC_S_NONE;
2509 	if (unref)
2510 		pf_release_state(st);
2511 
2512 	if (TAILQ_EMPTY(&b->b_qs[q]))
2513 		b->b_len -= sizeof(struct pfsync_subheader);
2514 }
2515 
2516 static void
pfsync_bulk_start(void)2517 pfsync_bulk_start(void)
2518 {
2519 	struct pfsync_softc *sc = V_pfsyncif;
2520 
2521 	if (V_pf_status.debug >= PF_DEBUG_MISC)
2522 		printf("pfsync: received bulk update request\n");
2523 
2524 	PFSYNC_BLOCK(sc);
2525 
2526 	sc->sc_ureq_received = time_uptime;
2527 	sc->sc_bulk_hashid = 0;
2528 	sc->sc_bulk_stateid = 0;
2529 	pfsync_bulk_status(PFSYNC_BUS_START);
2530 	callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
2531 	PFSYNC_BUNLOCK(sc);
2532 }
2533 
2534 static void
pfsync_bulk_update(void * arg)2535 pfsync_bulk_update(void *arg)
2536 {
2537 	struct pfsync_softc *sc = arg;
2538 	struct pf_kstate *s;
2539 	int i;
2540 
2541 	PFSYNC_BLOCK_ASSERT(sc);
2542 	CURVNET_SET(sc->sc_ifp->if_vnet);
2543 
2544 	/*
2545 	 * Start with last state from previous invocation.
2546 	 * It may had gone, in this case start from the
2547 	 * hash slot.
2548 	 */
2549 	s = pf_find_state_byid(sc->sc_bulk_stateid, sc->sc_bulk_creatorid);
2550 
2551 	if (s != NULL)
2552 		i = PF_IDHASH(s);
2553 	else
2554 		i = sc->sc_bulk_hashid;
2555 
2556 	for (; i <= V_pf_hashmask; i++) {
2557 		struct pf_idhash *ih = &V_pf_idhash[i];
2558 
2559 		if (s != NULL)
2560 			PF_HASHROW_ASSERT(ih);
2561 		else {
2562 			PF_HASHROW_LOCK(ih);
2563 			s = LIST_FIRST(&ih->states);
2564 		}
2565 
2566 		for (; s; s = LIST_NEXT(s, entry)) {
2567 			if (s->sync_state == PFSYNC_S_NONE &&
2568 			    s->timeout < PFTM_MAX &&
2569 			    s->pfsync_time <= sc->sc_ureq_received) {
2570 				if (pfsync_update_state_req(s)) {
2571 					/* We've filled a packet. */
2572 					sc->sc_bulk_hashid = i;
2573 					sc->sc_bulk_stateid = s->id;
2574 					sc->sc_bulk_creatorid = s->creatorid;
2575 					PF_HASHROW_UNLOCK(ih);
2576 					callout_reset(&sc->sc_bulk_tmo, 1,
2577 					    pfsync_bulk_update, sc);
2578 					goto full;
2579 				}
2580 			}
2581 		}
2582 		PF_HASHROW_UNLOCK(ih);
2583 	}
2584 
2585 	/* We're done. */
2586 	pfsync_bulk_status(PFSYNC_BUS_END);
2587 full:
2588 	CURVNET_RESTORE();
2589 }
2590 
2591 static void
pfsync_bulk_status(u_int8_t status)2592 pfsync_bulk_status(u_int8_t status)
2593 {
2594 	struct {
2595 		struct pfsync_subheader subh;
2596 		struct pfsync_bus bus;
2597 	} __packed r;
2598 
2599 	struct pfsync_softc *sc = V_pfsyncif;
2600 
2601 	bzero(&r, sizeof(r));
2602 
2603 	r.subh.action = PFSYNC_ACT_BUS;
2604 	r.subh.count = htons(1);
2605 	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_BUS]++;
2606 
2607 	r.bus.creatorid = V_pf_status.hostid;
2608 	r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
2609 	r.bus.status = status;
2610 
2611 	pfsync_send_plus(&r, sizeof(r));
2612 }
2613 
2614 static void
pfsync_bulk_fail(void * arg)2615 pfsync_bulk_fail(void *arg)
2616 {
2617 	struct pfsync_softc *sc = arg;
2618 	struct pfsync_bucket *b = &sc->sc_buckets[0];
2619 
2620 	CURVNET_SET(sc->sc_ifp->if_vnet);
2621 
2622 	PFSYNC_BLOCK_ASSERT(sc);
2623 
2624 	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
2625 		/* Try again */
2626 		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
2627 		    pfsync_bulk_fail, V_pfsyncif);
2628 		PFSYNC_BUCKET_LOCK(b);
2629 		pfsync_request_update(0, 0);
2630 		PFSYNC_BUCKET_UNLOCK(b);
2631 	} else {
2632 		/* Pretend like the transfer was ok. */
2633 		sc->sc_ureq_sent = 0;
2634 		sc->sc_bulk_tries = 0;
2635 		PFSYNC_LOCK(sc);
2636 		if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
2637 			(*carp_demote_adj_p)(-V_pfsync_carp_adj,
2638 			    "pfsync bulk fail");
2639 		sc->sc_flags |= PFSYNCF_OK;
2640 		PFSYNC_UNLOCK(sc);
2641 		if (V_pf_status.debug >= PF_DEBUG_MISC)
2642 			printf("pfsync: failed to receive bulk update\n");
2643 	}
2644 
2645 	CURVNET_RESTORE();
2646 }
2647 
2648 static void
pfsync_send_plus(void * plus,size_t pluslen)2649 pfsync_send_plus(void *plus, size_t pluslen)
2650 {
2651 	struct pfsync_softc *sc = V_pfsyncif;
2652 	struct pfsync_bucket *b = &sc->sc_buckets[0];
2653 	uint8_t *newplus;
2654 
2655 	PFSYNC_BUCKET_LOCK(b);
2656 
2657 	if (b->b_len + pluslen > sc->sc_ifp->if_mtu)
2658 		pfsync_sendout(1, b->b_id);
2659 
2660 	newplus = malloc(pluslen + b->b_pluslen, M_PFSYNC, M_NOWAIT);
2661 	if (newplus == NULL)
2662 		goto out;
2663 
2664 	if (b->b_plus != NULL) {
2665 		memcpy(newplus, b->b_plus, b->b_pluslen);
2666 		free(b->b_plus, M_PFSYNC);
2667 	} else {
2668 		MPASS(b->b_pluslen == 0);
2669 	}
2670 	memcpy(newplus + b->b_pluslen, plus, pluslen);
2671 
2672 	b->b_plus = newplus;
2673 	b->b_pluslen += pluslen;
2674 	b->b_len += pluslen;
2675 
2676 	pfsync_sendout(1, b->b_id);
2677 
2678 out:
2679 	PFSYNC_BUCKET_UNLOCK(b);
2680 }
2681 
2682 static void
pfsync_timeout(void * arg)2683 pfsync_timeout(void *arg)
2684 {
2685 	struct pfsync_bucket *b = arg;
2686 
2687 	CURVNET_SET(b->b_sc->sc_ifp->if_vnet);
2688 	PFSYNC_BUCKET_LOCK(b);
2689 	pfsync_push(b);
2690 	PFSYNC_BUCKET_UNLOCK(b);
2691 	CURVNET_RESTORE();
2692 }
2693 
2694 static void
pfsync_push(struct pfsync_bucket * b)2695 pfsync_push(struct pfsync_bucket *b)
2696 {
2697 
2698 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2699 
2700 	b->b_flags |= PFSYNCF_BUCKET_PUSH;
2701 	swi_sched(V_pfsync_swi_cookie, 0);
2702 }
2703 
2704 static void
pfsync_push_all(struct pfsync_softc * sc)2705 pfsync_push_all(struct pfsync_softc *sc)
2706 {
2707 	int c;
2708 	struct pfsync_bucket *b;
2709 
2710 	for (c = 0; c < pfsync_buckets; c++) {
2711 		b = &sc->sc_buckets[c];
2712 
2713 		PFSYNC_BUCKET_LOCK(b);
2714 		pfsync_push(b);
2715 		PFSYNC_BUCKET_UNLOCK(b);
2716 	}
2717 }
2718 
2719 static void
pfsync_tx(struct pfsync_softc * sc,struct mbuf * m)2720 pfsync_tx(struct pfsync_softc *sc, struct mbuf *m)
2721 {
2722 	struct ip *ip;
2723 	int af, error = 0;
2724 
2725 	ip = mtod(m, struct ip *);
2726 	MPASS(ip->ip_v == IPVERSION || ip->ip_v == (IPV6_VERSION >> 4));
2727 
2728 	af = ip->ip_v == IPVERSION ? AF_INET : AF_INET6;
2729 
2730 	/*
2731 	 * We distinguish between a deferral packet and our
2732 	 * own pfsync packet based on M_SKIP_FIREWALL
2733 	 * flag. This is XXX.
2734 	 */
2735 	switch (af) {
2736 #ifdef INET
2737 	case AF_INET:
2738 		if (m->m_flags & M_SKIP_FIREWALL) {
2739 			error = ip_output(m, NULL, NULL, 0,
2740 			    NULL, NULL);
2741 		} else {
2742 			error = ip_output(m, NULL, NULL,
2743 			    IP_RAWOUTPUT, &sc->sc_imo, NULL);
2744 		}
2745 		break;
2746 #endif
2747 #ifdef INET6
2748 	case AF_INET6:
2749 		if (m->m_flags & M_SKIP_FIREWALL) {
2750 			error = ip6_output(m, NULL, NULL, 0,
2751 			    NULL, NULL, NULL);
2752 		} else {
2753 			error = ip6_output(m, NULL, NULL, 0,
2754 				&sc->sc_im6o, NULL, NULL);
2755 		}
2756 		break;
2757 #endif
2758 	}
2759 
2760 	if (error == 0)
2761 		V_pfsyncstats.pfsyncs_opackets++;
2762 	else
2763 		V_pfsyncstats.pfsyncs_oerrors++;
2764 
2765 }
2766 
2767 static void
pfsyncintr(void * arg)2768 pfsyncintr(void *arg)
2769 {
2770 	struct epoch_tracker et;
2771 	struct pfsync_softc *sc = arg;
2772 	struct pfsync_bucket *b;
2773 	struct mbuf *m, *n;
2774 	int c;
2775 
2776 	NET_EPOCH_ENTER(et);
2777 	CURVNET_SET(sc->sc_ifp->if_vnet);
2778 
2779 	for (c = 0; c < pfsync_buckets; c++) {
2780 		b = &sc->sc_buckets[c];
2781 
2782 		PFSYNC_BUCKET_LOCK(b);
2783 		if ((b->b_flags & PFSYNCF_BUCKET_PUSH) && b->b_len > PFSYNC_MINPKT) {
2784 			pfsync_sendout(0, b->b_id);
2785 			b->b_flags &= ~PFSYNCF_BUCKET_PUSH;
2786 		}
2787 		_IF_DEQUEUE_ALL(&b->b_snd, m);
2788 		PFSYNC_BUCKET_UNLOCK(b);
2789 
2790 		for (; m != NULL; m = n) {
2791 			n = m->m_nextpkt;
2792 			m->m_nextpkt = NULL;
2793 
2794 			pfsync_tx(sc, m);
2795 		}
2796 	}
2797 	CURVNET_RESTORE();
2798 	NET_EPOCH_EXIT(et);
2799 }
2800 
2801 static int
pfsync_multicast_setup(struct pfsync_softc * sc,struct ifnet * ifp,struct in_mfilter * imf,struct in6_mfilter * im6f)2802 pfsync_multicast_setup(struct pfsync_softc *sc, struct ifnet *ifp,
2803     struct in_mfilter* imf, struct in6_mfilter* im6f)
2804 {
2805 #ifdef  INET
2806 	struct ip_moptions *imo = &sc->sc_imo;
2807 #endif
2808 #ifdef INET6
2809 	struct ip6_moptions *im6o = &sc->sc_im6o;
2810 	struct sockaddr_in6 *syncpeer_sa6 = NULL;
2811 #endif
2812 
2813 	if (!(ifp->if_flags & IFF_MULTICAST))
2814 		return (EADDRNOTAVAIL);
2815 
2816 	switch (sc->sc_sync_peer.ss_family) {
2817 #ifdef INET
2818 	case AF_INET:
2819 	{
2820 		int error;
2821 
2822 		ip_mfilter_init(&imo->imo_head);
2823 		imo->imo_multicast_vif = -1;
2824 		if ((error = in_joingroup(ifp,
2825 		    &((struct sockaddr_in *)&sc->sc_sync_peer)->sin_addr, NULL,
2826 		    &imf->imf_inm)) != 0)
2827 			return (error);
2828 
2829 		ip_mfilter_insert(&imo->imo_head, imf);
2830 		imo->imo_multicast_ifp = ifp;
2831 		imo->imo_multicast_ttl = PFSYNC_DFLTTL;
2832 		imo->imo_multicast_loop = 0;
2833 		break;
2834 	}
2835 #endif
2836 #ifdef INET6
2837 	case AF_INET6:
2838 	{
2839 		int error;
2840 
2841 		syncpeer_sa6 = (struct sockaddr_in6 *)&sc->sc_sync_peer;
2842 		if ((error = in6_setscope(&syncpeer_sa6->sin6_addr, ifp, NULL)))
2843 			return (error);
2844 
2845 		ip6_mfilter_init(&im6o->im6o_head);
2846 		if ((error = in6_joingroup(ifp, &syncpeer_sa6->sin6_addr, NULL,
2847 		    &(im6f->im6f_in6m), 0)) != 0)
2848 			return (error);
2849 
2850 		ip6_mfilter_insert(&im6o->im6o_head, im6f);
2851 		im6o->im6o_multicast_ifp = ifp;
2852 		im6o->im6o_multicast_hlim = PFSYNC_DFLTTL;
2853 		im6o->im6o_multicast_loop = 0;
2854 		break;
2855 	}
2856 #endif
2857 	}
2858 
2859 	return (0);
2860 }
2861 
2862 static void
pfsync_multicast_cleanup(struct pfsync_softc * sc)2863 pfsync_multicast_cleanup(struct pfsync_softc *sc)
2864 {
2865 #ifdef INET
2866 	struct ip_moptions *imo = &sc->sc_imo;
2867 	struct in_mfilter *imf;
2868 
2869 	while ((imf = ip_mfilter_first(&imo->imo_head)) != NULL) {
2870 		ip_mfilter_remove(&imo->imo_head, imf);
2871 		in_leavegroup(imf->imf_inm, NULL);
2872 		ip_mfilter_free(imf);
2873 	}
2874 	imo->imo_multicast_ifp = NULL;
2875 #endif
2876 
2877 #ifdef INET6
2878 	struct ip6_moptions *im6o = &sc->sc_im6o;
2879 	struct in6_mfilter *im6f;
2880 
2881 	while ((im6f = ip6_mfilter_first(&im6o->im6o_head)) != NULL) {
2882 		ip6_mfilter_remove(&im6o->im6o_head, im6f);
2883 		in6_leavegroup(im6f->im6f_in6m, NULL);
2884 		ip6_mfilter_free(im6f);
2885 	}
2886 	im6o->im6o_multicast_ifp = NULL;
2887 #endif
2888 }
2889 
2890 void
pfsync_detach_ifnet(struct ifnet * ifp)2891 pfsync_detach_ifnet(struct ifnet *ifp)
2892 {
2893 	struct pfsync_softc *sc = V_pfsyncif;
2894 
2895 	if (sc == NULL)
2896 		return;
2897 
2898 	PFSYNC_LOCK(sc);
2899 
2900 	if (sc->sc_sync_if == ifp) {
2901 		/* We don't need mutlicast cleanup here, because the interface
2902 		 * is going away. We do need to ensure we don't try to do
2903 		 * cleanup later.
2904 		 */
2905 		ip_mfilter_init(&sc->sc_imo.imo_head);
2906 		sc->sc_imo.imo_multicast_ifp = NULL;
2907 		sc->sc_im6o.im6o_multicast_ifp = NULL;
2908 		sc->sc_sync_if = NULL;
2909 	}
2910 
2911 	PFSYNC_UNLOCK(sc);
2912 }
2913 
2914 static int
pfsync_pfsyncreq_to_kstatus(struct pfsyncreq * pfsyncr,struct pfsync_kstatus * status)2915 pfsync_pfsyncreq_to_kstatus(struct pfsyncreq *pfsyncr, struct pfsync_kstatus *status)
2916 {
2917 	struct sockaddr_storage sa;
2918 	status->maxupdates = pfsyncr->pfsyncr_maxupdates;
2919 	status->flags = pfsyncr->pfsyncr_defer;
2920 
2921 	strlcpy(status->syncdev, pfsyncr->pfsyncr_syncdev, IFNAMSIZ);
2922 
2923 	memset(&sa, 0, sizeof(sa));
2924 	if (pfsyncr->pfsyncr_syncpeer.s_addr != 0) {
2925 		struct sockaddr_in *in = (struct sockaddr_in *)&sa;
2926 		in->sin_family = AF_INET;
2927 		in->sin_len = sizeof(*in);
2928 		in->sin_addr.s_addr = pfsyncr->pfsyncr_syncpeer.s_addr;
2929 	}
2930 	status->syncpeer = sa;
2931 
2932 	return 0;
2933 }
2934 
2935 static int
pfsync_kstatus_to_softc(struct pfsync_kstatus * status,struct pfsync_softc * sc)2936 pfsync_kstatus_to_softc(struct pfsync_kstatus *status, struct pfsync_softc *sc)
2937 {
2938 	struct ifnet *sifp;
2939 	struct in_mfilter *imf = NULL;
2940 	struct in6_mfilter *im6f = NULL;
2941 	int error;
2942 	int c;
2943 
2944 	if ((status->maxupdates < 0) || (status->maxupdates > 255))
2945 		return (EINVAL);
2946 
2947 	if (status->syncdev[0] == '\0')
2948 		sifp = NULL;
2949 	else if ((sifp = ifunit_ref(status->syncdev)) == NULL)
2950 		return (EINVAL);
2951 
2952 	switch (status->syncpeer.ss_family) {
2953 #ifdef INET
2954 	case AF_UNSPEC:
2955 	case AF_INET: {
2956 		struct sockaddr_in *status_sin;
2957 		status_sin = (struct sockaddr_in *)&(status->syncpeer);
2958 		if (sifp != NULL) {
2959 			if (status_sin->sin_addr.s_addr == 0 ||
2960 			    status_sin->sin_addr.s_addr ==
2961 			    htonl(INADDR_PFSYNC_GROUP)) {
2962 				status_sin->sin_family = AF_INET;
2963 				status_sin->sin_len = sizeof(*status_sin);
2964 				status_sin->sin_addr.s_addr =
2965 				    htonl(INADDR_PFSYNC_GROUP);
2966 			}
2967 
2968 			if (IN_MULTICAST(ntohl(status_sin->sin_addr.s_addr))) {
2969 				imf = ip_mfilter_alloc(M_WAITOK, 0, 0);
2970 			}
2971 		}
2972 		break;
2973 	}
2974 #endif
2975 #ifdef INET6
2976 	case AF_INET6: {
2977 		struct sockaddr_in6 *status_sin6;
2978 		status_sin6 = (struct sockaddr_in6*)&(status->syncpeer);
2979 		if (sifp != NULL) {
2980 			if (IN6_IS_ADDR_UNSPECIFIED(&status_sin6->sin6_addr) ||
2981 			    IN6_ARE_ADDR_EQUAL(&status_sin6->sin6_addr,
2982 				&in6addr_linklocal_pfsync_group)) {
2983 				status_sin6->sin6_family = AF_INET6;
2984 				status_sin6->sin6_len = sizeof(*status_sin6);
2985 				status_sin6->sin6_addr =
2986 				    in6addr_linklocal_pfsync_group;
2987 			}
2988 
2989 			if (IN6_IS_ADDR_MULTICAST(&status_sin6->sin6_addr)) {
2990 				im6f = ip6_mfilter_alloc(M_WAITOK, 0, 0);
2991 			}
2992 		}
2993 		break;
2994 	}
2995 #endif
2996 	}
2997 
2998 	PFSYNC_LOCK(sc);
2999 
3000 	switch (status->version) {
3001 		case PFSYNC_MSG_VERSION_UNSPECIFIED:
3002 			sc->sc_version = PFSYNC_MSG_VERSION_DEFAULT;
3003 			break;
3004 		case PFSYNC_MSG_VERSION_1301:
3005 		case PFSYNC_MSG_VERSION_1400:
3006 			sc->sc_version = status->version;
3007 			break;
3008 		default:
3009 			PFSYNC_UNLOCK(sc);
3010 			return (EINVAL);
3011 	}
3012 
3013 	switch (status->syncpeer.ss_family) {
3014 	case AF_INET: {
3015 		struct sockaddr_in *status_sin = (struct sockaddr_in *)&(status->syncpeer);
3016 		struct sockaddr_in *sc_sin = (struct sockaddr_in *)&sc->sc_sync_peer;
3017 		sc_sin->sin_family = AF_INET;
3018 		sc_sin->sin_len = sizeof(*sc_sin);
3019 		if (status_sin->sin_addr.s_addr == 0) {
3020 			sc_sin->sin_addr.s_addr = htonl(INADDR_PFSYNC_GROUP);
3021 		} else {
3022 			sc_sin->sin_addr.s_addr = status_sin->sin_addr.s_addr;
3023 		}
3024 		break;
3025 	}
3026 	case AF_INET6: {
3027 		struct sockaddr_in6 *status_sin = (struct sockaddr_in6 *)&(status->syncpeer);
3028 		struct sockaddr_in6 *sc_sin = (struct sockaddr_in6 *)&sc->sc_sync_peer;
3029 		sc_sin->sin6_family = AF_INET6;
3030 		sc_sin->sin6_len = sizeof(*sc_sin);
3031 		if(IN6_IS_ADDR_UNSPECIFIED(&status_sin->sin6_addr)) {
3032 			sc_sin->sin6_addr = in6addr_linklocal_pfsync_group;
3033 		} else {
3034 			sc_sin->sin6_addr = status_sin->sin6_addr;
3035 		}
3036 		break;
3037 	}
3038 	}
3039 
3040 	sc->sc_maxupdates = status->maxupdates;
3041 	if (status->flags & PFSYNCF_DEFER) {
3042 		sc->sc_flags |= PFSYNCF_DEFER;
3043 		V_pfsync_defer_ptr = pfsync_defer;
3044 	} else {
3045 		sc->sc_flags &= ~PFSYNCF_DEFER;
3046 		V_pfsync_defer_ptr = NULL;
3047 	}
3048 
3049 	if (sifp == NULL) {
3050 		if (sc->sc_sync_if)
3051 			if_rele(sc->sc_sync_if);
3052 		sc->sc_sync_if = NULL;
3053 		pfsync_multicast_cleanup(sc);
3054 		PFSYNC_UNLOCK(sc);
3055 		return (0);
3056 	}
3057 
3058 	for (c = 0; c < pfsync_buckets; c++) {
3059 		PFSYNC_BUCKET_LOCK(&sc->sc_buckets[c]);
3060 		if (sc->sc_buckets[c].b_len > PFSYNC_MINPKT &&
3061 		    (sifp->if_mtu < sc->sc_ifp->if_mtu ||
3062 			(sc->sc_sync_if != NULL &&
3063 			    sifp->if_mtu < sc->sc_sync_if->if_mtu) ||
3064 			sifp->if_mtu < MCLBYTES - sizeof(struct ip)))
3065 			pfsync_sendout(1, c);
3066 		PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[c]);
3067 	}
3068 
3069 	pfsync_multicast_cleanup(sc);
3070 
3071 	if (((sc->sc_sync_peer.ss_family == AF_INET) &&
3072 	    IN_MULTICAST(ntohl(((struct sockaddr_in *)
3073 	        &sc->sc_sync_peer)->sin_addr.s_addr))) ||
3074 	    ((sc->sc_sync_peer.ss_family == AF_INET6) &&
3075 	    IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6*)
3076 	        &sc->sc_sync_peer)->sin6_addr))) {
3077 		error = pfsync_multicast_setup(sc, sifp, imf, im6f);
3078 		if (error) {
3079 			if_rele(sifp);
3080 			PFSYNC_UNLOCK(sc);
3081 #ifdef INET
3082 			if (imf != NULL)
3083 				ip_mfilter_free(imf);
3084 #endif
3085 #ifdef INET6
3086 			if (im6f != NULL)
3087 				ip6_mfilter_free(im6f);
3088 #endif
3089 			return (error);
3090 		}
3091 	}
3092 	if (sc->sc_sync_if)
3093 		if_rele(sc->sc_sync_if);
3094 	sc->sc_sync_if = sifp;
3095 
3096 	switch (sc->sc_sync_peer.ss_family) {
3097 #ifdef INET
3098 	case AF_INET: {
3099 		struct ip *ip;
3100 		ip = &sc->sc_template.ipv4;
3101 		bzero(ip, sizeof(*ip));
3102 		ip->ip_v = IPVERSION;
3103 		ip->ip_hl = sizeof(sc->sc_template.ipv4) >> 2;
3104 		ip->ip_tos = IPTOS_LOWDELAY;
3105 		/* len and id are set later. */
3106 		ip->ip_off = htons(IP_DF);
3107 		ip->ip_ttl = PFSYNC_DFLTTL;
3108 		ip->ip_p = IPPROTO_PFSYNC;
3109 		ip->ip_src.s_addr = INADDR_ANY;
3110 		ip->ip_dst = ((struct sockaddr_in *)&sc->sc_sync_peer)->sin_addr;
3111 		break;
3112 	}
3113 #endif
3114 #ifdef INET6
3115 	case AF_INET6: {
3116 		struct ip6_hdr *ip6;
3117 		ip6 = &sc->sc_template.ipv6;
3118 		bzero(ip6, sizeof(*ip6));
3119 		ip6->ip6_vfc = IPV6_VERSION;
3120 		ip6->ip6_hlim = PFSYNC_DFLTTL;
3121 		ip6->ip6_nxt = IPPROTO_PFSYNC;
3122 		ip6->ip6_dst = ((struct sockaddr_in6 *)&sc->sc_sync_peer)->sin6_addr;
3123 
3124 		struct epoch_tracker et;
3125 		NET_EPOCH_ENTER(et);
3126 		in6_selectsrc_addr(if_getfib(sc->sc_sync_if), &ip6->ip6_dst, 0,
3127 		    sc->sc_sync_if, &ip6->ip6_src, NULL);
3128 		NET_EPOCH_EXIT(et);
3129 		break;
3130 	}
3131 #endif
3132 	}
3133 
3134 	/* Request a full state table update. */
3135 	if ((sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
3136 		(*carp_demote_adj_p)(V_pfsync_carp_adj,
3137 		    "pfsync bulk start");
3138 	sc->sc_flags &= ~PFSYNCF_OK;
3139 	if (V_pf_status.debug >= PF_DEBUG_MISC)
3140 		printf("pfsync: requesting bulk update\n");
3141 	PFSYNC_UNLOCK(sc);
3142 	PFSYNC_BUCKET_LOCK(&sc->sc_buckets[0]);
3143 	pfsync_request_update(0, 0);
3144 	PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[0]);
3145 	PFSYNC_BLOCK(sc);
3146 	sc->sc_ureq_sent = time_uptime;
3147 	callout_reset(&sc->sc_bulkfail_tmo, 5 * hz, pfsync_bulk_fail, sc);
3148 	PFSYNC_BUNLOCK(sc);
3149 	return (0);
3150 }
3151 
3152 static void
pfsync_pointers_init(void)3153 pfsync_pointers_init(void)
3154 {
3155 
3156 	PF_RULES_WLOCK();
3157 	V_pfsync_state_import_ptr = pfsync_state_import;
3158 	V_pfsync_insert_state_ptr = pfsync_insert_state;
3159 	V_pfsync_update_state_ptr = pfsync_update_state;
3160 	V_pfsync_delete_state_ptr = pfsync_delete_state;
3161 	V_pfsync_clear_states_ptr = pfsync_clear_states;
3162 	V_pfsync_defer_ptr = pfsync_defer;
3163 	PF_RULES_WUNLOCK();
3164 }
3165 
3166 static void
pfsync_pointers_uninit(void)3167 pfsync_pointers_uninit(void)
3168 {
3169 
3170 	PF_RULES_WLOCK();
3171 	V_pfsync_state_import_ptr = NULL;
3172 	V_pfsync_insert_state_ptr = NULL;
3173 	V_pfsync_update_state_ptr = NULL;
3174 	V_pfsync_delete_state_ptr = NULL;
3175 	V_pfsync_clear_states_ptr = NULL;
3176 	V_pfsync_defer_ptr = NULL;
3177 	PF_RULES_WUNLOCK();
3178 }
3179 
3180 static void
vnet_pfsync_init(const void * unused __unused)3181 vnet_pfsync_init(const void *unused __unused)
3182 {
3183 	int error;
3184 
3185 	V_pfsync_cloner = if_clone_simple(pfsyncname,
3186 	    pfsync_clone_create, pfsync_clone_destroy, 1);
3187 	error = swi_add(&V_pfsync_swi_ie, pfsyncname, pfsyncintr, V_pfsyncif,
3188 	    SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
3189 	if (error) {
3190 		if_clone_detach(V_pfsync_cloner);
3191 		log(LOG_INFO, "swi_add() failed in %s\n", __func__);
3192 	}
3193 
3194 	pfsync_pointers_init();
3195 }
3196 VNET_SYSINIT(vnet_pfsync_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY,
3197     vnet_pfsync_init, NULL);
3198 
3199 static void
vnet_pfsync_uninit(const void * unused __unused)3200 vnet_pfsync_uninit(const void *unused __unused)
3201 {
3202 	int ret __diagused;
3203 
3204 	pfsync_pointers_uninit();
3205 
3206 	if_clone_detach(V_pfsync_cloner);
3207 	ret = swi_remove(V_pfsync_swi_cookie);
3208 	MPASS(ret == 0);
3209 	ret = intr_event_destroy(V_pfsync_swi_ie);
3210 	MPASS(ret == 0);
3211 }
3212 
3213 VNET_SYSUNINIT(vnet_pfsync_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_FOURTH,
3214     vnet_pfsync_uninit, NULL);
3215 
3216 static int
pfsync_init(void)3217 pfsync_init(void)
3218 {
3219 	int error;
3220 
3221 	pfsync_detach_ifnet_ptr = pfsync_detach_ifnet;
3222 
3223 #ifdef INET
3224 	error = ipproto_register(IPPROTO_PFSYNC, pfsync_input, NULL);
3225 	if (error)
3226 		return (error);
3227 #endif
3228 #ifdef INET6
3229 	error = ip6proto_register(IPPROTO_PFSYNC, pfsync6_input, NULL);
3230 	if (error) {
3231 		ipproto_unregister(IPPROTO_PFSYNC);
3232 		return (error);
3233 	}
3234 #endif
3235 
3236 	return (0);
3237 }
3238 
3239 static void
pfsync_uninit(void)3240 pfsync_uninit(void)
3241 {
3242 	pfsync_detach_ifnet_ptr = NULL;
3243 
3244 #ifdef INET
3245 	ipproto_unregister(IPPROTO_PFSYNC);
3246 #endif
3247 #ifdef INET6
3248 	ip6proto_unregister(IPPROTO_PFSYNC);
3249 #endif
3250 }
3251 
3252 static int
pfsync_modevent(module_t mod,int type,void * data)3253 pfsync_modevent(module_t mod, int type, void *data)
3254 {
3255 	int error = 0;
3256 
3257 	switch (type) {
3258 	case MOD_LOAD:
3259 		error = pfsync_init();
3260 		break;
3261 	case MOD_UNLOAD:
3262 		pfsync_uninit();
3263 		break;
3264 	default:
3265 		error = EINVAL;
3266 		break;
3267 	}
3268 
3269 	return (error);
3270 }
3271 
3272 static moduledata_t pfsync_mod = {
3273 	pfsyncname,
3274 	pfsync_modevent,
3275 	0
3276 };
3277 
3278 #define PFSYNC_MODVER 1
3279 
3280 /* Stay on FIREWALL as we depend on pf being initialized and on inetdomain. */
3281 DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY);
3282 MODULE_VERSION(pfsync, PFSYNC_MODVER);
3283 MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);
3284