xref: /openbsd-src/sys/net/pf.c (revision d59bb9942320b767f2a19aaa7690c8c6e30b724c)
1 /*	$OpenBSD: pf.c,v 1.1015 2017/02/09 15:19:32 jca Exp $ */
2 
3 /*
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002 - 2013 Henning Brauer <henning@openbsd.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  *
12  *    - Redistributions of source code must retain the above copyright
13  *      notice, this list of conditions and the following disclaimer.
14  *    - Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  * Effort sponsored in part by the Defense Advanced Research Projects
33  * Agency (DARPA) and Air Force Research Laboratory, Air Force
34  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
35  *
36  */
37 
38 #include "bpfilter.h"
39 #include "carp.h"
40 #include "pflog.h"
41 #include "pfsync.h"
42 #include "pflow.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/mbuf.h>
47 #include <sys/filio.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/kernel.h>
51 #include <sys/time.h>
52 #include <sys/pool.h>
53 #include <sys/proc.h>
54 #include <sys/rwlock.h>
55 #include <sys/syslog.h>
56 
57 #include <crypto/sha2.h>
58 
59 #include <net/if.h>
60 #include <net/if_var.h>
61 #include <net/if_types.h>
62 #include <net/route.h>
63 
64 #include <netinet/in.h>
65 #include <netinet/ip.h>
66 #include <netinet/in_pcb.h>
67 #include <netinet/ip_var.h>
68 #include <netinet/ip_icmp.h>
69 #include <netinet/icmp_var.h>
70 #include <netinet/tcp.h>
71 #include <netinet/tcp_seq.h>
72 #include <netinet/tcp_timer.h>
73 #include <netinet/tcp_var.h>
74 #include <netinet/tcp_fsm.h>
75 #include <netinet/udp.h>
76 #include <netinet/udp_var.h>
77 #include <netinet/ip_divert.h>
78 
79 #ifdef INET6
80 #include <netinet/ip6.h>
81 #include <netinet6/ip6_var.h>
82 #include <netinet/icmp6.h>
83 #include <netinet6/nd6.h>
84 #include <netinet6/ip6_divert.h>
85 #endif /* INET6 */
86 
87 #include <net/pfvar.h>
88 #include <net/pfvar_priv.h>
89 
90 #if NPFLOG > 0
91 #include <net/if_pflog.h>
92 #endif	/* NPFLOG > 0 */
93 
94 #if NPFLOW > 0
95 #include <net/if_pflow.h>
96 #endif	/* NPFLOW > 0 */
97 
98 #if NPFSYNC > 0
99 #include <net/if_pfsync.h>
100 #endif /* NPFSYNC > 0 */
101 
102 #ifdef DDB
103 #include <machine/db_machdep.h>
104 #include <ddb/db_interface.h>
105 #endif
106 
107 /*
108  * Global variables
109  */
110 struct pf_state_tree	 pf_statetbl;
111 struct pf_queuehead	 pf_queues[2];
112 struct pf_queuehead	*pf_queues_active;
113 struct pf_queuehead	*pf_queues_inactive;
114 
115 struct pf_status	 pf_status;
116 
117 SHA2_CTX		 pf_tcp_secret_ctx;
118 u_char			 pf_tcp_secret[16];
119 int			 pf_tcp_secret_init;
120 int			 pf_tcp_iss_off;
121 
122 struct pf_anchor_stackframe {
123 	struct pf_ruleset			*rs;
124 	struct pf_rule				*r;
125 	struct pf_anchor_node			*parent;
126 	struct pf_anchor			*child;
127 } pf_anchor_stack[64];
128 
129 struct pool		 pf_src_tree_pl, pf_rule_pl, pf_queue_pl;
130 struct pool		 pf_state_pl, pf_state_key_pl, pf_state_item_pl;
131 struct pool		 pf_rule_item_pl, pf_sn_item_pl;
132 
133 void			 pf_init_threshold(struct pf_threshold *, u_int32_t,
134 			    u_int32_t);
135 void			 pf_add_threshold(struct pf_threshold *);
136 int			 pf_check_threshold(struct pf_threshold *);
137 int			 pf_check_tcp_cksum(struct mbuf *, int, int,
138 			    sa_family_t);
139 static __inline void	 pf_cksum_fixup(u_int16_t *, u_int16_t, u_int16_t,
140 			    u_int8_t);
141 void			 pf_cksum_fixup_a(u_int16_t *, const struct pf_addr *,
142 			    const struct pf_addr *, sa_family_t, u_int8_t);
143 int			 pf_modulate_sack(struct pf_pdesc *,
144 			    struct pf_state_peer *);
145 int			 pf_icmp_mapping(struct pf_pdesc *, u_int8_t, int *,
146 			    u_int16_t *, u_int16_t *);
147 int			 pf_change_icmp_af(struct mbuf *, int,
148 			    struct pf_pdesc *, struct pf_pdesc *,
149 			    struct pf_addr *, struct pf_addr *, sa_family_t,
150 			    sa_family_t);
151 int			 pf_translate_a(struct pf_pdesc *, struct pf_addr *,
152 			    struct pf_addr *);
153 void			 pf_translate_icmp(struct pf_pdesc *, struct pf_addr *,
154 			    u_int16_t *, struct pf_addr *, struct pf_addr *,
155 			    u_int16_t);
156 int			 pf_translate_icmp_af(struct pf_pdesc*, int, void *);
157 void			 pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
158 			    sa_family_t, struct pf_rule *, u_int);
159 void			 pf_detach_state(struct pf_state *);
160 void			 pf_state_key_detach(struct pf_state *, int);
161 u_int32_t		 pf_tcp_iss(struct pf_pdesc *);
162 void			 pf_rule_to_actions(struct pf_rule *,
163 			    struct pf_rule_actions *);
164 int			 pf_test_rule(struct pf_pdesc *, struct pf_rule **,
165 			    struct pf_state **, struct pf_rule **,
166 			    struct pf_ruleset **, u_short *);
167 static __inline int	 pf_create_state(struct pf_pdesc *, struct pf_rule *,
168 			    struct pf_rule *, struct pf_rule *,
169 			    struct pf_state_key **, struct pf_state_key **,
170 			    int *, struct pf_state **, int,
171 			    struct pf_rule_slist *, struct pf_rule_actions *,
172 			    struct pf_src_node *[]);
173 static __inline int	 pf_state_key_addr_setup(struct pf_pdesc *, void *,
174 			    int, struct pf_addr *, int, struct pf_addr *,
175 			    int, int);
176 int			 pf_state_key_setup(struct pf_pdesc *, struct
177 			    pf_state_key **, struct pf_state_key **, int);
178 int			 pf_tcp_track_full(struct pf_pdesc *,
179 			    struct pf_state_peer *, struct pf_state_peer *,
180 			    struct pf_state **, u_short *, int *);
181 int			 pf_tcp_track_sloppy(struct pf_pdesc *,
182 			    struct pf_state_peer *, struct pf_state_peer *,
183 			    struct pf_state **, u_short *);
184 static __inline int	 pf_synproxy(struct pf_pdesc *, struct pf_state **,
185 			    u_short *);
186 int			 pf_test_state(struct pf_pdesc *, struct pf_state **,
187 			    u_short *);
188 int			 pf_icmp_state_lookup(struct pf_pdesc *,
189 			    struct pf_state_key_cmp *, struct pf_state **,
190 			    u_int16_t, u_int16_t, int, int *, int, int);
191 int			 pf_test_state_icmp(struct pf_pdesc *,
192 			    struct pf_state **, u_short *);
193 u_int8_t		 pf_get_wscale(struct pf_pdesc *);
194 u_int16_t		 pf_get_mss(struct pf_pdesc *);
195 u_int16_t		 pf_calc_mss(struct pf_addr *, sa_family_t, int,
196 			    u_int16_t);
197 static __inline int	 pf_set_rt_ifp(struct pf_state *, struct pf_addr *,
198 			    sa_family_t);
199 struct pf_divert	*pf_get_divert(struct mbuf *);
200 int			 pf_walk_option6(struct pf_pdesc *, struct ip6_hdr *,
201 			    int, int, u_short *);
202 int			 pf_walk_header6(struct pf_pdesc *, struct ip6_hdr *,
203 			    u_short *);
204 void			 pf_print_state_parts(struct pf_state *,
205 			    struct pf_state_key *, struct pf_state_key *);
206 int			 pf_addr_wrap_neq(struct pf_addr_wrap *,
207 			    struct pf_addr_wrap *);
208 int			 pf_compare_state_keys(struct pf_state_key *,
209 			    struct pf_state_key *, struct pfi_kif *, u_int);
210 struct pf_state		*pf_find_state(struct pfi_kif *,
211 			    struct pf_state_key_cmp *, u_int, struct mbuf *);
212 int			 pf_src_connlimit(struct pf_state **);
213 int			 pf_match_rcvif(struct mbuf *, struct pf_rule *);
214 void			 pf_step_into_anchor(int *, struct pf_ruleset **,
215 			    struct pf_rule **, struct pf_rule **);
216 int			 pf_step_out_of_anchor(int *, struct pf_ruleset **,
217 			     struct pf_rule **, struct pf_rule **,
218 			     int *);
219 void			 pf_counters_inc(int, struct pf_pdesc *,
220 			    struct pf_state *, struct pf_rule *,
221 			    struct pf_rule *);
222 void			 pf_state_key_link(struct pf_state_key *,
223 			    struct pf_state_key *);
224 void			 pf_inpcb_unlink_state_key(struct inpcb *);
225 void			 pf_state_key_unlink_reverse(struct pf_state_key *);
226 
227 #if NPFLOG > 0
228 void			 pf_log_matches(struct pf_pdesc *, struct pf_rule *,
229 			    struct pf_rule *, struct pf_ruleset *,
230 			    struct pf_rule_slist *);
231 #endif	/* NPFLOG > 0 */
232 
233 extern struct pool pfr_ktable_pl;
234 extern struct pool pfr_kentry_pl;
235 
236 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
237 	{ &pf_state_pl, PFSTATE_HIWAT, PFSTATE_HIWAT },
238 	{ &pf_src_tree_pl, PFSNODE_HIWAT, PFSNODE_HIWAT },
239 	{ &pf_frent_pl, PFFRAG_FRENT_HIWAT, PFFRAG_FRENT_HIWAT },
240 	{ &pfr_ktable_pl, PFR_KTABLE_HIWAT, PFR_KTABLE_HIWAT },
241 	{ &pfr_kentry_pl, PFR_KENTRY_HIWAT, PFR_KENTRY_HIWAT }
242 };
243 
244 #define STATE_LOOKUP(i, k, d, s, m)					\
245 	do {								\
246 		s = pf_find_state(i, k, d, m);				\
247 		if (s == NULL || (s)->timeout == PFTM_PURGE)		\
248 			return (PF_DROP);				\
249 		if (d == PF_OUT &&					\
250 		    (((s)->rule.ptr->rt == PF_ROUTETO &&		\
251 		    (s)->rule.ptr->direction == PF_OUT) ||		\
252 		    ((s)->rule.ptr->rt == PF_REPLYTO &&			\
253 		    (s)->rule.ptr->direction == PF_IN)) &&		\
254 		    (s)->rt_kif != NULL &&				\
255 		    (s)->rt_kif != i)					\
256 			return (PF_PASS);				\
257 	} while (0)
258 
259 #define BOUND_IFACE(r, k) \
260 	((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
261 
262 #define STATE_INC_COUNTERS(s)					\
263 	do {							\
264 		struct pf_rule_item *mrm;			\
265 		s->rule.ptr->states_cur++;			\
266 		s->rule.ptr->states_tot++;			\
267 		if (s->anchor.ptr != NULL) {			\
268 			s->anchor.ptr->states_cur++;		\
269 			s->anchor.ptr->states_tot++;		\
270 		}						\
271 		SLIST_FOREACH(mrm, &s->match_rules, entry)	\
272 			mrm->r->states_cur++;			\
273 	} while (0)
274 
275 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
276 static __inline int pf_state_compare_key(struct pf_state_key *,
277 	struct pf_state_key *);
278 static __inline int pf_state_compare_id(struct pf_state *,
279 	struct pf_state *);
280 static __inline void pf_cksum_uncover(u_int16_t *, u_int16_t, u_int8_t);
281 static __inline void pf_cksum_cover(u_int16_t *, u_int16_t, u_int8_t);
282 
283 struct pf_src_tree tree_src_tracking;
284 
285 struct pf_state_tree_id tree_id;
286 struct pf_state_queue state_list;
287 
288 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
289 RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
290 RB_GENERATE(pf_state_tree_id, pf_state,
291     entry_id, pf_state_compare_id);
292 
293 SLIST_HEAD(pf_rule_gcl, pf_rule)	pf_rule_gcl =
294 	SLIST_HEAD_INITIALIZER(pf_rule_gcl);
295 
296 __inline int
297 pf_addr_compare(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
298 {
299 	switch (af) {
300 	case AF_INET:
301 		if (a->addr32[0] > b->addr32[0])
302 			return (1);
303 		if (a->addr32[0] < b->addr32[0])
304 			return (-1);
305 		break;
306 #ifdef INET6
307 	case AF_INET6:
308 		if (a->addr32[3] > b->addr32[3])
309 			return (1);
310 		if (a->addr32[3] < b->addr32[3])
311 			return (-1);
312 		if (a->addr32[2] > b->addr32[2])
313 			return (1);
314 		if (a->addr32[2] < b->addr32[2])
315 			return (-1);
316 		if (a->addr32[1] > b->addr32[1])
317 			return (1);
318 		if (a->addr32[1] < b->addr32[1])
319 			return (-1);
320 		if (a->addr32[0] > b->addr32[0])
321 			return (1);
322 		if (a->addr32[0] < b->addr32[0])
323 			return (-1);
324 		break;
325 #endif /* INET6 */
326 	}
327 	return (0);
328 }
329 
330 static __inline int
331 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
332 {
333 	int	diff;
334 
335 	if (a->rule.ptr > b->rule.ptr)
336 		return (1);
337 	if (a->rule.ptr < b->rule.ptr)
338 		return (-1);
339 	if ((diff = a->type - b->type) != 0)
340 		return (diff);
341 	if ((diff = a->af - b->af) != 0)
342 		return (diff);
343 	if ((diff = pf_addr_compare(&a->addr, &b->addr, a->af)) != 0)
344 		return (diff);
345 	return (0);
346 }
347 
348 void
349 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
350 {
351 	switch (af) {
352 	case AF_INET:
353 		dst->addr32[0] = src->addr32[0];
354 		break;
355 #ifdef INET6
356 	case AF_INET6:
357 		dst->addr32[0] = src->addr32[0];
358 		dst->addr32[1] = src->addr32[1];
359 		dst->addr32[2] = src->addr32[2];
360 		dst->addr32[3] = src->addr32[3];
361 		break;
362 #endif /* INET6 */
363 	default:
364 		unhandled_af(af);
365 	}
366 }
367 
368 void
369 pf_init_threshold(struct pf_threshold *threshold,
370     u_int32_t limit, u_int32_t seconds)
371 {
372 	threshold->limit = limit * PF_THRESHOLD_MULT;
373 	threshold->seconds = seconds;
374 	threshold->count = 0;
375 	threshold->last = time_uptime;
376 }
377 
378 void
379 pf_add_threshold(struct pf_threshold *threshold)
380 {
381 	u_int32_t t = time_uptime, diff = t - threshold->last;
382 
383 	if (diff >= threshold->seconds)
384 		threshold->count = 0;
385 	else
386 		threshold->count -= threshold->count * diff /
387 		    threshold->seconds;
388 	threshold->count += PF_THRESHOLD_MULT;
389 	threshold->last = t;
390 }
391 
392 int
393 pf_check_threshold(struct pf_threshold *threshold)
394 {
395 	return (threshold->count > threshold->limit);
396 }
397 
398 int
399 pf_src_connlimit(struct pf_state **state)
400 {
401 	int			 bad = 0;
402 	struct pf_src_node	*sn;
403 
404 	if ((sn = pf_get_src_node((*state), PF_SN_NONE)) == NULL)
405 		return (0);
406 
407 	sn->conn++;
408 	(*state)->src.tcp_est = 1;
409 	pf_add_threshold(&sn->conn_rate);
410 
411 	if ((*state)->rule.ptr->max_src_conn &&
412 	    (*state)->rule.ptr->max_src_conn < sn->conn) {
413 		pf_status.lcounters[LCNT_SRCCONN]++;
414 		bad++;
415 	}
416 
417 	if ((*state)->rule.ptr->max_src_conn_rate.limit &&
418 	    pf_check_threshold(&sn->conn_rate)) {
419 		pf_status.lcounters[LCNT_SRCCONNRATE]++;
420 		bad++;
421 	}
422 
423 	if (!bad)
424 		return (0);
425 
426 	if ((*state)->rule.ptr->overload_tbl) {
427 		struct pfr_addr p;
428 		u_int32_t	killed = 0;
429 
430 		pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
431 		if (pf_status.debug >= LOG_NOTICE) {
432 			log(LOG_NOTICE,
433 			    "pf: pf_src_connlimit: blocking address ");
434 			pf_print_host(&sn->addr, 0,
435 			    (*state)->key[PF_SK_WIRE]->af);
436 		}
437 
438 		bzero(&p, sizeof(p));
439 		p.pfra_af = (*state)->key[PF_SK_WIRE]->af;
440 		switch ((*state)->key[PF_SK_WIRE]->af) {
441 		case AF_INET:
442 			p.pfra_net = 32;
443 			p.pfra_ip4addr = sn->addr.v4;
444 			break;
445 #ifdef INET6
446 		case AF_INET6:
447 			p.pfra_net = 128;
448 			p.pfra_ip6addr = sn->addr.v6;
449 			break;
450 #endif /* INET6 */
451 		}
452 
453 		pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
454 		    &p, time_second);
455 
456 		/* kill existing states if that's required. */
457 		if ((*state)->rule.ptr->flush) {
458 			struct pf_state_key *sk;
459 			struct pf_state *st;
460 
461 			pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
462 			RB_FOREACH(st, pf_state_tree_id, &tree_id) {
463 				sk = st->key[PF_SK_WIRE];
464 				/*
465 				 * Kill states from this source.  (Only those
466 				 * from the same rule if PF_FLUSH_GLOBAL is not
467 				 * set)
468 				 */
469 				if (sk->af ==
470 				    (*state)->key[PF_SK_WIRE]->af &&
471 				    (((*state)->direction == PF_OUT &&
472 				    PF_AEQ(&sn->addr, &sk->addr[1], sk->af)) ||
473 				    ((*state)->direction == PF_IN &&
474 				    PF_AEQ(&sn->addr, &sk->addr[0], sk->af))) &&
475 				    ((*state)->rule.ptr->flush &
476 				    PF_FLUSH_GLOBAL ||
477 				    (*state)->rule.ptr == st->rule.ptr)) {
478 					st->timeout = PFTM_PURGE;
479 					st->src.state = st->dst.state =
480 					    TCPS_CLOSED;
481 					killed++;
482 				}
483 			}
484 			if (pf_status.debug >= LOG_NOTICE)
485 				addlog(", %u states killed", killed);
486 		}
487 		if (pf_status.debug >= LOG_NOTICE)
488 			addlog("\n");
489 	}
490 
491 	/* kill this state */
492 	(*state)->timeout = PFTM_PURGE;
493 	(*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
494 	return (1);
495 }
496 
497 int
498 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
499     enum pf_sn_types type, sa_family_t af, struct pf_addr *src,
500     struct pf_addr *raddr)
501 {
502 	struct pf_src_node	k;
503 
504 	if (*sn == NULL) {
505 		k.af = af;
506 		k.type = type;
507 		PF_ACPY(&k.addr, src, af);
508 		k.rule.ptr = rule;
509 		pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
510 		*sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
511 	}
512 	if (*sn == NULL) {
513 		if (!rule->max_src_nodes ||
514 		    rule->src_nodes < rule->max_src_nodes)
515 			(*sn) = pool_get(&pf_src_tree_pl, PR_NOWAIT | PR_ZERO);
516 		else
517 			pf_status.lcounters[LCNT_SRCNODES]++;
518 		if ((*sn) == NULL)
519 			return (-1);
520 
521 		pf_init_threshold(&(*sn)->conn_rate,
522 		    rule->max_src_conn_rate.limit,
523 		    rule->max_src_conn_rate.seconds);
524 
525 		(*sn)->type = type;
526 		(*sn)->af = af;
527 		(*sn)->rule.ptr = rule;
528 		PF_ACPY(&(*sn)->addr, src, af);
529 		if (raddr)
530 			PF_ACPY(&(*sn)->raddr, raddr, af);
531 		if (RB_INSERT(pf_src_tree,
532 		    &tree_src_tracking, *sn) != NULL) {
533 			if (pf_status.debug >= LOG_NOTICE) {
534 				log(LOG_NOTICE,
535 				    "pf: src_tree insert failed: ");
536 				pf_print_host(&(*sn)->addr, 0, af);
537 				addlog("\n");
538 			}
539 			pool_put(&pf_src_tree_pl, *sn);
540 			return (-1);
541 		}
542 		(*sn)->creation = time_uptime;
543 		(*sn)->rule.ptr->src_nodes++;
544 		pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
545 		pf_status.src_nodes++;
546 	} else {
547 		if (rule->max_src_states &&
548 		    (*sn)->states >= rule->max_src_states) {
549 			pf_status.lcounters[LCNT_SRCSTATES]++;
550 			return (-1);
551 		}
552 	}
553 	return (0);
554 }
555 
556 void
557 pf_remove_src_node(struct pf_src_node *sn)
558 {
559 	if (sn->states > 0 || sn->expire > time_uptime)
560 		return;
561 
562 	sn->rule.ptr->src_nodes--;
563 	if (sn->rule.ptr->states_cur == 0 &&
564 	    sn->rule.ptr->src_nodes == 0)
565 		pf_rm_rule(NULL, sn->rule.ptr);
566 	RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
567 	pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
568 	pf_status.src_nodes--;
569 	pool_put(&pf_src_tree_pl, sn);
570 }
571 
572 struct pf_src_node *
573 pf_get_src_node(struct pf_state *s, enum pf_sn_types type)
574 {
575 	struct pf_sn_item	*sni;
576 
577 	SLIST_FOREACH(sni, &s->src_nodes, next)
578 		if (sni->sn->type == type)
579 			return (sni->sn);
580 	return (NULL);
581 }
582 
583 void
584 pf_state_rm_src_node(struct pf_state *s, struct pf_src_node *sn)
585 {
586 	struct pf_sn_item	*sni, *snin, *snip = NULL;
587 
588 	for (sni = SLIST_FIRST(&s->src_nodes); sni; sni = snin) {
589 		snin = SLIST_NEXT(sni, next);
590 		if (sni->sn == sn) {
591 			if (snip)
592 				SLIST_REMOVE_AFTER(snip, next);
593 			else
594 				SLIST_REMOVE_HEAD(&s->src_nodes, next);
595 			pool_put(&pf_sn_item_pl, sni);
596 			sni = NULL;
597 			sn->states--;
598 		}
599 		if (sni != NULL)
600 			snip = sni;
601 	}
602 }
603 
604 /* state table stuff */
605 
606 static __inline int
607 pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
608 {
609 	int	diff;
610 
611 	if ((diff = a->proto - b->proto) != 0)
612 		return (diff);
613 	if ((diff = a->af - b->af) != 0)
614 		return (diff);
615 	if ((diff = pf_addr_compare(&a->addr[0], &b->addr[0], a->af)) != 0)
616 		return (diff);
617 	if ((diff = pf_addr_compare(&a->addr[1], &b->addr[1], a->af)) != 0)
618 		return (diff);
619 	if ((diff = a->port[0] - b->port[0]) != 0)
620 		return (diff);
621 	if ((diff = a->port[1] - b->port[1]) != 0)
622 		return (diff);
623 	if ((diff = a->rdomain - b->rdomain) != 0)
624 		return (diff);
625 	return (0);
626 }
627 
628 static __inline int
629 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
630 {
631 	if (a->id > b->id)
632 		return (1);
633 	if (a->id < b->id)
634 		return (-1);
635 	if (a->creatorid > b->creatorid)
636 		return (1);
637 	if (a->creatorid < b->creatorid)
638 		return (-1);
639 
640 	return (0);
641 }
642 
643 int
644 pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
645 {
646 	struct pf_state_item	*si;
647 	struct pf_state_key     *cur;
648 	struct pf_state		*olds = NULL;
649 
650 	KASSERT(s->key[idx] == NULL);
651 	if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl, sk)) != NULL) {
652 		/* key exists. check for same kif, if none, add to key */
653 		TAILQ_FOREACH(si, &cur->states, entry)
654 			if (si->s->kif == s->kif &&
655 			    ((si->s->key[PF_SK_WIRE]->af == sk->af &&
656 			     si->s->direction == s->direction) ||
657 			    (si->s->key[PF_SK_WIRE]->af !=
658 			     si->s->key[PF_SK_STACK]->af &&
659 			     sk->af == si->s->key[PF_SK_STACK]->af &&
660 			     si->s->direction != s->direction))) {
661 				int reuse = 0;
662 
663 				if (sk->proto == IPPROTO_TCP &&
664 				    si->s->src.state >= TCPS_FIN_WAIT_2 &&
665 				    si->s->dst.state >= TCPS_FIN_WAIT_2)
666 					reuse = 1;
667 				if (pf_status.debug >= LOG_NOTICE) {
668 					log(LOG_NOTICE,
669 					    "pf: %s key attach %s on %s: ",
670 					    (idx == PF_SK_WIRE) ?
671 					    "wire" : "stack",
672 					    reuse ? "reuse" : "failed",
673 					    s->kif->pfik_name);
674 					pf_print_state_parts(s,
675 					    (idx == PF_SK_WIRE) ?  sk : NULL,
676 					    (idx == PF_SK_STACK) ?  sk : NULL);
677 					addlog(", existing: ");
678 					pf_print_state_parts(si->s,
679 					    (idx == PF_SK_WIRE) ?  sk : NULL,
680 					    (idx == PF_SK_STACK) ?  sk : NULL);
681 					addlog("\n");
682 				}
683 				if (reuse) {
684 					si->s->src.state = si->s->dst.state =
685 					    TCPS_CLOSED;
686 					/* remove late or sks can go away */
687 					olds = si->s;
688 				} else {
689 					pool_put(&pf_state_key_pl, sk);
690 					return (-1);	/* collision! */
691 				}
692 			}
693 		pool_put(&pf_state_key_pl, sk);
694 		s->key[idx] = cur;
695 	} else
696 		s->key[idx] = sk;
697 
698 	if ((si = pool_get(&pf_state_item_pl, PR_NOWAIT)) == NULL) {
699 		pf_state_key_detach(s, idx);
700 		return (-1);
701 	}
702 	si->s = s;
703 
704 	/* list is sorted, if-bound states before floating */
705 	if (s->kif == pfi_all)
706 		TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
707 	else
708 		TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
709 
710 	if (olds)
711 		pf_remove_state(olds);
712 
713 	return (0);
714 }
715 
716 void
717 pf_detach_state(struct pf_state *s)
718 {
719 	if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
720 		s->key[PF_SK_WIRE] = NULL;
721 
722 	if (s->key[PF_SK_STACK] != NULL)
723 		pf_state_key_detach(s, PF_SK_STACK);
724 
725 	if (s->key[PF_SK_WIRE] != NULL)
726 		pf_state_key_detach(s, PF_SK_WIRE);
727 }
728 
729 void
730 pf_state_key_detach(struct pf_state *s, int idx)
731 {
732 	struct pf_state_item	*si;
733 	struct pf_state_key	*sk;
734 
735 	if (s->key[idx] == NULL)
736 		return;
737 
738 	si = TAILQ_FIRST(&s->key[idx]->states);
739 	while (si && si->s != s)
740 	    si = TAILQ_NEXT(si, entry);
741 
742 	if (si) {
743 		TAILQ_REMOVE(&s->key[idx]->states, si, entry);
744 		pool_put(&pf_state_item_pl, si);
745 	}
746 
747 	sk = s->key[idx];
748 	s->key[idx] = NULL;
749 	if (TAILQ_EMPTY(&sk->states)) {
750 		RB_REMOVE(pf_state_tree, &pf_statetbl, sk);
751 		sk->removed = 1;
752 		pf_state_key_unlink_reverse(sk);
753 		pf_inpcb_unlink_state_key(sk->inp);
754 		pf_state_key_unref(sk);
755 	}
756 }
757 
758 struct pf_state_key *
759 pf_alloc_state_key(int pool_flags)
760 {
761 	struct pf_state_key	*sk;
762 
763 	if ((sk = pool_get(&pf_state_key_pl, pool_flags)) == NULL)
764 		return (NULL);
765 	TAILQ_INIT(&sk->states);
766 
767 	return (sk);
768 }
769 
770 static __inline int
771 pf_state_key_addr_setup(struct pf_pdesc *pd, void *arg, int sidx,
772     struct pf_addr *saddr, int didx, struct pf_addr *daddr, int af, int multi)
773 {
774 	struct pf_state_key_cmp *key = arg;
775 #ifdef INET6
776 	struct pf_addr *target;
777 
778 	if (af == AF_INET || pd->proto != IPPROTO_ICMPV6)
779 		goto copy;
780 
781 	switch (pd->hdr.icmp6.icmp6_type) {
782 	case ND_NEIGHBOR_SOLICIT:
783 		if (multi)
784 			return (-1);
785 		target = (struct pf_addr *)&pd->hdr.nd_ns.nd_ns_target;
786 		daddr = target;
787 		break;
788 	case ND_NEIGHBOR_ADVERT:
789 		if (multi)
790 			return (-1);
791 		target = (struct pf_addr *)&pd->hdr.nd_ns.nd_ns_target;
792 		saddr = target;
793 		if (IN6_IS_ADDR_MULTICAST(&pd->dst->v6)) {
794 			key->addr[didx].addr32[0] = 0;
795 			key->addr[didx].addr32[1] = 0;
796 			key->addr[didx].addr32[2] = 0;
797 			key->addr[didx].addr32[3] = 0;
798 			daddr = NULL; /* overwritten */
799 		}
800 		break;
801 	default:
802 		if (multi) {
803 			key->addr[sidx].addr32[0] = __IPV6_ADDR_INT32_MLL;
804 			key->addr[sidx].addr32[1] = 0;
805 			key->addr[sidx].addr32[2] = 0;
806 			key->addr[sidx].addr32[3] = __IPV6_ADDR_INT32_ONE;
807 			saddr = NULL; /* overwritten */
808 		}
809 	}
810  copy:
811 #endif	/* INET6 */
812 	if (saddr)
813 		PF_ACPY(&key->addr[sidx], saddr, af);
814 	if (daddr)
815 		PF_ACPY(&key->addr[didx], daddr, af);
816 
817 	return (0);
818 }
819 
820 int
821 pf_state_key_setup(struct pf_pdesc *pd, struct pf_state_key **skw,
822     struct pf_state_key **sks, int rtableid)
823 {
824 	/* if returning error we MUST pool_put state keys ourselves */
825 	struct pf_state_key *sk1, *sk2;
826 	u_int wrdom = pd->rdomain;
827 	int afto = pd->af != pd->naf;
828 
829 	if ((sk1 = pf_alloc_state_key(PR_NOWAIT | PR_ZERO)) == NULL)
830 		return (ENOMEM);
831 
832 	pf_state_key_addr_setup(pd, sk1, pd->sidx, pd->src, pd->didx, pd->dst,
833 	    pd->af, 0);
834 	sk1->port[pd->sidx] = pd->osport;
835 	sk1->port[pd->didx] = pd->odport;
836 	sk1->proto = pd->proto;
837 	sk1->af = pd->af;
838 	sk1->rdomain = pd->rdomain;
839 	PF_REF_INIT(sk1->refcnt);
840 	sk1->removed = 0;
841 	if (rtableid >= 0)
842 		wrdom = rtable_l2(rtableid);
843 
844 	if (PF_ANEQ(&pd->nsaddr, pd->src, pd->af) ||
845 	    PF_ANEQ(&pd->ndaddr, pd->dst, pd->af) ||
846 	    pd->nsport != pd->osport || pd->ndport != pd->odport ||
847 	    wrdom != pd->rdomain || afto) {	/* NAT/NAT64 */
848 		if ((sk2 = pf_alloc_state_key(PR_NOWAIT | PR_ZERO)) == NULL) {
849 			pool_put(&pf_state_key_pl, sk1);
850 			return (ENOMEM);
851 		}
852 		pf_state_key_addr_setup(pd, sk2, afto ? pd->didx : pd->sidx,
853 		    &pd->nsaddr, afto ? pd->sidx : pd->didx, &pd->ndaddr,
854 		    pd->naf, 0);
855 		sk2->port[afto ? pd->didx : pd->sidx] = pd->nsport;
856 		sk2->port[afto ? pd->sidx : pd->didx] = pd->ndport;
857 		if (afto) {
858 			switch (pd->proto) {
859 			case IPPROTO_ICMP:
860 				sk2->proto = IPPROTO_ICMPV6;
861 				break;
862 			case IPPROTO_ICMPV6:
863 				sk2->proto = IPPROTO_ICMP;
864 				break;
865 			default:
866 				sk2->proto = pd->proto;
867 			}
868 		} else
869 			sk2->proto = pd->proto;
870 		sk2->af = pd->naf;
871 		sk2->rdomain = wrdom;
872 		PF_REF_INIT(sk2->refcnt);
873 		sk2->removed = 0;
874 	} else
875 		sk2 = sk1;
876 
877 	if (pd->dir == PF_IN) {
878 		*skw = sk1;
879 		*sks = sk2;
880 	} else {
881 		*sks = sk1;
882 		*skw = sk2;
883 	}
884 
885 	if (pf_status.debug >= LOG_DEBUG) {
886 		log(LOG_DEBUG, "pf: key setup: ");
887 		pf_print_state_parts(NULL, *skw, *sks);
888 		addlog("\n");
889 	}
890 
891 	return (0);
892 }
893 
894 int
895 pf_state_insert(struct pfi_kif *kif, struct pf_state_key **skw,
896     struct pf_state_key **sks, struct pf_state *s)
897 {
898 	splsoftassert(IPL_SOFTNET);
899 
900 	s->kif = kif;
901 	if (*skw == *sks) {
902 		if (pf_state_key_attach(*skw, s, PF_SK_WIRE))
903 			return (-1);
904 		*skw = *sks = s->key[PF_SK_WIRE];
905 		s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
906 	} else {
907 		if (pf_state_key_attach(*skw, s, PF_SK_WIRE)) {
908 			pool_put(&pf_state_key_pl, *sks);
909 			return (-1);
910 		}
911 		*skw = s->key[PF_SK_WIRE];
912 		if (pf_state_key_attach(*sks, s, PF_SK_STACK)) {
913 			pf_state_key_detach(s, PF_SK_WIRE);
914 			return (-1);
915 		}
916 		*sks = s->key[PF_SK_STACK];
917 	}
918 
919 	if (s->id == 0 && s->creatorid == 0) {
920 		s->id = htobe64(pf_status.stateid++);
921 		s->creatorid = pf_status.hostid;
922 	}
923 	if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
924 		if (pf_status.debug >= LOG_NOTICE) {
925 			log(LOG_NOTICE, "pf: state insert failed: "
926 			    "id: %016llx creatorid: %08x",
927 			    betoh64(s->id), ntohl(s->creatorid));
928 			addlog("\n");
929 		}
930 		pf_detach_state(s);
931 		return (-1);
932 	}
933 	TAILQ_INSERT_TAIL(&state_list, s, entry_list);
934 	pf_status.fcounters[FCNT_STATE_INSERT]++;
935 	pf_status.states++;
936 	pfi_kif_ref(kif, PFI_KIF_REF_STATE);
937 #if NPFSYNC > 0
938 	pfsync_insert_state(s);
939 #endif	/* NPFSYNC > 0 */
940 	return (0);
941 }
942 
943 struct pf_state *
944 pf_find_state_byid(struct pf_state_cmp *key)
945 {
946 	pf_status.fcounters[FCNT_STATE_SEARCH]++;
947 
948 	return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
949 }
950 
951 int
952 pf_compare_state_keys(struct pf_state_key *a, struct pf_state_key *b,
953     struct pfi_kif *kif, u_int dir)
954 {
955 	/* a (from hdr) and b (new) must be exact opposites of each other */
956 	if (a->af == b->af && a->proto == b->proto &&
957 	    PF_AEQ(&a->addr[0], &b->addr[1], a->af) &&
958 	    PF_AEQ(&a->addr[1], &b->addr[0], a->af) &&
959 	    a->port[0] == b->port[1] &&
960 	    a->port[1] == b->port[0] && a->rdomain == b->rdomain)
961 		return (0);
962 	else {
963 		/* mismatch. must not happen. */
964 		if (pf_status.debug >= LOG_ERR) {
965 			log(LOG_ERR,
966 			    "pf: state key linking mismatch! dir=%s, "
967 			    "if=%s, stored af=%u, a0: ",
968 			    dir == PF_OUT ? "OUT" : "IN",
969 			    kif->pfik_name, a->af);
970 			pf_print_host(&a->addr[0], a->port[0], a->af);
971 			addlog(", a1: ");
972 			pf_print_host(&a->addr[1], a->port[1], a->af);
973 			addlog(", proto=%u", a->proto);
974 			addlog(", found af=%u, a0: ", b->af);
975 			pf_print_host(&b->addr[0], b->port[0], b->af);
976 			addlog(", a1: ");
977 			pf_print_host(&b->addr[1], b->port[1], b->af);
978 			addlog(", proto=%u", b->proto);
979 			addlog("\n");
980 		}
981 		return (-1);
982 	}
983 }
984 
985 struct pf_state *
986 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
987     struct mbuf *m)
988 {
989 	struct pf_state_key	*sk, *pkt_sk, *inp_sk;
990 	struct pf_state_item	*si;
991 
992 	pf_status.fcounters[FCNT_STATE_SEARCH]++;
993 	if (pf_status.debug >= LOG_DEBUG) {
994 		log(LOG_DEBUG, "pf: key search, if=%s: ", kif->pfik_name);
995 		pf_print_state_parts(NULL, (struct pf_state_key *)key, NULL);
996 		addlog("\n");
997 	}
998 
999 	inp_sk = NULL;
1000 	pkt_sk = NULL;
1001 	sk = NULL;
1002 	if (dir == PF_OUT) {
1003 		/* first if block deals with outbound forwarded packet */
1004 		pkt_sk = m->m_pkthdr.pf.statekey;
1005 
1006 		if (!pf_state_key_isvalid(pkt_sk)) {
1007 			pf_pkt_unlink_state_key(m);
1008 			pkt_sk = NULL;
1009 		}
1010 
1011 		if (pkt_sk && pf_state_key_isvalid(pkt_sk->reverse))
1012 			sk = pkt_sk->reverse;
1013 
1014 		if (pkt_sk == NULL) {
1015 			/* here we deal with local outbound packet */
1016 			if (m->m_pkthdr.pf.inp != NULL) {
1017 				inp_sk = m->m_pkthdr.pf.inp->inp_pf_sk;
1018 				if (pf_state_key_isvalid(inp_sk))
1019 					sk = inp_sk;
1020 				else
1021 					pf_inpcb_unlink_state_key(
1022 					    m->m_pkthdr.pf.inp);
1023 			}
1024 		}
1025 	}
1026 
1027 	if (sk == NULL) {
1028 		if ((sk = RB_FIND(pf_state_tree, &pf_statetbl,
1029 		    (struct pf_state_key *)key)) == NULL)
1030 			return (NULL);
1031 		if (dir == PF_OUT && pkt_sk &&
1032 		    pf_compare_state_keys(pkt_sk, sk, kif, dir) == 0)
1033 			pf_state_key_link(sk, pkt_sk);
1034 		else if (dir == PF_OUT)
1035 			pf_inp_link(m, m->m_pkthdr.pf.inp);
1036 	}
1037 
1038 	/* remove firewall data from outbound packet */
1039 	if (dir == PF_OUT)
1040 		pf_pkt_addr_changed(m);
1041 
1042 	/* list is sorted, if-bound states before floating ones */
1043 	TAILQ_FOREACH(si, &sk->states, entry)
1044 		if ((si->s->kif == pfi_all || si->s->kif == kif) &&
1045 		    ((si->s->key[PF_SK_WIRE]->af == si->s->key[PF_SK_STACK]->af
1046 		    && sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
1047 		    si->s->key[PF_SK_STACK])) ||
1048 		    (si->s->key[PF_SK_WIRE]->af != si->s->key[PF_SK_STACK]->af
1049 		    && dir == PF_IN && (sk == si->s->key[PF_SK_STACK] ||
1050 		    sk == si->s->key[PF_SK_WIRE]))))
1051 			return (si->s);
1052 
1053 	return (NULL);
1054 }
1055 
1056 struct pf_state *
1057 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1058 {
1059 	struct pf_state_key	*sk;
1060 	struct pf_state_item	*si, *ret = NULL;
1061 
1062 	pf_status.fcounters[FCNT_STATE_SEARCH]++;
1063 
1064 	sk = RB_FIND(pf_state_tree, &pf_statetbl, (struct pf_state_key *)key);
1065 
1066 	if (sk != NULL) {
1067 		TAILQ_FOREACH(si, &sk->states, entry)
1068 			if (dir == PF_INOUT ||
1069 			    (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
1070 			    si->s->key[PF_SK_STACK]))) {
1071 				if (more == NULL)
1072 					return (si->s);
1073 
1074 				if (ret)
1075 					(*more)++;
1076 				else
1077 					ret = si;
1078 			}
1079 	}
1080 	return (ret ? ret->s : NULL);
1081 }
1082 
1083 void
1084 pf_state_export(struct pfsync_state *sp, struct pf_state *st)
1085 {
1086 	int32_t expire;
1087 
1088 	bzero(sp, sizeof(struct pfsync_state));
1089 
1090 	/* copy from state key */
1091 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
1092 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
1093 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
1094 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
1095 	sp->key[PF_SK_WIRE].rdomain = htons(st->key[PF_SK_WIRE]->rdomain);
1096 	sp->key[PF_SK_WIRE].af = st->key[PF_SK_WIRE]->af;
1097 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
1098 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
1099 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
1100 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
1101 	sp->key[PF_SK_STACK].rdomain = htons(st->key[PF_SK_STACK]->rdomain);
1102 	sp->key[PF_SK_STACK].af = st->key[PF_SK_STACK]->af;
1103 	sp->rtableid[PF_SK_WIRE] = htonl(st->rtableid[PF_SK_WIRE]);
1104 	sp->rtableid[PF_SK_STACK] = htonl(st->rtableid[PF_SK_STACK]);
1105 	sp->proto = st->key[PF_SK_WIRE]->proto;
1106 	sp->af = st->key[PF_SK_WIRE]->af;
1107 
1108 	/* copy from state */
1109 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
1110 	memcpy(&sp->rt_addr, &st->rt_addr, sizeof(sp->rt_addr));
1111 	sp->creation = htonl(time_uptime - st->creation);
1112 	expire = pf_state_expires(st);
1113 	if (expire <= time_uptime)
1114 		sp->expire = htonl(0);
1115 	else
1116 		sp->expire = htonl(expire - time_uptime);
1117 
1118 	sp->direction = st->direction;
1119 #if NPFLOG > 0
1120 	sp->log = st->log;
1121 #endif	/* NPFLOG > 0 */
1122 	sp->timeout = st->timeout;
1123 	sp->state_flags = htons(st->state_flags);
1124 	if (!SLIST_EMPTY(&st->src_nodes))
1125 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
1126 
1127 	sp->id = st->id;
1128 	sp->creatorid = st->creatorid;
1129 	pf_state_peer_hton(&st->src, &sp->src);
1130 	pf_state_peer_hton(&st->dst, &sp->dst);
1131 
1132 	if (st->rule.ptr == NULL)
1133 		sp->rule = htonl(-1);
1134 	else
1135 		sp->rule = htonl(st->rule.ptr->nr);
1136 	if (st->anchor.ptr == NULL)
1137 		sp->anchor = htonl(-1);
1138 	else
1139 		sp->anchor = htonl(st->anchor.ptr->nr);
1140 	sp->nat_rule = htonl(-1);	/* left for compat, nat_rule is gone */
1141 
1142 	pf_state_counter_hton(st->packets[0], sp->packets[0]);
1143 	pf_state_counter_hton(st->packets[1], sp->packets[1]);
1144 	pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
1145 	pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
1146 
1147 	sp->max_mss = htons(st->max_mss);
1148 	sp->min_ttl = st->min_ttl;
1149 	sp->set_tos = st->set_tos;
1150 	sp->set_prio[0] = st->set_prio[0];
1151 	sp->set_prio[1] = st->set_prio[1];
1152 }
1153 
1154 /* END state table stuff */
1155 
1156 void
1157 pf_purge_expired_rules(void)
1158 {
1159 	struct pf_rule	*r;
1160 
1161 	NET_ASSERT_LOCKED();
1162 
1163 	if (SLIST_EMPTY(&pf_rule_gcl))
1164 		return;
1165 
1166 	while ((r = SLIST_FIRST(&pf_rule_gcl)) != NULL) {
1167 		SLIST_REMOVE(&pf_rule_gcl, r, pf_rule, gcle);
1168 		KASSERT(r->rule_flag & PFRULE_EXPIRED);
1169 		pf_purge_rule(r);
1170 	}
1171 }
1172 
1173 void
1174 pf_purge_thread(void *v)
1175 {
1176 	int nloops = 0, s;
1177 
1178 	for (;;) {
1179 		tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
1180 
1181 		NET_LOCK(s);
1182 
1183 		/* process a fraction of the state table every second */
1184 		pf_purge_expired_states(1 + (pf_status.states
1185 		    / pf_default_rule.timeout[PFTM_INTERVAL]));
1186 
1187 		/* purge other expired types every PFTM_INTERVAL seconds */
1188 		if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
1189 			pf_purge_expired_fragments();
1190 			pf_purge_expired_src_nodes(0);
1191 			pf_purge_expired_rules();
1192 			nloops = 0;
1193 		}
1194 
1195 		NET_UNLOCK(s);
1196 	}
1197 }
1198 
1199 int32_t
1200 pf_state_expires(const struct pf_state *state)
1201 {
1202 	int32_t		timeout;
1203 	u_int32_t	start;
1204 	u_int32_t	end;
1205 	u_int32_t	states;
1206 
1207 	/* handle all PFTM_* > PFTM_MAX here */
1208 	if (state->timeout == PFTM_PURGE)
1209 		return (0);
1210 
1211 	KASSERT(state->timeout != PFTM_UNLINKED);
1212 	KASSERT(state->timeout < PFTM_MAX);
1213 
1214 	timeout = state->rule.ptr->timeout[state->timeout];
1215 	if (!timeout)
1216 		timeout = pf_default_rule.timeout[state->timeout];
1217 
1218 	start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1219 	if (start) {
1220 		end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1221 		states = state->rule.ptr->states_cur;
1222 	} else {
1223 		start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1224 		end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1225 		states = pf_status.states;
1226 	}
1227 	if (end && states > start && start < end) {
1228 		if (states >= end)
1229 			return (0);
1230 
1231 		timeout = timeout * (end - states) / (end - start);
1232 	}
1233 
1234 	return (state->expire + timeout);
1235 }
1236 
1237 void
1238 pf_purge_expired_src_nodes(void)
1239 {
1240 	struct pf_src_node		*cur, *next;
1241 
1242 	NET_ASSERT_LOCKED();
1243 
1244 	for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
1245 	next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
1246 
1247 		if (cur->states == 0 && cur->expire <= time_uptime) {
1248 			next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
1249 			pf_remove_src_node(cur);
1250 		}
1251 	}
1252 }
1253 
1254 void
1255 pf_src_tree_remove_state(struct pf_state *s)
1256 {
1257 	u_int32_t		 timeout;
1258 	struct pf_sn_item	*sni;
1259 
1260 	while ((sni = SLIST_FIRST(&s->src_nodes)) != NULL) {
1261 		SLIST_REMOVE_HEAD(&s->src_nodes, next);
1262 		if (s->src.tcp_est)
1263 			--sni->sn->conn;
1264 		if (--sni->sn->states == 0) {
1265 			timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1266 			if (!timeout)
1267 				timeout =
1268 				    pf_default_rule.timeout[PFTM_SRC_NODE];
1269 			sni->sn->expire = time_uptime + timeout;
1270 		}
1271 		pool_put(&pf_sn_item_pl, sni);
1272 	}
1273 }
1274 
1275 void
1276 pf_remove_state(struct pf_state *cur)
1277 {
1278 	splsoftassert(IPL_SOFTNET);
1279 
1280 	/* handle load balancing related tasks */
1281 	pf_postprocess_addr(cur);
1282 
1283 	if (cur->src.state == PF_TCPS_PROXY_DST) {
1284 		pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1285 		    &cur->key[PF_SK_WIRE]->addr[1],
1286 		    &cur->key[PF_SK_WIRE]->addr[0],
1287 		    cur->key[PF_SK_WIRE]->port[1],
1288 		    cur->key[PF_SK_WIRE]->port[0],
1289 		    cur->src.seqhi, cur->src.seqlo + 1,
1290 		    TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag,
1291 		    cur->key[PF_SK_WIRE]->rdomain);
1292 	}
1293 	RB_REMOVE(pf_state_tree_id, &tree_id, cur);
1294 #if NPFLOW > 0
1295 	if (cur->state_flags & PFSTATE_PFLOW) {
1296 		/* XXXSMP breaks atomicity */
1297 		rw_exit_write(&netlock);
1298 		export_pflow(cur);
1299 		rw_enter_write(&netlock);
1300 	}
1301 #endif	/* NPFLOW > 0 */
1302 #if NPFSYNC > 0
1303 	pfsync_delete_state(cur);
1304 #endif	/* NPFSYNC > 0 */
1305 	cur->timeout = PFTM_UNLINKED;
1306 	pf_src_tree_remove_state(cur);
1307 	pf_detach_state(cur);
1308 }
1309 
1310 void
1311 pf_remove_divert_state(struct pf_state_key *sk)
1312 {
1313 	struct pf_state_item	*si;
1314 
1315 	TAILQ_FOREACH(si, &sk->states, entry) {
1316 		if (sk == si->s->key[PF_SK_STACK] && si->s->rule.ptr &&
1317 		    si->s->rule.ptr->divert.port) {
1318 			pf_remove_state(si->s);
1319 			break;
1320 		}
1321 	}
1322 }
1323 
1324 void
1325 pf_free_state(struct pf_state *cur)
1326 {
1327 	struct pf_rule_item *ri;
1328 
1329 	NET_ASSERT_LOCKED();
1330 
1331 #if NPFSYNC > 0
1332 	if (pfsync_state_in_use(cur))
1333 		return;
1334 #endif	/* NPFSYNC > 0 */
1335 	KASSERT(cur->timeout == PFTM_UNLINKED);
1336 	if (--cur->rule.ptr->states_cur == 0 &&
1337 	    cur->rule.ptr->src_nodes == 0)
1338 		pf_rm_rule(NULL, cur->rule.ptr);
1339 	if (cur->anchor.ptr != NULL)
1340 		if (--cur->anchor.ptr->states_cur == 0)
1341 			pf_rm_rule(NULL, cur->anchor.ptr);
1342 	while ((ri = SLIST_FIRST(&cur->match_rules))) {
1343 		SLIST_REMOVE_HEAD(&cur->match_rules, entry);
1344 		if (--ri->r->states_cur == 0 &&
1345 		    ri->r->src_nodes == 0)
1346 			pf_rm_rule(NULL, ri->r);
1347 		pool_put(&pf_rule_item_pl, ri);
1348 	}
1349 	pf_normalize_tcp_cleanup(cur);
1350 	pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1351 	TAILQ_REMOVE(&state_list, cur, entry_list);
1352 	if (cur->tag)
1353 		pf_tag_unref(cur->tag);
1354 	pool_put(&pf_state_pl, cur);
1355 	pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1356 	pf_status.states--;
1357 }
1358 
1359 void
1360 pf_purge_expired_states(u_int32_t maxcheck)
1361 {
1362 	static struct pf_state	*cur = NULL;
1363 	struct pf_state		*next;
1364 
1365 	NET_ASSERT_LOCKED();
1366 
1367 	while (maxcheck--) {
1368 		/* wrap to start of list when we hit the end */
1369 		if (cur == NULL) {
1370 			cur = TAILQ_FIRST(&state_list);
1371 			if (cur == NULL)
1372 				break;	/* list empty */
1373 		}
1374 
1375 		/* get next state, as cur may get deleted */
1376 		next = TAILQ_NEXT(cur, entry_list);
1377 
1378 		if (cur->timeout == PFTM_UNLINKED) {
1379 			/* free removed state */
1380 			pf_free_state(cur);
1381 		} else if (pf_state_expires(cur) <= time_uptime) {
1382 			/* remove and free expired state */
1383 			pf_remove_state(cur);
1384 			pf_free_state(cur);
1385 		}
1386 		cur = next;
1387 	}
1388 }
1389 
1390 int
1391 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1392 {
1393 	if (aw->type != PF_ADDR_TABLE)
1394 		return (0);
1395 	if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname, 1)) == NULL)
1396 		return (1);
1397 	return (0);
1398 }
1399 
1400 void
1401 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1402 {
1403 	if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1404 		return;
1405 	pfr_detach_table(aw->p.tbl);
1406 	aw->p.tbl = NULL;
1407 }
1408 
1409 void
1410 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1411 {
1412 	struct pfr_ktable *kt = aw->p.tbl;
1413 
1414 	if (aw->type != PF_ADDR_TABLE || kt == NULL)
1415 		return;
1416 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1417 		kt = kt->pfrkt_root;
1418 	aw->p.tbl = NULL;
1419 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1420 		kt->pfrkt_cnt : -1;
1421 }
1422 
1423 void
1424 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1425 {
1426 	switch (af) {
1427 	case AF_INET: {
1428 		u_int32_t a = ntohl(addr->addr32[0]);
1429 		addlog("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1430 		    (a>>8)&255, a&255);
1431 		if (p) {
1432 			p = ntohs(p);
1433 			addlog(":%u", p);
1434 		}
1435 		break;
1436 	}
1437 #ifdef INET6
1438 	case AF_INET6: {
1439 		u_int16_t b;
1440 		u_int8_t i, curstart, curend, maxstart, maxend;
1441 		curstart = curend = maxstart = maxend = 255;
1442 		for (i = 0; i < 8; i++) {
1443 			if (!addr->addr16[i]) {
1444 				if (curstart == 255)
1445 					curstart = i;
1446 				curend = i;
1447 			} else {
1448 				if ((curend - curstart) >
1449 				    (maxend - maxstart)) {
1450 					maxstart = curstart;
1451 					maxend = curend;
1452 				}
1453 				curstart = curend = 255;
1454 			}
1455 		}
1456 		if ((curend - curstart) >
1457 		    (maxend - maxstart)) {
1458 			maxstart = curstart;
1459 			maxend = curend;
1460 		}
1461 		for (i = 0; i < 8; i++) {
1462 			if (i >= maxstart && i <= maxend) {
1463 				if (i == 0)
1464 					addlog(":");
1465 				if (i == maxend)
1466 					addlog(":");
1467 			} else {
1468 				b = ntohs(addr->addr16[i]);
1469 				addlog("%x", b);
1470 				if (i < 7)
1471 					addlog(":");
1472 			}
1473 		}
1474 		if (p) {
1475 			p = ntohs(p);
1476 			addlog("[%u]", p);
1477 		}
1478 		break;
1479 	}
1480 #endif /* INET6 */
1481 	}
1482 }
1483 
1484 void
1485 pf_print_state(struct pf_state *s)
1486 {
1487 	pf_print_state_parts(s, NULL, NULL);
1488 }
1489 
1490 void
1491 pf_print_state_parts(struct pf_state *s,
1492     struct pf_state_key *skwp, struct pf_state_key *sksp)
1493 {
1494 	struct pf_state_key *skw, *sks;
1495 	u_int8_t proto, dir;
1496 
1497 	/* Do our best to fill these, but they're skipped if NULL */
1498 	skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1499 	sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1500 	proto = skw ? skw->proto : (sks ? sks->proto : 0);
1501 	dir = s ? s->direction : 0;
1502 
1503 	switch (proto) {
1504 	case IPPROTO_IPV4:
1505 		addlog("IPv4");
1506 		break;
1507 	case IPPROTO_IPV6:
1508 		addlog("IPv6");
1509 		break;
1510 	case IPPROTO_TCP:
1511 		addlog("TCP");
1512 		break;
1513 	case IPPROTO_UDP:
1514 		addlog("UDP");
1515 		break;
1516 	case IPPROTO_ICMP:
1517 		addlog("ICMP");
1518 		break;
1519 	case IPPROTO_ICMPV6:
1520 		addlog("ICMPv6");
1521 		break;
1522 	default:
1523 		addlog("%u", proto);
1524 		break;
1525 	}
1526 	switch (dir) {
1527 	case PF_IN:
1528 		addlog(" in");
1529 		break;
1530 	case PF_OUT:
1531 		addlog(" out");
1532 		break;
1533 	}
1534 	if (skw) {
1535 		addlog(" wire: (%d) ", skw->rdomain);
1536 		pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1537 		addlog(" ");
1538 		pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1539 	}
1540 	if (sks) {
1541 		addlog(" stack: (%d) ", sks->rdomain);
1542 		if (sks != skw) {
1543 			pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1544 			addlog(" ");
1545 			pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1546 		} else
1547 			addlog("-");
1548 	}
1549 	if (s) {
1550 		if (proto == IPPROTO_TCP) {
1551 			addlog(" [lo=%u high=%u win=%u modulator=%u",
1552 			    s->src.seqlo, s->src.seqhi,
1553 			    s->src.max_win, s->src.seqdiff);
1554 			if (s->src.wscale && s->dst.wscale)
1555 				addlog(" wscale=%u",
1556 				    s->src.wscale & PF_WSCALE_MASK);
1557 			addlog("]");
1558 			addlog(" [lo=%u high=%u win=%u modulator=%u",
1559 			    s->dst.seqlo, s->dst.seqhi,
1560 			    s->dst.max_win, s->dst.seqdiff);
1561 			if (s->src.wscale && s->dst.wscale)
1562 				addlog(" wscale=%u",
1563 				s->dst.wscale & PF_WSCALE_MASK);
1564 			addlog("]");
1565 		}
1566 		addlog(" %u:%u", s->src.state, s->dst.state);
1567 		if (s->rule.ptr)
1568 			addlog(" @%d", s->rule.ptr->nr);
1569 	}
1570 }
1571 
1572 void
1573 pf_print_flags(u_int8_t f)
1574 {
1575 	if (f)
1576 		addlog(" ");
1577 	if (f & TH_FIN)
1578 		addlog("F");
1579 	if (f & TH_SYN)
1580 		addlog("S");
1581 	if (f & TH_RST)
1582 		addlog("R");
1583 	if (f & TH_PUSH)
1584 		addlog("P");
1585 	if (f & TH_ACK)
1586 		addlog("A");
1587 	if (f & TH_URG)
1588 		addlog("U");
1589 	if (f & TH_ECE)
1590 		addlog("E");
1591 	if (f & TH_CWR)
1592 		addlog("W");
1593 }
1594 
1595 #define	PF_SET_SKIP_STEPS(i)					\
1596 	do {							\
1597 		while (head[i] != cur) {			\
1598 			head[i]->skip[i].ptr = cur;		\
1599 			head[i] = TAILQ_NEXT(head[i], entries);	\
1600 		}						\
1601 	} while (0)
1602 
1603 void
1604 pf_calc_skip_steps(struct pf_rulequeue *rules)
1605 {
1606 	struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1607 	int i;
1608 
1609 	cur = TAILQ_FIRST(rules);
1610 	prev = cur;
1611 	for (i = 0; i < PF_SKIP_COUNT; ++i)
1612 		head[i] = cur;
1613 	while (cur != NULL) {
1614 		if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1615 			PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1616 		if (cur->direction != prev->direction)
1617 			PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1618 		if (cur->onrdomain != prev->onrdomain ||
1619 		    cur->ifnot != prev->ifnot)
1620 			PF_SET_SKIP_STEPS(PF_SKIP_RDOM);
1621 		if (cur->af != prev->af)
1622 			PF_SET_SKIP_STEPS(PF_SKIP_AF);
1623 		if (cur->proto != prev->proto)
1624 			PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1625 		if (cur->src.neg != prev->src.neg ||
1626 		    pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1627 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1628 		if (cur->dst.neg != prev->dst.neg ||
1629 		    pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1630 			PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1631 		if (cur->src.port[0] != prev->src.port[0] ||
1632 		    cur->src.port[1] != prev->src.port[1] ||
1633 		    cur->src.port_op != prev->src.port_op)
1634 			PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1635 		if (cur->dst.port[0] != prev->dst.port[0] ||
1636 		    cur->dst.port[1] != prev->dst.port[1] ||
1637 		    cur->dst.port_op != prev->dst.port_op)
1638 			PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1639 
1640 		prev = cur;
1641 		cur = TAILQ_NEXT(cur, entries);
1642 	}
1643 	for (i = 0; i < PF_SKIP_COUNT; ++i)
1644 		PF_SET_SKIP_STEPS(i);
1645 }
1646 
1647 int
1648 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1649 {
1650 	if (aw1->type != aw2->type)
1651 		return (1);
1652 	switch (aw1->type) {
1653 	case PF_ADDR_ADDRMASK:
1654 	case PF_ADDR_RANGE:
1655 		if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
1656 			return (1);
1657 		if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
1658 			return (1);
1659 		return (0);
1660 	case PF_ADDR_DYNIFTL:
1661 		return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1662 	case PF_ADDR_NONE:
1663 	case PF_ADDR_NOROUTE:
1664 	case PF_ADDR_URPFFAILED:
1665 		return (0);
1666 	case PF_ADDR_TABLE:
1667 		return (aw1->p.tbl != aw2->p.tbl);
1668 	case PF_ADDR_RTLABEL:
1669 		return (aw1->v.rtlabel != aw2->v.rtlabel);
1670 	default:
1671 		addlog("invalid address type: %d\n", aw1->type);
1672 		return (1);
1673 	}
1674 }
1675 
1676 /* This algorithm computes 'a + b - c' in ones-complement using a trick to
1677  * emulate at most one ones-complement subtraction. This thereby limits net
1678  * carries/borrows to at most one, eliminating a reduction step and saving one
1679  * each of +, >>, & and ~.
1680  *
1681  * def. x mod y = x - (x//y)*y for integer x,y
1682  * def. sum = x mod 2^16
1683  * def. accumulator = (x >> 16) mod 2^16
1684  *
1685  * The trick works as follows: subtracting exactly one u_int16_t from the
1686  * u_int32_t x incurs at most one underflow, wrapping its upper 16-bits, the
1687  * accumulator, to 2^16 - 1. Adding this to the 16-bit sum preserves the
1688  * ones-complement borrow:
1689  *
1690  *  (sum + accumulator) mod 2^16
1691  * =	{ assume underflow: accumulator := 2^16 - 1 }
1692  *  (sum + 2^16 - 1) mod 2^16
1693  * =	{ mod }
1694  *  (sum - 1) mod 2^16
1695  *
1696  * Although this breaks for sum = 0, giving 0xffff, which is ones-complement's
1697  * other zero, not -1, that cannot occur: the 16-bit sum cannot be underflown
1698  * to zero as that requires subtraction of at least 2^16, which exceeds a
1699  * single u_int16_t's range.
1700  *
1701  * We use the following theorem to derive the implementation:
1702  *
1703  * th. (x + (y mod z)) mod z  =  (x + y) mod z   (0)
1704  * proof.
1705  *     (x + (y mod z)) mod z
1706  *    =  { def mod }
1707  *     (x + y - (y//z)*z) mod z
1708  *    =  { (a + b*c) mod c = a mod c }
1709  *     (x + y) mod z			[end of proof]
1710  *
1711  * ... and thereby obtain:
1712  *
1713  *  (sum + accumulator) mod 2^16
1714  * =	{ def. accumulator, def. sum }
1715  *  (x mod 2^16 + (x >> 16) mod 2^16) mod 2^16
1716  * =	{ (0), twice }
1717  *  (x + (x >> 16)) mod 2^16
1718  * =	{ x mod 2^n = x & (2^n - 1) }
1719  *  (x + (x >> 16)) & 0xffff
1720  *
1721  * Note: this serves also as a reduction step for at most one add (as the
1722  * trailing mod 2^16 prevents further reductions by destroying carries).
1723  */
1724 static __inline void
1725 pf_cksum_fixup(u_int16_t *cksum, u_int16_t was, u_int16_t now,
1726     u_int8_t proto)
1727 {
1728 	u_int32_t x;
1729 	const int udp = proto == IPPROTO_UDP;
1730 
1731 	x = *cksum + was - now;
1732 	x = (x + (x >> 16)) & 0xffff;
1733 
1734 	/* optimise: eliminate a branch when not udp */
1735 	if (udp && *cksum == 0x0000)
1736 		return;
1737 	if (udp && x == 0x0000)
1738 		x = 0xffff;
1739 
1740 	*cksum = (u_int16_t)(x);
1741 }
1742 
1743 /* pre: coverage(cksum) is superset of coverage(covered_cksum) */
1744 static __inline void
1745 pf_cksum_uncover(u_int16_t *cksum, u_int16_t covered_cksum, u_int8_t proto)
1746 {
1747 	pf_cksum_fixup(cksum, ~covered_cksum, 0x0, proto);
1748 }
1749 
1750 /* pre: disjoint(coverage(cksum), coverage(uncovered_cksum)) */
1751 static __inline void
1752 pf_cksum_cover(u_int16_t *cksum, u_int16_t uncovered_cksum, u_int8_t proto)
1753 {
1754 	pf_cksum_fixup(cksum, 0x0, ~uncovered_cksum, proto);
1755 }
1756 
1757 /* pre: *a is 16-bit aligned within its packet
1758  *
1759  * This algorithm emulates 16-bit ones-complement sums on a twos-complement
1760  * machine by conserving ones-complement's otherwise discarded carries in the
1761  * upper bits of x. These accumulated carries when added to the lower 16-bits
1762  * over at least zero 'reduction' steps then complete the ones-complement sum.
1763  *
1764  * def. sum = x mod 2^16
1765  * def. accumulator = (x >> 16)
1766  *
1767  * At most two reduction steps
1768  *
1769  *   x := sum + accumulator
1770  * =    { def sum, def accumulator }
1771  *   x := x mod 2^16 + (x >> 16)
1772  * =    { x mod 2^n = x & (2^n - 1) }
1773  *   x := (x & 0xffff) + (x >> 16)
1774  *
1775  * are necessary to incorporate the accumulated carries (at most one per add)
1776  * i.e. to reduce x < 2^16 from at most 16 carries in the upper 16 bits.
1777  *
1778  * The function is also invariant over the endian of the host. Why?
1779  *
1780  * Define the unary transpose operator ~ on a bitstring in python slice
1781  * notation as lambda m: m[P:] + m[:P] , for some constant pivot P.
1782  *
1783  * th. ~ distributes over ones-complement addition, denoted by +_1, i.e.
1784  *
1785  *     ~m +_1 ~n  =  ~(m +_1 n)    (for all bitstrings m,n of equal length)
1786  *
1787  * proof. Regard the bitstrings in m +_1 n as split at P, forming at most two
1788  * 'half-adds'. Under ones-complement addition, each half-add carries to the
1789  * other, so the sum of each half-add is unaffected by their relative
1790  * order. Therefore:
1791  *
1792  *     ~m +_1 ~n
1793  *   =    { half-adds invariant under transposition }
1794  *     ~s
1795  *   =    { substitute }
1796  *     ~(m +_1 n)                   [end of proof]
1797  *
1798  * th. Summing two in-memory ones-complement 16-bit variables m,n on a machine
1799  * with the converse endian does not alter the result.
1800  *
1801  * proof.
1802  *        { converse machine endian: load/store transposes, P := 8 }
1803  *     ~(~m +_1 ~n)
1804  *   =    { ~ over +_1 }
1805  *     ~~m +_1 ~~n
1806  *   =    { ~ is an involution }
1807  *      m +_1 n                     [end of proof]
1808  *
1809  */
1810 #define NEG(x) ((u_int16_t)~(x))
1811 void
1812 pf_cksum_fixup_a(u_int16_t *cksum, const struct pf_addr *a,
1813     const struct pf_addr *an, sa_family_t af, u_int8_t proto)
1814 {
1815 	u_int32_t	 x;
1816 	const u_int16_t	*n = an->addr16;
1817 	const u_int16_t *o = a->addr16;
1818 	const int	 udp = proto == IPPROTO_UDP;
1819 
1820 	switch (af) {
1821 	case AF_INET:
1822 		x = *cksum + o[0] + NEG(n[0]) + o[1] + NEG(n[1]);
1823 		break;
1824 #ifdef INET6
1825 	case AF_INET6:
1826 		x = *cksum + o[0] + NEG(n[0]) + o[1] + NEG(n[1]) +\
1827 			     o[2] + NEG(n[2]) + o[3] + NEG(n[3]) +\
1828 			     o[4] + NEG(n[4]) + o[5] + NEG(n[5]) +\
1829 			     o[6] + NEG(n[6]) + o[7] + NEG(n[7]);
1830 		break;
1831 #endif /* INET6 */
1832 	default:
1833 		unhandled_af(af);
1834 	}
1835 
1836 	x = (x & 0xffff) + (x >> 16);
1837 	x = (x & 0xffff) + (x >> 16);
1838 
1839 	/* optimise: eliminate a branch when not udp */
1840 	if (udp && *cksum == 0x0000)
1841 		return;
1842 	if (udp && x == 0x0000)
1843 		x = 0xffff;
1844 
1845 	*cksum = (u_int16_t)(x);
1846 }
1847 
1848 int
1849 pf_patch_8(struct pf_pdesc *pd, u_int8_t *f, u_int8_t v, bool hi)
1850 {
1851 	int	rewrite = 0;
1852 
1853 	if (*f != v) {
1854 		u_int16_t old = htons(hi ? (*f << 8) : *f);
1855 		u_int16_t new = htons(hi ? ( v << 8) :  v);
1856 
1857 		pf_cksum_fixup(pd->pcksum, old, new, pd->proto);
1858 		*f = v;
1859 		rewrite = 1;
1860 	}
1861 
1862 	return (rewrite);
1863 }
1864 
1865 /* pre: *f is 16-bit aligned within its packet */
1866 int
1867 pf_patch_16(struct pf_pdesc *pd, u_int16_t *f, u_int16_t v)
1868 {
1869 	int	rewrite = 0;
1870 
1871 	if (*f != v) {
1872 		pf_cksum_fixup(pd->pcksum, *f, v, pd->proto);
1873 		*f = v;
1874 		rewrite = 1;
1875 	}
1876 
1877 	return (rewrite);
1878 }
1879 
1880 int
1881 pf_patch_16_unaligned(struct pf_pdesc *pd, void *f, u_int16_t v, bool hi)
1882 {
1883 	int		rewrite = 0;
1884 	u_int8_t       *fb = (u_int8_t*)f;
1885 	u_int8_t       *vb = (u_int8_t*)&v;
1886 
1887 	if (hi && ALIGNED_POINTER(f, u_int16_t)) {
1888 		return (pf_patch_16(pd, f, v)); /* optimise */
1889 	}
1890 
1891 	rewrite += pf_patch_8(pd, fb++, *vb++, hi);
1892 	rewrite += pf_patch_8(pd, fb++, *vb++,!hi);
1893 
1894 	return (rewrite);
1895 }
1896 
1897 /* pre: *f is 16-bit aligned within its packet */
1898 /* pre: pd->proto != IPPROTO_UDP */
1899 int
1900 pf_patch_32(struct pf_pdesc *pd, u_int32_t *f, u_int32_t v)
1901 {
1902 	int		rewrite = 0;
1903 	u_int16_t      *pc = pd->pcksum;
1904 	u_int8_t        proto = pd->proto;
1905 
1906 	/* optimise: inline udp fixup code is unused; let compiler scrub it */
1907 	if (proto == IPPROTO_UDP)
1908 		panic("pf_patch_32: udp");
1909 
1910 	/* optimise: skip *f != v guard; true for all use-cases */
1911 	pf_cksum_fixup(pc, *f / (1 << 16), v / (1 << 16), proto);
1912 	pf_cksum_fixup(pc, *f % (1 << 16), v % (1 << 16), proto);
1913 
1914 	*f = v;
1915 	rewrite = 1;
1916 
1917 	return (rewrite);
1918 }
1919 
1920 int
1921 pf_patch_32_unaligned(struct pf_pdesc *pd, void *f, u_int32_t v, bool hi)
1922 {
1923 	int		rewrite = 0;
1924 	u_int8_t       *fb = (u_int8_t*)f;
1925 	u_int8_t       *vb = (u_int8_t*)&v;
1926 
1927 	if (hi && ALIGNED_POINTER(f, u_int32_t)) {
1928 		return (pf_patch_32(pd, f, v)); /* optimise */
1929 	}
1930 
1931 	rewrite += pf_patch_8(pd, fb++, *vb++, hi);
1932 	rewrite += pf_patch_8(pd, fb++, *vb++,!hi);
1933 	rewrite += pf_patch_8(pd, fb++, *vb++, hi);
1934 	rewrite += pf_patch_8(pd, fb++, *vb++,!hi);
1935 
1936 	return (rewrite);
1937 }
1938 
1939 int
1940 pf_icmp_mapping(struct pf_pdesc *pd, u_int8_t type, int *icmp_dir,
1941     u_int16_t *virtual_id, u_int16_t *virtual_type)
1942 {
1943 	/*
1944 	 * ICMP types marked with PF_OUT are typically responses to
1945 	 * PF_IN, and will match states in the opposite direction.
1946 	 * PF_IN ICMP types need to match a state with that type.
1947 	 */
1948 	*icmp_dir = PF_OUT;
1949 
1950 	/* Queries (and responses) */
1951 	switch (pd->af) {
1952 	case AF_INET:
1953 		switch (type) {
1954 		case ICMP_ECHO:
1955 			*icmp_dir = PF_IN;
1956 			/* FALLTHROUGH */
1957 		case ICMP_ECHOREPLY:
1958 			*virtual_type = ICMP_ECHO;
1959 			*virtual_id = pd->hdr.icmp.icmp_id;
1960 			break;
1961 
1962 		case ICMP_TSTAMP:
1963 			*icmp_dir = PF_IN;
1964 			/* FALLTHROUGH */
1965 		case ICMP_TSTAMPREPLY:
1966 			*virtual_type = ICMP_TSTAMP;
1967 			*virtual_id = pd->hdr.icmp.icmp_id;
1968 			break;
1969 
1970 		case ICMP_IREQ:
1971 			*icmp_dir = PF_IN;
1972 			/* FALLTHROUGH */
1973 		case ICMP_IREQREPLY:
1974 			*virtual_type = ICMP_IREQ;
1975 			*virtual_id = pd->hdr.icmp.icmp_id;
1976 			break;
1977 
1978 		case ICMP_MASKREQ:
1979 			*icmp_dir = PF_IN;
1980 			/* FALLTHROUGH */
1981 		case ICMP_MASKREPLY:
1982 			*virtual_type = ICMP_MASKREQ;
1983 			*virtual_id = pd->hdr.icmp.icmp_id;
1984 			break;
1985 
1986 		case ICMP_IPV6_WHEREAREYOU:
1987 			*icmp_dir = PF_IN;
1988 			/* FALLTHROUGH */
1989 		case ICMP_IPV6_IAMHERE:
1990 			*virtual_type = ICMP_IPV6_WHEREAREYOU;
1991 			*virtual_id = 0; /* Nothing sane to match on! */
1992 			break;
1993 
1994 		case ICMP_MOBILE_REGREQUEST:
1995 			*icmp_dir = PF_IN;
1996 			/* FALLTHROUGH */
1997 		case ICMP_MOBILE_REGREPLY:
1998 			*virtual_type = ICMP_MOBILE_REGREQUEST;
1999 			*virtual_id = 0; /* Nothing sane to match on! */
2000 			break;
2001 
2002 		case ICMP_ROUTERSOLICIT:
2003 			*icmp_dir = PF_IN;
2004 			/* FALLTHROUGH */
2005 		case ICMP_ROUTERADVERT:
2006 			*virtual_type = ICMP_ROUTERSOLICIT;
2007 			*virtual_id = 0; /* Nothing sane to match on! */
2008 			break;
2009 
2010 		/* These ICMP types map to other connections */
2011 		case ICMP_UNREACH:
2012 		case ICMP_SOURCEQUENCH:
2013 		case ICMP_REDIRECT:
2014 		case ICMP_TIMXCEED:
2015 		case ICMP_PARAMPROB:
2016 			/* These will not be used, but set them anyway */
2017 			*icmp_dir = PF_IN;
2018 			*virtual_type = htons(type);
2019 			*virtual_id = 0;
2020 			return (1);  /* These types match to another state */
2021 
2022 		/*
2023 		 * All remaining ICMP types get their own states,
2024 		 * and will only match in one direction.
2025 		 */
2026 		default:
2027 			*icmp_dir = PF_IN;
2028 			*virtual_type = type;
2029 			*virtual_id = 0;
2030 			break;
2031 		}
2032 		break;
2033 #ifdef INET6
2034 	case AF_INET6:
2035 		switch (type) {
2036 		case ICMP6_ECHO_REQUEST:
2037 			*icmp_dir = PF_IN;
2038 			/* FALLTHROUGH */
2039 		case ICMP6_ECHO_REPLY:
2040 			*virtual_type = ICMP6_ECHO_REQUEST;
2041 			*virtual_id = pd->hdr.icmp6.icmp6_id;
2042 			break;
2043 
2044 		case MLD_LISTENER_QUERY:
2045 			*icmp_dir = PF_IN;
2046 			/* FALLTHROUGH */
2047 		case MLD_LISTENER_REPORT: {
2048 			struct mld_hdr *mld = &pd->hdr.mld;
2049 			u_int32_t h;
2050 
2051 			*virtual_type = MLD_LISTENER_QUERY;
2052 			/* generate fake id for these messages */
2053 			h = mld->mld_addr.s6_addr32[0] ^
2054 			    mld->mld_addr.s6_addr32[1] ^
2055 			    mld->mld_addr.s6_addr32[2] ^
2056 			    mld->mld_addr.s6_addr32[3];
2057 			*virtual_id = (h >> 16) ^ (h & 0xffff);
2058 			break;
2059 		}
2060 
2061 		/*
2062 		 * ICMP6_FQDN and ICMP6_NI query/reply are the same type as
2063 		 * ICMP6_WRU
2064 		 */
2065 		case ICMP6_WRUREQUEST:
2066 			*icmp_dir = PF_IN;
2067 			/* FALLTHROUGH */
2068 		case ICMP6_WRUREPLY:
2069 			*virtual_type = ICMP6_WRUREQUEST;
2070 			*virtual_id = 0; /* Nothing sane to match on! */
2071 			break;
2072 
2073 		case MLD_MTRACE:
2074 			*icmp_dir = PF_IN;
2075 			/* FALLTHROUGH */
2076 		case MLD_MTRACE_RESP:
2077 			*virtual_type = MLD_MTRACE;
2078 			*virtual_id = 0; /* Nothing sane to match on! */
2079 			break;
2080 
2081 		case ND_NEIGHBOR_SOLICIT:
2082 			*icmp_dir = PF_IN;
2083 			/* FALLTHROUGH */
2084 		case ND_NEIGHBOR_ADVERT: {
2085 			struct nd_neighbor_solicit *nd = &pd->hdr.nd_ns;
2086 			u_int32_t h;
2087 
2088 			*virtual_type = ND_NEIGHBOR_SOLICIT;
2089 			/* generate fake id for these messages */
2090 			h = nd->nd_ns_target.s6_addr32[0] ^
2091 			    nd->nd_ns_target.s6_addr32[1] ^
2092 			    nd->nd_ns_target.s6_addr32[2] ^
2093 			    nd->nd_ns_target.s6_addr32[3];
2094 			*virtual_id = (h >> 16) ^ (h & 0xffff);
2095 			break;
2096 		}
2097 
2098 		/*
2099 		 * These ICMP types map to other connections.
2100 		 * ND_REDIRECT can't be in this list because the triggering
2101 		 * packet header is optional.
2102 		 */
2103 		case ICMP6_DST_UNREACH:
2104 		case ICMP6_PACKET_TOO_BIG:
2105 		case ICMP6_TIME_EXCEEDED:
2106 		case ICMP6_PARAM_PROB:
2107 			/* These will not be used, but set them anyway */
2108 			*icmp_dir = PF_IN;
2109 			*virtual_type = htons(type);
2110 			*virtual_id = 0;
2111 			return (1);  /* These types match to another state */
2112 		/*
2113 		 * All remaining ICMP6 types get their own states,
2114 		 * and will only match in one direction.
2115 		 */
2116 		default:
2117 			*icmp_dir = PF_IN;
2118 			*virtual_type = type;
2119 			*virtual_id = 0;
2120 			break;
2121 		}
2122 		break;
2123 #endif /* INET6 */
2124 	}
2125 	*virtual_type = htons(*virtual_type);
2126 	return (0);  /* These types match to their own state */
2127 }
2128 
2129 void
2130 pf_translate_icmp(struct pf_pdesc *pd, struct pf_addr *qa, u_int16_t *qp,
2131     struct pf_addr *oa, struct pf_addr *na, u_int16_t np)
2132 {
2133 	/* note: doesn't trouble to fixup quoted checksums, if any */
2134 
2135 	/* change quoted protocol port */
2136 	if (qp != NULL)
2137 		pf_patch_16(pd, qp, np);
2138 
2139 	/* change quoted ip address */
2140 	pf_cksum_fixup_a(pd->pcksum, qa, na, pd->af, pd->proto);
2141 	PF_ACPY(qa, na, pd->af);
2142 
2143 	/* change network-header's ip address */
2144 	if (oa)
2145 		pf_translate_a(pd, oa, na);
2146 }
2147 
2148 /* pre: *a is 16-bit aligned within its packet */
2149 /*      *a is a network header src/dst address */
2150 int
2151 pf_translate_a(struct pf_pdesc *pd, struct pf_addr *a, struct pf_addr *an)
2152 {
2153 	int	rewrite = 0;
2154 
2155 	/* warning: !PF_ANEQ != PF_AEQ */
2156 	if (!PF_ANEQ(a, an, pd->af))
2157 		return (0);
2158 
2159 	/* fixup transport pseudo-header, if any */
2160 	switch (pd->proto) {
2161 	case IPPROTO_TCP:       /* FALLTHROUGH */
2162 	case IPPROTO_UDP:	/* FALLTHROUGH */
2163 	case IPPROTO_ICMPV6:
2164 		pf_cksum_fixup_a(pd->pcksum, a, an, pd->af, pd->proto);
2165 		break;
2166 	default:
2167 		break;  /* assume no pseudo-header */
2168 	}
2169 
2170 	PF_ACPY(a, an, pd->af);
2171 	rewrite = 1;
2172 
2173 	return (rewrite);
2174 }
2175 
2176 #if INET6
2177 /* pf_translate_af() may change pd->m, adjust local copies after calling */
2178 int
2179 pf_translate_af(struct pf_pdesc *pd)
2180 {
2181 	static const struct pf_addr	zero;
2182 	struct ip		       *ip4;
2183 	struct ip6_hdr		       *ip6;
2184 	int				copyback = 0;
2185 	u_int				hlen, ohlen, dlen;
2186 	u_int16_t		       *pc;
2187 	u_int8_t			af_proto, naf_proto;
2188 
2189 	hlen = (pd->naf == AF_INET) ? sizeof(*ip4) : sizeof(*ip6);
2190 	ohlen = pd->off;
2191 	dlen = pd->tot_len - pd->off;
2192 	pc = pd->pcksum;
2193 
2194 	af_proto = naf_proto = pd->proto;
2195 	if (naf_proto == IPPROTO_ICMP)
2196 		af_proto = IPPROTO_ICMPV6;
2197 	if (naf_proto == IPPROTO_ICMPV6)
2198 		af_proto = IPPROTO_ICMP;
2199 
2200 	/* uncover stale pseudo-header */
2201 	switch (af_proto) {
2202 	case IPPROTO_ICMPV6:
2203 		/* optimise: unchanged for TCP/UDP */
2204 		pf_cksum_fixup(pc, htons(af_proto), 0x0, af_proto);
2205 		pf_cksum_fixup(pc, htons(dlen),     0x0, af_proto);
2206 				/* FALLTHROUGH */
2207 	case IPPROTO_UDP:	/* FALLTHROUGH */
2208 	case IPPROTO_TCP:
2209 		pf_cksum_fixup_a(pc, pd->src, &zero, pd->af, af_proto);
2210 		pf_cksum_fixup_a(pc, pd->dst, &zero, pd->af, af_proto);
2211 		copyback = 1;
2212 		break;
2213 	default:
2214 		break;	/* assume no pseudo-header */
2215 	}
2216 
2217 	/* replace the network header */
2218 	m_adj(pd->m, pd->off);
2219 	pd->src = NULL;
2220 	pd->dst = NULL;
2221 
2222 	if ((M_PREPEND(pd->m, hlen, M_DONTWAIT)) == NULL) {
2223 		pd->m = NULL;
2224 		return (-1);
2225 	}
2226 
2227 	pd->off = hlen;
2228 	pd->tot_len += hlen - ohlen;
2229 
2230 	switch (pd->naf) {
2231 	case AF_INET:
2232 		ip4 = mtod(pd->m, struct ip *);
2233 		bzero(ip4, hlen);
2234 		ip4->ip_v   = IPVERSION;
2235 		ip4->ip_hl  = hlen >> 2;
2236 		ip4->ip_tos = pd->tos;
2237 		ip4->ip_len = htons(hlen + dlen);
2238 		ip4->ip_id  = htons(ip_randomid());
2239 		ip4->ip_off = htons(IP_DF);
2240 		ip4->ip_ttl = pd->ttl;
2241 		ip4->ip_p   = pd->proto;
2242 		ip4->ip_src = pd->nsaddr.v4;
2243 		ip4->ip_dst = pd->ndaddr.v4;
2244 		break;
2245 	case AF_INET6:
2246 		ip6 = mtod(pd->m, struct ip6_hdr *);
2247 		bzero(ip6, hlen);
2248 		ip6->ip6_vfc  = IPV6_VERSION;
2249 		ip6->ip6_flow |= htonl((u_int32_t)pd->tos << 20);
2250 		ip6->ip6_plen = htons(dlen);
2251 		ip6->ip6_nxt  = pd->proto;
2252 		if (!pd->ttl || pd->ttl > IPV6_DEFHLIM)
2253 			ip6->ip6_hlim = IPV6_DEFHLIM;
2254 		else
2255 			ip6->ip6_hlim = pd->ttl;
2256 		ip6->ip6_src  = pd->nsaddr.v6;
2257 		ip6->ip6_dst  = pd->ndaddr.v6;
2258 		break;
2259 	default:
2260 		unhandled_af(pd->naf);
2261 	}
2262 
2263 	/* UDP over IPv6 must be checksummed per rfc2460 p27 */
2264 	if (naf_proto == IPPROTO_UDP && *pc == 0x0000 &&
2265 	    pd->naf == AF_INET6) {
2266 		pd->m->m_pkthdr.csum_flags |= M_UDP_CSUM_OUT;
2267 	}
2268 
2269 	/* cover fresh pseudo-header */
2270 	switch (naf_proto) {
2271 	case IPPROTO_ICMPV6:
2272 		/* optimise: unchanged for TCP/UDP */
2273 		pf_cksum_fixup(pc, 0x0, htons(naf_proto), naf_proto);
2274 		pf_cksum_fixup(pc, 0x0, htons(dlen),      naf_proto);
2275 				/* FALLTHROUGH */
2276 	case IPPROTO_UDP:	/* FALLTHROUGH */
2277 	case IPPROTO_TCP:
2278 		pf_cksum_fixup_a(pc, &zero, &pd->nsaddr, pd->naf, naf_proto);
2279 		pf_cksum_fixup_a(pc, &zero, &pd->ndaddr, pd->naf, naf_proto);
2280 		copyback = 1;
2281 		break;
2282 	default:
2283 		break;	/* assume no pseudo-header */
2284 	}
2285 
2286 	/* flush pd->pcksum */
2287 	if (copyback)
2288 		m_copyback(pd->m, pd->off, pd->hdrlen, &pd->hdr, M_NOWAIT);
2289 
2290 	return (0);
2291 }
2292 
2293 int
2294 pf_change_icmp_af(struct mbuf *m, int ipoff2, struct pf_pdesc *pd,
2295     struct pf_pdesc *pd2, struct pf_addr *src, struct pf_addr *dst,
2296     sa_family_t af, sa_family_t naf)
2297 {
2298 	struct mbuf		*n = NULL;
2299 	struct ip		*ip4;
2300 	struct ip6_hdr		*ip6;
2301 	u_int			 hlen, ohlen, dlen;
2302 	int			 d;
2303 
2304 	if (af == naf || (af != AF_INET && af != AF_INET6) ||
2305 	    (naf != AF_INET && naf != AF_INET6))
2306 		return (-1);
2307 
2308 	/* split the mbuf chain on the quoted ip/ip6 header boundary */
2309 	if ((n = m_split(m, ipoff2, M_DONTWAIT)) == NULL)
2310 		return (-1);
2311 
2312 	/* new quoted header */
2313 	hlen = naf == AF_INET ? sizeof(*ip4) : sizeof(*ip6);
2314 	/* old quoted header */
2315 	ohlen = pd2->off - ipoff2;
2316 
2317 	/* trim old quoted header */
2318 	pf_cksum_uncover(pd->pcksum, in_cksum(n, ohlen), pd->proto);
2319 	m_adj(n, ohlen);
2320 
2321 	/* prepend a new, translated, quoted header */
2322 	if ((M_PREPEND(n, hlen, M_DONTWAIT)) == NULL)
2323 		return (-1);
2324 
2325 	switch (naf) {
2326 	case AF_INET:
2327 		ip4 = mtod(n, struct ip *);
2328 		bzero(ip4, sizeof(*ip4));
2329 		ip4->ip_v   = IPVERSION;
2330 		ip4->ip_hl  = sizeof(*ip4) >> 2;
2331 		ip4->ip_len = htons(sizeof(*ip4) + pd2->tot_len - ohlen);
2332 		ip4->ip_id  = htons(ip_randomid());
2333 		ip4->ip_off = htons(IP_DF);
2334 		ip4->ip_ttl = pd2->ttl;
2335 		if (pd2->proto == IPPROTO_ICMPV6)
2336 			ip4->ip_p = IPPROTO_ICMP;
2337 		else
2338 			ip4->ip_p = pd2->proto;
2339 		ip4->ip_src = src->v4;
2340 		ip4->ip_dst = dst->v4;
2341 		ip4->ip_sum = in_cksum(n, ip4->ip_hl << 2);
2342 		break;
2343 	case AF_INET6:
2344 		ip6 = mtod(n, struct ip6_hdr *);
2345 		bzero(ip6, sizeof(*ip6));
2346 		ip6->ip6_vfc  = IPV6_VERSION;
2347 		ip6->ip6_plen = htons(pd2->tot_len - ohlen);
2348 		if (pd2->proto == IPPROTO_ICMP)
2349 			ip6->ip6_nxt = IPPROTO_ICMPV6;
2350 		else
2351 			ip6->ip6_nxt = pd2->proto;
2352 		if (!pd2->ttl || pd2->ttl > IPV6_DEFHLIM)
2353 			ip6->ip6_hlim = IPV6_DEFHLIM;
2354 		else
2355 			ip6->ip6_hlim = pd2->ttl;
2356 		ip6->ip6_src  = src->v6;
2357 		ip6->ip6_dst  = dst->v6;
2358 		break;
2359 	}
2360 
2361 	/* cover new quoted header */
2362 	/* optimise: any new AF_INET header of ours sums to zero */
2363 	if (naf != AF_INET) {
2364 		pf_cksum_cover(pd->pcksum, in_cksum(n, hlen), pd->proto);
2365 	}
2366 
2367 	/* reattach modified quoted packet to outer header */
2368 	{
2369 		int nlen = n->m_pkthdr.len;
2370 		m_cat(m, n);
2371 		m->m_pkthdr.len += nlen;
2372 	}
2373 
2374 	/* account for altered length */
2375 	d = hlen - ohlen;
2376 
2377 	if (pd->proto == IPPROTO_ICMPV6) {
2378 		/* fixup pseudo-header */
2379 		dlen = pd->tot_len - pd->off;
2380 		pf_cksum_fixup(pd->pcksum,
2381 		    htons(dlen), htons(dlen + d), pd->proto);
2382 	}
2383 
2384 	pd->tot_len  += d;
2385 	pd2->tot_len += d;
2386 	pd2->off     += d;
2387 
2388 	/* note: not bothering to update network headers as
2389 	   these due for rewrite by pf_translate_af() */
2390 
2391 	return (0);
2392 }
2393 
2394 
2395 #define PTR_IP(field)	(offsetof(struct ip, field))
2396 #define PTR_IP6(field)	(offsetof(struct ip6_hdr, field))
2397 
2398 int
2399 pf_translate_icmp_af(struct pf_pdesc *pd, int af, void *arg)
2400 {
2401 	struct icmp		*icmp4;
2402 	struct icmp6_hdr	*icmp6;
2403 	u_int32_t		 mtu;
2404 	int32_t			 ptr = -1;
2405 	u_int8_t		 type;
2406 	u_int8_t		 code;
2407 
2408 	switch (af) {
2409 	case AF_INET:
2410 		icmp6 = arg;
2411 		type  = icmp6->icmp6_type;
2412 		code  = icmp6->icmp6_code;
2413 		mtu   = ntohl(icmp6->icmp6_mtu);
2414 
2415 		switch (type) {
2416 		case ICMP6_ECHO_REQUEST:
2417 			type = ICMP_ECHO;
2418 			break;
2419 		case ICMP6_ECHO_REPLY:
2420 			type = ICMP_ECHOREPLY;
2421 			break;
2422 		case ICMP6_DST_UNREACH:
2423 			type = ICMP_UNREACH;
2424 			switch (code) {
2425 			case ICMP6_DST_UNREACH_NOROUTE:
2426 			case ICMP6_DST_UNREACH_BEYONDSCOPE:
2427 			case ICMP6_DST_UNREACH_ADDR:
2428 				code = ICMP_UNREACH_HOST;
2429 				break;
2430 			case ICMP6_DST_UNREACH_ADMIN:
2431 				code = ICMP_UNREACH_HOST_PROHIB;
2432 				break;
2433 			case ICMP6_DST_UNREACH_NOPORT:
2434 				code = ICMP_UNREACH_PORT;
2435 				break;
2436 			default:
2437 				return (-1);
2438 			}
2439 			break;
2440 		case ICMP6_PACKET_TOO_BIG:
2441 			type = ICMP_UNREACH;
2442 			code = ICMP_UNREACH_NEEDFRAG;
2443 			mtu -= 20;
2444 			break;
2445 		case ICMP6_TIME_EXCEEDED:
2446 			type = ICMP_TIMXCEED;
2447 			break;
2448 		case ICMP6_PARAM_PROB:
2449 			switch (code) {
2450 			case ICMP6_PARAMPROB_HEADER:
2451 				type = ICMP_PARAMPROB;
2452 				code = ICMP_PARAMPROB_ERRATPTR;
2453 				ptr  = ntohl(icmp6->icmp6_pptr);
2454 
2455 				if (ptr == PTR_IP6(ip6_vfc))
2456 					; /* preserve */
2457 				else if (ptr == PTR_IP6(ip6_vfc) + 1)
2458 					ptr = PTR_IP(ip_tos);
2459 				else if (ptr == PTR_IP6(ip6_plen) ||
2460 				    ptr == PTR_IP6(ip6_plen) + 1)
2461 					ptr = PTR_IP(ip_len);
2462 				else if (ptr == PTR_IP6(ip6_nxt))
2463 					ptr = PTR_IP(ip_p);
2464 				else if (ptr == PTR_IP6(ip6_hlim))
2465 					ptr = PTR_IP(ip_ttl);
2466 				else if (ptr >= PTR_IP6(ip6_src) &&
2467 				    ptr < PTR_IP6(ip6_dst))
2468 					ptr = PTR_IP(ip_src);
2469 				else if (ptr >= PTR_IP6(ip6_dst) &&
2470 				    ptr < sizeof(struct ip6_hdr))
2471 					ptr = PTR_IP(ip_dst);
2472 				else {
2473 					return (-1);
2474 				}
2475 				break;
2476 			case ICMP6_PARAMPROB_NEXTHEADER:
2477 				type = ICMP_UNREACH;
2478 				code = ICMP_UNREACH_PROTOCOL;
2479 				break;
2480 			default:
2481 				return (-1);
2482 			}
2483 			break;
2484 		default:
2485 			return (-1);
2486 		}
2487 
2488 		pf_patch_8(pd, &icmp6->icmp6_type, type, PF_HI);
2489 		pf_patch_8(pd, &icmp6->icmp6_code, code, PF_LO);
2490 
2491 		/* aligns well with a icmpv4 nextmtu */
2492 		pf_patch_32(pd, &icmp6->icmp6_mtu, htonl(mtu));
2493 
2494 		/* icmpv4 pptr is a one most significant byte */
2495 		if (ptr >= 0)
2496 			pf_patch_32(pd, &icmp6->icmp6_pptr, htonl(ptr << 24));
2497 		break;
2498 	case AF_INET6:
2499 		icmp4 = arg;
2500 		type  = icmp4->icmp_type;
2501 		code  = icmp4->icmp_code;
2502 		mtu   = ntohs(icmp4->icmp_nextmtu);
2503 
2504 		switch (type) {
2505 		case ICMP_ECHO:
2506 			type = ICMP6_ECHO_REQUEST;
2507 			break;
2508 		case ICMP_ECHOREPLY:
2509 			type = ICMP6_ECHO_REPLY;
2510 			break;
2511 		case ICMP_UNREACH:
2512 			type = ICMP6_DST_UNREACH;
2513 			switch (code) {
2514 			case ICMP_UNREACH_NET:
2515 			case ICMP_UNREACH_HOST:
2516 			case ICMP_UNREACH_NET_UNKNOWN:
2517 			case ICMP_UNREACH_HOST_UNKNOWN:
2518 			case ICMP_UNREACH_ISOLATED:
2519 			case ICMP_UNREACH_TOSNET:
2520 			case ICMP_UNREACH_TOSHOST:
2521 				code = ICMP6_DST_UNREACH_NOROUTE;
2522 				break;
2523 			case ICMP_UNREACH_PORT:
2524 				code = ICMP6_DST_UNREACH_NOPORT;
2525 				break;
2526 			case ICMP_UNREACH_NET_PROHIB:
2527 			case ICMP_UNREACH_HOST_PROHIB:
2528 			case ICMP_UNREACH_FILTER_PROHIB:
2529 			case ICMP_UNREACH_PRECEDENCE_CUTOFF:
2530 				code = ICMP6_DST_UNREACH_ADMIN;
2531 				break;
2532 			case ICMP_UNREACH_PROTOCOL:
2533 				type = ICMP6_PARAM_PROB;
2534 				code = ICMP6_PARAMPROB_NEXTHEADER;
2535 				ptr  = offsetof(struct ip6_hdr, ip6_nxt);
2536 				break;
2537 			case ICMP_UNREACH_NEEDFRAG:
2538 				type = ICMP6_PACKET_TOO_BIG;
2539 				code = 0;
2540 				mtu += 20;
2541 				break;
2542 			default:
2543 				return (-1);
2544 			}
2545 			break;
2546 		case ICMP_TIMXCEED:
2547 			type = ICMP6_TIME_EXCEEDED;
2548 			break;
2549 		case ICMP_PARAMPROB:
2550 			type = ICMP6_PARAM_PROB;
2551 			switch (code) {
2552 			case ICMP_PARAMPROB_ERRATPTR:
2553 				code = ICMP6_PARAMPROB_HEADER;
2554 				break;
2555 			case ICMP_PARAMPROB_LENGTH:
2556 				code = ICMP6_PARAMPROB_HEADER;
2557 				break;
2558 			default:
2559 				return (-1);
2560 			}
2561 
2562 			ptr = icmp4->icmp_pptr;
2563 			if (ptr == 0 || ptr == PTR_IP(ip_tos))
2564 				; /* preserve */
2565 			else if (ptr == PTR_IP(ip_len) ||
2566 			    ptr == PTR_IP(ip_len) + 1)
2567 				ptr = PTR_IP6(ip6_plen);
2568 			else if (ptr == PTR_IP(ip_ttl))
2569 				ptr = PTR_IP6(ip6_hlim);
2570 			else if (ptr == PTR_IP(ip_p))
2571 				ptr = PTR_IP6(ip6_nxt);
2572 			else if (ptr >= PTR_IP(ip_src) &&
2573 			    ptr < PTR_IP(ip_dst))
2574 				ptr = PTR_IP6(ip6_src);
2575 			else if (ptr >= PTR_IP(ip_dst) &&
2576 			    ptr < sizeof(struct ip))
2577 				ptr = PTR_IP6(ip6_dst);
2578 			else {
2579 				return (-1);
2580 			}
2581 			break;
2582 		default:
2583 			return (-1);
2584 		}
2585 
2586 		pf_patch_8(pd, &icmp4->icmp_type, type, PF_HI);
2587 		pf_patch_8(pd, &icmp4->icmp_code, code, PF_LO);
2588 		pf_patch_16(pd, &icmp4->icmp_nextmtu, htons(mtu));
2589 		if (ptr >= 0)
2590 			pf_patch_32(pd, &icmp4->icmp_void, htonl(ptr));
2591 		break;
2592 	}
2593 
2594 	return (0);
2595 }
2596 #endif /* INET6 */
2597 
2598 /*
2599  * Need to modulate the sequence numbers in the TCP SACK option
2600  * (credits to Krzysztof Pfaff for report and patch)
2601  */
2602 int
2603 pf_modulate_sack(struct pf_pdesc *pd, struct pf_state_peer *dst)
2604 {
2605 	struct tcphdr	*th = &pd->hdr.tcp;
2606 	int		 hlen = (th->th_off << 2) - sizeof(*th);
2607 	int		 thoptlen = hlen;
2608 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt = opts;
2609 	int		 copyback = 0, i, olen;
2610 	struct sackblk	 sack;
2611 
2612 #define TCPOLEN_SACKLEN	(TCPOLEN_SACK + 2)
2613 	if (hlen < TCPOLEN_SACKLEN || hlen > MAX_TCPOPTLEN || !pf_pull_hdr(
2614 	    pd->m, pd->off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2615 		return 0;
2616 
2617 	while (hlen >= TCPOLEN_SACKLEN) {
2618 		olen = opt[1];
2619 		switch (*opt) {
2620 		case TCPOPT_EOL:	/* FALLTHROUGH */
2621 		case TCPOPT_NOP:
2622 			opt++;
2623 			hlen--;
2624 			break;
2625 		case TCPOPT_SACK:
2626 			if (olen > hlen)
2627 				olen = hlen;
2628 			if (olen >= TCPOLEN_SACKLEN) {
2629 				for (i = 2; i + TCPOLEN_SACK <= olen;
2630 				    i += TCPOLEN_SACK) {
2631 					size_t startoff = (opt + i) - opts;
2632 					memcpy(&sack, &opt[i], sizeof(sack));
2633 					pf_patch_32_unaligned(pd, &sack.start,
2634 					    htonl(ntohl(sack.start) -
2635 						dst->seqdiff),
2636 					    PF_ALGNMNT(startoff));
2637 					pf_patch_32_unaligned(pd, &sack.end,
2638 					    htonl(ntohl(sack.end) -
2639 						dst->seqdiff),
2640 					    PF_ALGNMNT(startoff +
2641 						sizeof(sack.start)));
2642 					memcpy(&opt[i], &sack, sizeof(sack));
2643 				}
2644 				copyback = 1;
2645 			}
2646 			/* FALLTHROUGH */
2647 		default:
2648 			if (olen < 2)
2649 				olen = 2;
2650 			hlen -= olen;
2651 			opt += olen;
2652 		}
2653 	}
2654 
2655 	if (copyback)
2656 		m_copyback(pd->m, pd->off + sizeof(*th), thoptlen, opts,
2657 		    M_NOWAIT);
2658 	return (copyback);
2659 }
2660 
2661 struct mbuf *
2662 pf_build_tcp(const struct pf_rule *r, sa_family_t af,
2663     const struct pf_addr *saddr, const struct pf_addr *daddr,
2664     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2665     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2666     u_int16_t rtag, u_int rdom)
2667 {
2668 	struct mbuf	*m;
2669 	int		 len, tlen;
2670 	struct ip	*h;
2671 #ifdef INET6
2672 	struct ip6_hdr	*h6;
2673 #endif /* INET6 */
2674 	struct tcphdr	*th;
2675 	char		*opt;
2676 
2677 	/* maximum segment size tcp option */
2678 	tlen = sizeof(struct tcphdr);
2679 	if (mss)
2680 		tlen += 4;
2681 
2682 	switch (af) {
2683 	case AF_INET:
2684 		len = sizeof(struct ip) + tlen;
2685 		break;
2686 #ifdef INET6
2687 	case AF_INET6:
2688 		len = sizeof(struct ip6_hdr) + tlen;
2689 		break;
2690 #endif /* INET6 */
2691 	default:
2692 		unhandled_af(af);
2693 	}
2694 
2695 	/* create outgoing mbuf */
2696 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
2697 	if (m == NULL)
2698 		return (NULL);
2699 	if (tag)
2700 		m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
2701 	m->m_pkthdr.pf.tag = rtag;
2702 	m->m_pkthdr.ph_rtableid = rdom;
2703 	if (r && (r->scrub_flags & PFSTATE_SETPRIO))
2704 		m->m_pkthdr.pf.prio = r->set_prio[0];
2705 	if (r && r->qid)
2706 		m->m_pkthdr.pf.qid = r->qid;
2707 	m->m_data += max_linkhdr;
2708 	m->m_pkthdr.len = m->m_len = len;
2709 	m->m_pkthdr.ph_ifidx = 0;
2710 	m->m_pkthdr.csum_flags |= M_TCP_CSUM_OUT;
2711 	bzero(m->m_data, len);
2712 	switch (af) {
2713 	case AF_INET:
2714 		h = mtod(m, struct ip *);
2715 		h->ip_p = IPPROTO_TCP;
2716 		h->ip_len = htons(tlen);
2717 		h->ip_v = 4;
2718 		h->ip_hl = sizeof(*h) >> 2;
2719 		h->ip_tos = IPTOS_LOWDELAY;
2720 		h->ip_len = htons(len);
2721 		h->ip_off = htons(ip_mtudisc ? IP_DF : 0);
2722 		h->ip_ttl = ttl ? ttl : ip_defttl;
2723 		h->ip_sum = 0;
2724 		h->ip_src.s_addr = saddr->v4.s_addr;
2725 		h->ip_dst.s_addr = daddr->v4.s_addr;
2726 
2727 		th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2728 		break;
2729 #ifdef INET6
2730 	case AF_INET6:
2731 		h6 = mtod(m, struct ip6_hdr *);
2732 		h6->ip6_nxt = IPPROTO_TCP;
2733 		h6->ip6_plen = htons(tlen);
2734 		h6->ip6_vfc |= IPV6_VERSION;
2735 		h6->ip6_hlim = IPV6_DEFHLIM;
2736 		memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2737 		memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2738 
2739 		th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2740 		break;
2741 #endif /* INET6 */
2742 	default:
2743 		unhandled_af(af);
2744 	}
2745 
2746 	/* TCP header */
2747 	th->th_sport = sport;
2748 	th->th_dport = dport;
2749 	th->th_seq = htonl(seq);
2750 	th->th_ack = htonl(ack);
2751 	th->th_off = tlen >> 2;
2752 	th->th_flags = flags;
2753 	th->th_win = htons(win);
2754 
2755 	if (mss) {
2756 		opt = (char *)(th + 1);
2757 		opt[0] = TCPOPT_MAXSEG;
2758 		opt[1] = 4;
2759 		mss = htons(mss);
2760 		memcpy((opt + 2), &mss, 2);
2761 	}
2762 
2763 	return (m);
2764 }
2765 
2766 void
2767 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
2768     const struct pf_addr *saddr, const struct pf_addr *daddr,
2769     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2770     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2771     u_int16_t rtag, u_int rdom)
2772 {
2773 	struct mbuf     *m;
2774 
2775 	if ((m = pf_build_tcp(r, af, saddr, daddr, sport, dport, seq, ack,
2776 	     flags, win, mss, ttl, tag, rtag, rdom)) == NULL)
2777 		return;
2778 
2779 	switch (af) {
2780 	case AF_INET:
2781 		ip_send(m);
2782 		break;
2783 #ifdef INET6
2784 	case AF_INET6:
2785 		ip6_send(m);
2786 		break;
2787 #endif /* INET6 */
2788 	}
2789 }
2790 
2791 static void
2792 pf_send_challenge_ack(struct pf_pdesc *pd, struct pf_state *s,
2793     struct pf_state_peer *src, struct pf_state_peer *dst)
2794 {
2795 	/*
2796 	 * We are sending challenge ACK as a response to SYN packet, which
2797 	 * matches existing state (modulo TCP window check). Therefore packet
2798 	 * must be sent on behalf of destination.
2799 	 *
2800 	 * We expect sender to remain either silent, or send RST packet
2801 	 * so both, firewall and remote peer, can purge dead state from
2802 	 * memory.
2803 	 */
2804 	pf_send_tcp(s->rule.ptr, pd->af, pd->dst, pd->src,
2805 	    pd->hdr.tcp.th_dport, pd->hdr.tcp.th_sport, dst->seqlo,
2806 	    src->seqlo, TH_ACK, 0, 0, s->rule.ptr->return_ttl, 1, 0,
2807 	    pd->rdomain);
2808 }
2809 
2810 void
2811 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2812     struct pf_rule *r, u_int rdomain)
2813 {
2814 	struct mbuf	*m0;
2815 
2816 	if ((m0 = m_copym(m, 0, M_COPYALL, M_NOWAIT)) == NULL)
2817 		return;
2818 
2819 	m0->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
2820 	m0->m_pkthdr.ph_rtableid = rdomain;
2821 	if (r && (r->scrub_flags & PFSTATE_SETPRIO))
2822 		m0->m_pkthdr.pf.prio = r->set_prio[0];
2823 	if (r && r->qid)
2824 		m0->m_pkthdr.pf.qid = r->qid;
2825 
2826 	switch (af) {
2827 	case AF_INET:
2828 		icmp_error(m0, type, code, 0, 0);
2829 		break;
2830 #ifdef INET6
2831 	case AF_INET6:
2832 		icmp6_error(m0, type, code, 0);
2833 		break;
2834 #endif /* INET6 */
2835 	}
2836 }
2837 
2838 /*
2839  * Return ((n = 0) == (a = b [with mask m]))
2840  * Note: n != 0 => returns (a != b [with mask m])
2841  */
2842 int
2843 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2844     struct pf_addr *b, sa_family_t af)
2845 {
2846 	switch (af) {
2847 	case AF_INET:
2848 		if ((a->addr32[0] & m->addr32[0]) ==
2849 		    (b->addr32[0] & m->addr32[0]))
2850 			return (n == 0);
2851 		break;
2852 #ifdef INET6
2853 	case AF_INET6:
2854 		if (((a->addr32[0] & m->addr32[0]) ==
2855 		     (b->addr32[0] & m->addr32[0])) &&
2856 		    ((a->addr32[1] & m->addr32[1]) ==
2857 		     (b->addr32[1] & m->addr32[1])) &&
2858 		    ((a->addr32[2] & m->addr32[2]) ==
2859 		     (b->addr32[2] & m->addr32[2])) &&
2860 		    ((a->addr32[3] & m->addr32[3]) ==
2861 		     (b->addr32[3] & m->addr32[3])))
2862 			return (n == 0);
2863 		break;
2864 #endif /* INET6 */
2865 	}
2866 
2867 	return (n != 0);
2868 }
2869 
2870 /*
2871  * Return 1 if b <= a <= e, otherwise return 0.
2872  */
2873 int
2874 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2875     struct pf_addr *a, sa_family_t af)
2876 {
2877 	switch (af) {
2878 	case AF_INET:
2879 		if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2880 		    (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2881 			return (0);
2882 		break;
2883 #ifdef INET6
2884 	case AF_INET6: {
2885 		int	i;
2886 
2887 		/* check a >= b */
2888 		for (i = 0; i < 4; ++i)
2889 			if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2890 				break;
2891 			else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2892 				return (0);
2893 		/* check a <= e */
2894 		for (i = 0; i < 4; ++i)
2895 			if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2896 				break;
2897 			else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2898 				return (0);
2899 		break;
2900 	}
2901 #endif /* INET6 */
2902 	}
2903 	return (1);
2904 }
2905 
2906 int
2907 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2908 {
2909 	switch (op) {
2910 	case PF_OP_IRG:
2911 		return ((p > a1) && (p < a2));
2912 	case PF_OP_XRG:
2913 		return ((p < a1) || (p > a2));
2914 	case PF_OP_RRG:
2915 		return ((p >= a1) && (p <= a2));
2916 	case PF_OP_EQ:
2917 		return (p == a1);
2918 	case PF_OP_NE:
2919 		return (p != a1);
2920 	case PF_OP_LT:
2921 		return (p < a1);
2922 	case PF_OP_LE:
2923 		return (p <= a1);
2924 	case PF_OP_GT:
2925 		return (p > a1);
2926 	case PF_OP_GE:
2927 		return (p >= a1);
2928 	}
2929 	return (0); /* never reached */
2930 }
2931 
2932 int
2933 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2934 {
2935 	return (pf_match(op, ntohs(a1), ntohs(a2), ntohs(p)));
2936 }
2937 
2938 int
2939 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2940 {
2941 	if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2942 		return (0);
2943 	return (pf_match(op, a1, a2, u));
2944 }
2945 
2946 int
2947 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2948 {
2949 	if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2950 		return (0);
2951 	return (pf_match(op, a1, a2, g));
2952 }
2953 
2954 int
2955 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
2956 {
2957 	if (*tag == -1)
2958 		*tag = m->m_pkthdr.pf.tag;
2959 
2960 	return ((!r->match_tag_not && r->match_tag == *tag) ||
2961 	    (r->match_tag_not && r->match_tag != *tag));
2962 }
2963 
2964 int
2965 pf_match_rcvif(struct mbuf *m, struct pf_rule *r)
2966 {
2967 	struct ifnet *ifp;
2968 	struct pfi_kif *kif;
2969 
2970 	ifp = if_get(m->m_pkthdr.ph_ifidx);
2971 	if (ifp == NULL)
2972 		return (0);
2973 
2974 #if NCARP > 0
2975 	if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
2976 		kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
2977 	else
2978 #endif /* NCARP */
2979 		kif = (struct pfi_kif *)ifp->if_pf_kif;
2980 
2981 	if_put(ifp);
2982 
2983 	if (kif == NULL) {
2984 		DPFPRINTF(LOG_ERR,
2985 		    "%s: kif == NULL, @%d via %s", __func__,
2986 		    r->nr, r->rcv_ifname);
2987 		return (0);
2988 	}
2989 
2990 	return (pfi_kif_match(r->rcv_kif, kif));
2991 }
2992 
2993 void
2994 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
2995 {
2996 	if (tag > 0)
2997 		m->m_pkthdr.pf.tag = tag;
2998 	if (rtableid >= 0)
2999 		m->m_pkthdr.ph_rtableid = (u_int)rtableid;
3000 }
3001 
3002 void
3003 pf_step_into_anchor(int *depth, struct pf_ruleset **rs,
3004     struct pf_rule **r, struct pf_rule **a)
3005 {
3006 	struct pf_anchor_stackframe	*f;
3007 
3008 	if (*depth >= sizeof(pf_anchor_stack) /
3009 	    sizeof(pf_anchor_stack[0])) {
3010 		log(LOG_ERR, "pf: anchor stack overflow\n");
3011 		*r = TAILQ_NEXT(*r, entries);
3012 		return;
3013 	} else if (a != NULL)
3014 		*a = *r;
3015 	f = pf_anchor_stack + (*depth)++;
3016 	f->rs = *rs;
3017 	f->r = *r;
3018 	if ((*r)->anchor_wildcard) {
3019 		f->parent = &(*r)->anchor->children;
3020 		if ((f->child = RB_MIN(pf_anchor_node, f->parent)) == NULL) {
3021 			*r = NULL;
3022 			return;
3023 		}
3024 		*rs = &f->child->ruleset;
3025 	} else {
3026 		f->parent = NULL;
3027 		f->child = NULL;
3028 		*rs = &(*r)->anchor->ruleset;
3029 	}
3030 	*r = TAILQ_FIRST((*rs)->rules.active.ptr);
3031 }
3032 
3033 int
3034 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs,
3035     struct pf_rule **r, struct pf_rule **a, int *match)
3036 {
3037 	struct pf_anchor_stackframe	*f;
3038 	int quick = 0;
3039 
3040 	do {
3041 		if (*depth <= 0)
3042 			break;
3043 		f = pf_anchor_stack + *depth - 1;
3044 		if (f->parent != NULL && f->child != NULL) {
3045 			f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
3046 			if (f->child != NULL) {
3047 				*rs = &f->child->ruleset;
3048 				*r = TAILQ_FIRST((*rs)->rules.active.ptr);
3049 				if (*r == NULL)
3050 					continue;
3051 				else
3052 					break;
3053 			}
3054 		}
3055 		(*depth)--;
3056 		if (*depth == 0 && a != NULL)
3057 			*a = NULL;
3058 		else if (a != NULL)
3059 			*a = f->r;
3060 		*rs = f->rs;
3061 		if (*match > *depth) {
3062 			*match = *depth;
3063 			if (f->r->quick)
3064 				quick = 1;
3065 		}
3066 		*r = TAILQ_NEXT(f->r, entries);
3067 	} while (*r == NULL);
3068 
3069 	return (quick);
3070 }
3071 
3072 void
3073 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
3074     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
3075 {
3076 	switch (af) {
3077 	case AF_INET:
3078 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3079 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3080 		break;
3081 #ifdef INET6
3082 	case AF_INET6:
3083 		naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
3084 		((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
3085 		naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
3086 		((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
3087 		naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
3088 		((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
3089 		naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
3090 		((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
3091 		break;
3092 #endif /* INET6 */
3093 	default:
3094 		unhandled_af(af);
3095 	}
3096 }
3097 
3098 void
3099 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
3100 {
3101 	switch (af) {
3102 	case AF_INET:
3103 		addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
3104 		break;
3105 #ifdef INET6
3106 	case AF_INET6:
3107 		if (addr->addr32[3] == 0xffffffff) {
3108 			addr->addr32[3] = 0;
3109 			if (addr->addr32[2] == 0xffffffff) {
3110 				addr->addr32[2] = 0;
3111 				if (addr->addr32[1] == 0xffffffff) {
3112 					addr->addr32[1] = 0;
3113 					addr->addr32[0] =
3114 					    htonl(ntohl(addr->addr32[0]) + 1);
3115 				} else
3116 					addr->addr32[1] =
3117 					    htonl(ntohl(addr->addr32[1]) + 1);
3118 			} else
3119 				addr->addr32[2] =
3120 				    htonl(ntohl(addr->addr32[2]) + 1);
3121 		} else
3122 			addr->addr32[3] =
3123 			    htonl(ntohl(addr->addr32[3]) + 1);
3124 		break;
3125 #endif /* INET6 */
3126 	default:
3127 		unhandled_af(af);
3128 	}
3129 }
3130 
3131 int
3132 pf_socket_lookup(struct pf_pdesc *pd)
3133 {
3134 	struct pf_addr		*saddr, *daddr;
3135 	u_int16_t		 sport, dport;
3136 	struct inpcbtable	*tb;
3137 	struct inpcb		*inp;
3138 
3139 	pd->lookup.uid = UID_MAX;
3140 	pd->lookup.gid = GID_MAX;
3141 	pd->lookup.pid = NO_PID;
3142 	switch (pd->virtual_proto) {
3143 	case IPPROTO_TCP:
3144 		sport = pd->hdr.tcp.th_sport;
3145 		dport = pd->hdr.tcp.th_dport;
3146 		tb = &tcbtable;
3147 		break;
3148 	case IPPROTO_UDP:
3149 		sport = pd->hdr.udp.uh_sport;
3150 		dport = pd->hdr.udp.uh_dport;
3151 		tb = &udbtable;
3152 		break;
3153 	default:
3154 		return (-1);
3155 	}
3156 	if (pd->dir == PF_IN) {
3157 		saddr = pd->src;
3158 		daddr = pd->dst;
3159 	} else {
3160 		u_int16_t	p;
3161 
3162 		p = sport;
3163 		sport = dport;
3164 		dport = p;
3165 		saddr = pd->dst;
3166 		daddr = pd->src;
3167 	}
3168 	switch (pd->af) {
3169 	case AF_INET:
3170 		/*
3171 		 * Fails when rtable is changed while evaluating the ruleset
3172 		 * The socket looked up will not match the one hit in the end.
3173 		 */
3174 		inp = in_pcbhashlookup(tb, saddr->v4, sport, daddr->v4, dport,
3175 		    pd->rdomain);
3176 		if (inp == NULL) {
3177 			inp = in_pcblookup_listen(tb, daddr->v4, dport, 0,
3178 			    NULL, pd->rdomain);
3179 			if (inp == NULL)
3180 				return (-1);
3181 		}
3182 		break;
3183 #ifdef INET6
3184 	case AF_INET6:
3185 		inp = in6_pcbhashlookup(tb, &saddr->v6, sport, &daddr->v6,
3186 		    dport, pd->rdomain);
3187 		if (inp == NULL) {
3188 			inp = in6_pcblookup_listen(tb, &daddr->v6, dport, 0,
3189 			    NULL, pd->rdomain);
3190 			if (inp == NULL)
3191 				return (-1);
3192 		}
3193 		break;
3194 #endif /* INET6 */
3195 	default:
3196 		unhandled_af(pd->af);
3197 	}
3198 	pd->lookup.uid = inp->inp_socket->so_euid;
3199 	pd->lookup.gid = inp->inp_socket->so_egid;
3200 	pd->lookup.pid = inp->inp_socket->so_cpid;
3201 	return (1);
3202 }
3203 
3204 u_int8_t
3205 pf_get_wscale(struct pf_pdesc *pd)
3206 {
3207 	struct tcphdr	*th = &pd->hdr.tcp;
3208 	int		 hlen;
3209 	u_int8_t	 hdr[60];
3210 	u_int8_t	*opt, optlen;
3211 	u_int8_t	 wscale = 0;
3212 
3213 	hlen = th->th_off << 2;		/* hlen <= sizeof(hdr) */
3214 	if (hlen <= sizeof(struct tcphdr))
3215 		return (0);
3216 	if (!pf_pull_hdr(pd->m, pd->off, hdr, hlen, NULL, NULL, pd->af))
3217 		return (0);
3218 	opt = hdr + sizeof(struct tcphdr);
3219 	hlen -= sizeof(struct tcphdr);
3220 	while (hlen >= 3) {
3221 		switch (*opt) {
3222 		case TCPOPT_EOL:
3223 		case TCPOPT_NOP:
3224 			++opt;
3225 			--hlen;
3226 			break;
3227 		case TCPOPT_WINDOW:
3228 			wscale = opt[2];
3229 			if (wscale > TCP_MAX_WINSHIFT)
3230 				wscale = TCP_MAX_WINSHIFT;
3231 			wscale |= PF_WSCALE_FLAG;
3232 			/* FALLTHROUGH */
3233 		default:
3234 			optlen = opt[1];
3235 			if (optlen < 2)
3236 				optlen = 2;
3237 			hlen -= optlen;
3238 			opt += optlen;
3239 			break;
3240 		}
3241 	}
3242 	return (wscale);
3243 }
3244 
3245 u_int16_t
3246 pf_get_mss(struct pf_pdesc *pd)
3247 {
3248 	struct tcphdr	*th = &pd->hdr.tcp;
3249 	int		 hlen;
3250 	u_int8_t	 hdr[60];
3251 	u_int8_t	*opt, optlen;
3252 	u_int16_t	 mss = tcp_mssdflt;
3253 
3254 	hlen = th->th_off << 2;		/* hlen <= sizeof(hdr) */
3255 	if (hlen <= sizeof(struct tcphdr))
3256 		return (0);
3257 	if (!pf_pull_hdr(pd->m, pd->off, hdr, hlen, NULL, NULL, pd->af))
3258 		return (0);
3259 	opt = hdr + sizeof(struct tcphdr);
3260 	hlen -= sizeof(struct tcphdr);
3261 	while (hlen >= TCPOLEN_MAXSEG) {
3262 		switch (*opt) {
3263 		case TCPOPT_EOL:
3264 		case TCPOPT_NOP:
3265 			++opt;
3266 			--hlen;
3267 			break;
3268 		case TCPOPT_MAXSEG:
3269 			memcpy(&mss, (opt + 2), 2);
3270 			mss = ntohs(mss);
3271 			/* FALLTHROUGH */
3272 		default:
3273 			optlen = opt[1];
3274 			if (optlen < 2)
3275 				optlen = 2;
3276 			hlen -= optlen;
3277 			opt += optlen;
3278 			break;
3279 		}
3280 	}
3281 	return (mss);
3282 }
3283 
3284 u_int16_t
3285 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3286 {
3287 	struct ifnet		*ifp;
3288 	struct sockaddr_in	*dst;
3289 #ifdef INET6
3290 	struct sockaddr_in6	*dst6;
3291 #endif /* INET6 */
3292 	struct rtentry		*rt = NULL;
3293 	struct sockaddr_storage	 ss;
3294 	int			 hlen;
3295 	u_int16_t		 mss = tcp_mssdflt;
3296 
3297 	memset(&ss, 0, sizeof(ss));
3298 
3299 	switch (af) {
3300 	case AF_INET:
3301 		hlen = sizeof(struct ip);
3302 		dst = (struct sockaddr_in *)&ss;
3303 		dst->sin_family = AF_INET;
3304 		dst->sin_len = sizeof(*dst);
3305 		dst->sin_addr = addr->v4;
3306 		rt = rtalloc(sintosa(dst), 0, rtableid);
3307 		break;
3308 #ifdef INET6
3309 	case AF_INET6:
3310 		hlen = sizeof(struct ip6_hdr);
3311 		dst6 = (struct sockaddr_in6 *)&ss;
3312 		dst6->sin6_family = AF_INET6;
3313 		dst6->sin6_len = sizeof(*dst6);
3314 		dst6->sin6_addr = addr->v6;
3315 		rt = rtalloc(sin6tosa(dst6), 0, rtableid);
3316 		break;
3317 #endif /* INET6 */
3318 	}
3319 
3320 	if (rt != NULL && (ifp = if_get(rt->rt_ifidx)) != NULL) {
3321 		mss = ifp->if_mtu - hlen - sizeof(struct tcphdr);
3322 		mss = max(tcp_mssdflt, mss);
3323 		if_put(ifp);
3324 	}
3325 	rtfree(rt);
3326 	mss = min(mss, offer);
3327 	mss = max(mss, 64);		/* sanity - at least max opt space */
3328 	return (mss);
3329 }
3330 
3331 static __inline int
3332 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr, sa_family_t af)
3333 {
3334 	struct pf_rule *r = s->rule.ptr;
3335 	struct pf_src_node *sns[PF_SN_MAX];
3336 	int	rv;
3337 
3338 	s->rt_kif = NULL;
3339 	if (!r->rt)
3340 		return (0);
3341 
3342 	bzero(sns, sizeof(sns));
3343 	switch (af) {
3344 	case AF_INET:
3345 		rv = pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL, sns,
3346 		    &r->route, PF_SN_ROUTE);
3347 		break;
3348 #ifdef INET6
3349 	case AF_INET6:
3350 		rv = pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL, sns,
3351 		    &r->route, PF_SN_ROUTE);
3352 		break;
3353 #endif /* INET6 */
3354 	default:
3355 		rv = 1;
3356 	}
3357 
3358 	if (rv == 0) {
3359 		s->rt_kif = r->route.kif;
3360 		s->natrule.ptr = r;
3361 	}
3362 
3363 	return (rv);
3364 }
3365 
3366 u_int32_t
3367 pf_tcp_iss(struct pf_pdesc *pd)
3368 {
3369 	SHA2_CTX ctx;
3370 	union {
3371 		uint8_t bytes[SHA512_DIGEST_LENGTH];
3372 		uint32_t words[1];
3373 	} digest;
3374 
3375 	if (pf_tcp_secret_init == 0) {
3376 		arc4random_buf(pf_tcp_secret, sizeof(pf_tcp_secret));
3377 		SHA512Init(&pf_tcp_secret_ctx);
3378 		SHA512Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3379 		    sizeof(pf_tcp_secret));
3380 		pf_tcp_secret_init = 1;
3381 	}
3382 	ctx = pf_tcp_secret_ctx;
3383 
3384 	SHA512Update(&ctx, &pd->rdomain, sizeof(pd->rdomain));
3385 	SHA512Update(&ctx, &pd->hdr.tcp.th_sport, sizeof(u_short));
3386 	SHA512Update(&ctx, &pd->hdr.tcp.th_dport, sizeof(u_short));
3387 	switch (pd->af) {
3388 	case AF_INET:
3389 		SHA512Update(&ctx, &pd->src->v4, sizeof(struct in_addr));
3390 		SHA512Update(&ctx, &pd->dst->v4, sizeof(struct in_addr));
3391 		break;
3392 #ifdef INET6
3393 	case AF_INET6:
3394 		SHA512Update(&ctx, &pd->src->v6, sizeof(struct in6_addr));
3395 		SHA512Update(&ctx, &pd->dst->v6, sizeof(struct in6_addr));
3396 		break;
3397 #endif /* INET6 */
3398 	}
3399 	SHA512Final(digest.bytes, &ctx);
3400 	pf_tcp_iss_off += 4096;
3401 	return (digest.words[0] + tcp_iss + pf_tcp_iss_off);
3402 }
3403 
3404 void
3405 pf_rule_to_actions(struct pf_rule *r, struct pf_rule_actions *a)
3406 {
3407 	if (r->qid)
3408 		a->qid = r->qid;
3409 	if (r->pqid)
3410 		a->pqid = r->pqid;
3411 	if (r->rtableid >= 0)
3412 		a->rtableid = r->rtableid;
3413 #if NPFLOG > 0
3414 	a->log |= r->log;
3415 #endif	/* NPFLOG > 0 */
3416 	if (r->scrub_flags & PFSTATE_SETTOS)
3417 		a->set_tos = r->set_tos;
3418 	if (r->min_ttl)
3419 		a->min_ttl = r->min_ttl;
3420 	if (r->max_mss)
3421 		a->max_mss = r->max_mss;
3422 	a->flags |= (r->scrub_flags & (PFSTATE_NODF|PFSTATE_RANDOMID|
3423 	    PFSTATE_SETTOS|PFSTATE_SCRUB_TCP|PFSTATE_SETPRIO));
3424 	if (r->scrub_flags & PFSTATE_SETPRIO) {
3425 		a->set_prio[0] = r->set_prio[0];
3426 		a->set_prio[1] = r->set_prio[1];
3427 	}
3428 }
3429 
3430 #define PF_TEST_ATTRIB(t, a)			\
3431 	do {					\
3432 		if (t) {			\
3433 			r = a;			\
3434 			goto nextrule;		\
3435 		}				\
3436 	} while (0)
3437 
3438 int
3439 pf_test_rule(struct pf_pdesc *pd, struct pf_rule **rm, struct pf_state **sm,
3440     struct pf_rule **am, struct pf_ruleset **rsm, u_short *reason)
3441 {
3442 	struct pf_rule		*r;
3443 	struct pf_rule		*nr = NULL;
3444 	struct pf_rule		*a = NULL;
3445 	struct pf_ruleset	*arsm = NULL;
3446 	struct pf_ruleset	*aruleset = NULL;
3447 	struct pf_ruleset	*ruleset = NULL;
3448 	struct pf_rule_slist	 rules;
3449 	struct pf_rule_item	*ri;
3450 	struct pf_src_node	*sns[PF_SN_MAX];
3451 	struct pf_state_key	*skw = NULL, *sks = NULL;
3452 	struct pf_rule_actions	 act;
3453 	int			 rewrite = 0;
3454 	int			 tag = -1;
3455 	int			 asd = 0;
3456 	int			 match = 0;
3457 	int			 state_icmp = 0, icmp_dir = 0;
3458 	u_int16_t		 virtual_type, virtual_id;
3459 	u_int8_t		 icmptype = 0, icmpcode = 0;
3460 	int			 action = PF_DROP;
3461 
3462 	bzero(&act, sizeof(act));
3463 	bzero(sns, sizeof(sns));
3464 	act.rtableid = pd->rdomain;
3465 	SLIST_INIT(&rules);
3466 
3467 	if (pd->dir == PF_IN && if_congested()) {
3468 		REASON_SET(reason, PFRES_CONGEST);
3469 		return (PF_DROP);
3470 	}
3471 
3472 	switch (pd->virtual_proto) {
3473 	case IPPROTO_ICMP:
3474 		icmptype = pd->hdr.icmp.icmp_type;
3475 		icmpcode = pd->hdr.icmp.icmp_code;
3476 		state_icmp = pf_icmp_mapping(pd, icmptype,
3477 		    &icmp_dir, &virtual_id, &virtual_type);
3478 		if (icmp_dir == PF_IN) {
3479 			pd->osport = pd->nsport = virtual_id;
3480 			pd->odport = pd->ndport = virtual_type;
3481 		} else {
3482 			pd->osport = pd->nsport = virtual_type;
3483 			pd->odport = pd->ndport = virtual_id;
3484 		}
3485 		break;
3486 #ifdef INET6
3487 	case IPPROTO_ICMPV6:
3488 		icmptype = pd->hdr.icmp6.icmp6_type;
3489 		icmpcode = pd->hdr.icmp6.icmp6_code;
3490 		state_icmp = pf_icmp_mapping(pd, icmptype,
3491 		    &icmp_dir, &virtual_id, &virtual_type);
3492 		if (icmp_dir == PF_IN) {
3493 			pd->osport = pd->nsport = virtual_id;
3494 			pd->odport = pd->ndport = virtual_type;
3495 		} else {
3496 			pd->osport = pd->nsport = virtual_type;
3497 			pd->odport = pd->ndport = virtual_id;
3498 		}
3499 		break;
3500 #endif /* INET6 */
3501 	}
3502 
3503 	ruleset = &pf_main_ruleset;
3504 	r = TAILQ_FIRST(pf_main_ruleset.rules.active.ptr);
3505 	while (r != NULL) {
3506 		if (r->rule_flag & PFRULE_EXPIRED) {
3507 			r = TAILQ_NEXT(r, entries);
3508 			goto nextrule;
3509 		}
3510 		r->evaluations++;
3511 		PF_TEST_ATTRIB((pfi_kif_match(r->kif, pd->kif) == r->ifnot),
3512 			r->skip[PF_SKIP_IFP].ptr);
3513 		PF_TEST_ATTRIB((r->direction && r->direction != pd->dir),
3514 			r->skip[PF_SKIP_DIR].ptr);
3515 		PF_TEST_ATTRIB((r->onrdomain >= 0  &&
3516 		    (r->onrdomain == pd->rdomain) == r->ifnot),
3517 			r->skip[PF_SKIP_RDOM].ptr);
3518 		PF_TEST_ATTRIB((r->af && r->af != pd->af),
3519 			r->skip[PF_SKIP_AF].ptr);
3520 		PF_TEST_ATTRIB((r->proto && r->proto != pd->proto),
3521 			r->skip[PF_SKIP_PROTO].ptr);
3522 		PF_TEST_ATTRIB((PF_MISMATCHAW(&r->src.addr, &pd->nsaddr,
3523 		    pd->naf, r->src.neg, pd->kif, act.rtableid)),
3524 			r->skip[PF_SKIP_SRC_ADDR].ptr);
3525 		PF_TEST_ATTRIB((PF_MISMATCHAW(&r->dst.addr, &pd->ndaddr, pd->af,
3526 		    r->dst.neg, NULL, act.rtableid)),
3527 			r->skip[PF_SKIP_DST_ADDR].ptr);
3528 
3529 		switch (pd->virtual_proto) {
3530 		case PF_VPROTO_FRAGMENT:
3531 			/* tcp/udp only. port_op always 0 in other cases */
3532 			PF_TEST_ATTRIB((r->src.port_op || r->dst.port_op),
3533 				TAILQ_NEXT(r, entries));
3534 			PF_TEST_ATTRIB((pd->proto == IPPROTO_TCP && r->flagset),
3535 				TAILQ_NEXT(r, entries));
3536 			/* icmp only. type/code always 0 in other cases */
3537 			PF_TEST_ATTRIB((r->type || r->code),
3538 				TAILQ_NEXT(r, entries));
3539 			/* tcp/udp only. {uid|gid}.op always 0 in other cases */
3540 			PF_TEST_ATTRIB((r->gid.op || r->uid.op),
3541 				TAILQ_NEXT(r, entries));
3542 			break;
3543 
3544 		case IPPROTO_TCP:
3545 			PF_TEST_ATTRIB(((r->flagset & pd->hdr.tcp.th_flags) !=
3546 			    r->flags),
3547 				TAILQ_NEXT(r, entries));
3548 			PF_TEST_ATTRIB((r->os_fingerprint != PF_OSFP_ANY &&
3549 			    !pf_osfp_match(pf_osfp_fingerprint(pd),
3550 			    r->os_fingerprint)),
3551 				TAILQ_NEXT(r, entries));
3552 			/* FALLTHROUGH */
3553 
3554 		case IPPROTO_UDP:
3555 			/* tcp/udp only. port_op always 0 in other cases */
3556 			PF_TEST_ATTRIB((r->src.port_op &&
3557 			    !pf_match_port(r->src.port_op, r->src.port[0],
3558 			    r->src.port[1], pd->nsport)),
3559 				r->skip[PF_SKIP_SRC_PORT].ptr);
3560 			PF_TEST_ATTRIB((r->dst.port_op &&
3561 			    !pf_match_port(r->dst.port_op, r->dst.port[0],
3562 			    r->dst.port[1], pd->ndport)),
3563 				r->skip[PF_SKIP_DST_PORT].ptr);
3564 			/* tcp/udp only. uid.op always 0 in other cases */
3565 			PF_TEST_ATTRIB((r->uid.op && (pd->lookup.done ||
3566 			    (pd->lookup.done =
3567 			    pf_socket_lookup(pd), 1)) &&
3568 			    !pf_match_uid(r->uid.op, r->uid.uid[0],
3569 			    r->uid.uid[1], pd->lookup.uid)),
3570 				TAILQ_NEXT(r, entries));
3571 			/* tcp/udp only. gid.op always 0 in other cases */
3572 			PF_TEST_ATTRIB((r->gid.op && (pd->lookup.done ||
3573 			    (pd->lookup.done =
3574 			    pf_socket_lookup(pd), 1)) &&
3575 			    !pf_match_gid(r->gid.op, r->gid.gid[0],
3576 			    r->gid.gid[1], pd->lookup.gid)),
3577 				TAILQ_NEXT(r, entries));
3578 			break;
3579 
3580 		case IPPROTO_ICMP:
3581 		case IPPROTO_ICMPV6:
3582 			/* icmp only. type always 0 in other cases */
3583 			PF_TEST_ATTRIB((r->type && r->type != icmptype + 1),
3584 				TAILQ_NEXT(r, entries));
3585 			/* icmp only. type always 0 in other cases */
3586 			PF_TEST_ATTRIB((r->code && r->code != icmpcode + 1),
3587 				TAILQ_NEXT(r, entries));
3588 			/* icmp only. don't create states on replies */
3589 			PF_TEST_ATTRIB((r->keep_state && !state_icmp &&
3590 			    (r->rule_flag & PFRULE_STATESLOPPY) == 0 &&
3591 			    icmp_dir != PF_IN),
3592 				TAILQ_NEXT(r, entries));
3593 			break;
3594 
3595 		default:
3596 			break;
3597 		}
3598 
3599 		PF_TEST_ATTRIB((r->rule_flag & PFRULE_FRAGMENT &&
3600 		    pd->virtual_proto != PF_VPROTO_FRAGMENT),
3601 			TAILQ_NEXT(r, entries));
3602 		PF_TEST_ATTRIB((r->tos && !(r->tos == pd->tos)),
3603 			TAILQ_NEXT(r, entries));
3604 		PF_TEST_ATTRIB((r->prob &&
3605 		    r->prob <= arc4random_uniform(UINT_MAX - 1) + 1),
3606 			TAILQ_NEXT(r, entries));
3607 		PF_TEST_ATTRIB((r->match_tag && !pf_match_tag(pd->m, r, &tag)),
3608 			TAILQ_NEXT(r, entries));
3609 		PF_TEST_ATTRIB((r->rcv_kif && pf_match_rcvif(pd->m, r) ==
3610 		    r->rcvifnot),
3611 			TAILQ_NEXT(r, entries));
3612 		PF_TEST_ATTRIB((r->prio && (r->prio == PF_PRIO_ZERO ?
3613 		    0 : r->prio) != pd->m->m_pkthdr.pf.prio),
3614 			TAILQ_NEXT(r, entries));
3615 
3616 		/* FALLTHROUGH */
3617 		if (r->tag)
3618 			tag = r->tag;
3619 		if (r->anchor == NULL) {
3620 			if (r->action == PF_MATCH) {
3621 				if ((ri = pool_get(&pf_rule_item_pl,
3622 				    PR_NOWAIT)) == NULL) {
3623 					REASON_SET(reason, PFRES_MEMORY);
3624 					goto cleanup;
3625 				}
3626 				ri->r = r;
3627 				/* order is irrelevant */
3628 				SLIST_INSERT_HEAD(&rules, ri, entry);
3629 				pf_rule_to_actions(r, &act);
3630 				if (r->rule_flag & PFRULE_AFTO)
3631 					pd->naf = r->naf;
3632 				if (pf_get_transaddr(r, pd, sns, &nr) == -1) {
3633 					REASON_SET(reason, PFRES_TRANSLATE);
3634 					goto cleanup;
3635 				}
3636 #if NPFLOG > 0
3637 				if (r->log) {
3638 					REASON_SET(reason, PFRES_MATCH);
3639 					PFLOG_PACKET(pd, *reason, r, a, ruleset,
3640 					    NULL);
3641 				}
3642 #endif	/* NPFLOG > 0 */
3643 			} else {
3644 				match = asd;
3645 				*rm = r;
3646 				*am = a;
3647 				*rsm = ruleset;
3648 				arsm = aruleset;
3649 			}
3650 
3651 #if NPFLOG > 0
3652 			if (act.log & PF_LOG_MATCHES)
3653 				pf_log_matches(pd, r, a, ruleset, &rules);
3654 #endif	/* NPFLOG > 0 */
3655 
3656 			if (r->quick)
3657 				break;
3658 			r = TAILQ_NEXT(r, entries);
3659 		} else {
3660 			aruleset = ruleset;
3661 			pf_step_into_anchor(&asd, &ruleset, &r, &a);
3662 		}
3663 
3664  nextrule:
3665 		if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3666 		    &r, &a, &match))
3667 			break;
3668 	}
3669 	r = *rm;	/* matching rule */
3670 	a = *am;	/* rule that defines an anchor containing 'r' */
3671 	ruleset = *rsm;	/* ruleset of the anchor defined by the rule 'a' */
3672 	aruleset = arsm;/* ruleset of the 'a' rule itself */
3673 
3674 	/* apply actions for last matching pass/block rule */
3675 	pf_rule_to_actions(r, &act);
3676 	if (r->rule_flag & PFRULE_AFTO)
3677 		pd->naf = r->naf;
3678 	if (pf_get_transaddr(r, pd, sns, &nr) == -1) {
3679 		REASON_SET(reason, PFRES_TRANSLATE);
3680 		goto cleanup;
3681 	}
3682 	REASON_SET(reason, PFRES_MATCH);
3683 
3684 #if NPFLOG > 0
3685 	if (r->log)
3686 		PFLOG_PACKET(pd, *reason, r, a, ruleset, NULL);
3687 	if (act.log & PF_LOG_MATCHES)
3688 		pf_log_matches(pd, r, a, ruleset, &rules);
3689 #endif	/* NPFLOG > 0 */
3690 
3691 	if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
3692 	    (r->action == PF_DROP) &&
3693 	    ((r->rule_flag & PFRULE_RETURNRST) ||
3694 	    (r->rule_flag & PFRULE_RETURNICMP) ||
3695 	    (r->rule_flag & PFRULE_RETURN))) {
3696 		if (pd->proto == IPPROTO_TCP &&
3697 		    ((r->rule_flag & PFRULE_RETURNRST) ||
3698 		    (r->rule_flag & PFRULE_RETURN)) &&
3699 		    !(pd->hdr.tcp.th_flags & TH_RST)) {
3700 			struct tcphdr	*th = &pd->hdr.tcp;
3701 			u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3702 
3703 			if (pf_check_tcp_cksum(pd->m, pd->off,
3704 			    pd->tot_len - pd->off, pd->af))
3705 				REASON_SET(reason, PFRES_PROTCKSUM);
3706 			else {
3707 				if (th->th_flags & TH_SYN)
3708 					ack++;
3709 				if (th->th_flags & TH_FIN)
3710 					ack++;
3711 				pf_send_tcp(r, pd->af, pd->dst,
3712 				    pd->src, th->th_dport, th->th_sport,
3713 				    ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3714 				    r->return_ttl, 1, 0, pd->rdomain);
3715 			}
3716 		} else if ((pd->proto != IPPROTO_ICMP ||
3717 		    ICMP_INFOTYPE(icmptype)) && pd->af == AF_INET &&
3718 		    r->return_icmp)
3719 			pf_send_icmp(pd->m, r->return_icmp >> 8,
3720 			    r->return_icmp & 255, pd->af, r, pd->rdomain);
3721 		else if ((pd->proto != IPPROTO_ICMPV6 ||
3722 		    (icmptype >= ICMP6_ECHO_REQUEST &&
3723 		    icmptype != ND_REDIRECT)) && pd->af == AF_INET6 &&
3724 		    r->return_icmp6)
3725 			pf_send_icmp(pd->m, r->return_icmp6 >> 8,
3726 			    r->return_icmp6 & 255, pd->af, r, pd->rdomain);
3727 	}
3728 
3729 	if (r->action == PF_DROP)
3730 		goto cleanup;
3731 
3732 	pf_tag_packet(pd->m, tag, act.rtableid);
3733 	if (act.rtableid >= 0 &&
3734 	    rtable_l2(act.rtableid) != pd->rdomain)
3735 		pd->destchg = 1;
3736 
3737 	if (r->action == PF_PASS && pd->badopts && ! r->allow_opts) {
3738 		REASON_SET(reason, PFRES_IPOPTIONS);
3739 #if NPFLOG > 0
3740 		pd->pflog |= PF_LOG_FORCE;
3741 #endif	/* NPFLOG > 0 */
3742 		DPFPRINTF(LOG_NOTICE, "dropping packet with "
3743 		    "ip/ipv6 options in pf_test_rule()");
3744 		goto cleanup;
3745 	}
3746 
3747 	action = PF_PASS;
3748 
3749 	if (pd->virtual_proto != PF_VPROTO_FRAGMENT
3750 	    && !state_icmp && r->keep_state) {
3751 
3752 		if (r->rule_flag & PFRULE_SRCTRACK &&
3753 		    pf_insert_src_node(&sns[PF_SN_NONE], r, PF_SN_NONE, pd->af,
3754 		    pd->src, NULL) != 0) {
3755 			REASON_SET(reason, PFRES_SRCLIMIT);
3756 			goto cleanup;
3757 		}
3758 
3759 		if (r->max_states && (r->states_cur >= r->max_states)) {
3760 			pf_status.lcounters[LCNT_STATES]++;
3761 			REASON_SET(reason, PFRES_MAXSTATES);
3762 			goto cleanup;
3763 		}
3764 
3765 		action = pf_create_state(pd, r, a, nr, &skw, &sks, &rewrite,
3766 		    sm, tag, &rules, &act, sns);
3767 
3768 		if (action != PF_PASS)
3769 			goto cleanup;
3770 		if (sks != skw) {
3771 			struct pf_state_key	*sk;
3772 
3773 			if (pd->dir == PF_IN)
3774 				sk = sks;
3775 			else
3776 				sk = skw;
3777 			rewrite += pf_translate(pd,
3778 			    &sk->addr[pd->af == pd->naf ? pd->sidx : pd->didx],
3779 			    sk->port[pd->af == pd->naf ? pd->sidx : pd->didx],
3780 			    &sk->addr[pd->af == pd->naf ? pd->didx : pd->sidx],
3781 			    sk->port[pd->af == pd->naf ? pd->didx : pd->sidx],
3782 			    virtual_type, icmp_dir);
3783 		}
3784 
3785 #ifdef INET6
3786 		if (rewrite && skw->af != sks->af)
3787 			action = PF_AFRT;
3788 #endif /* INET6 */
3789 
3790 	} else {
3791 		while ((ri = SLIST_FIRST(&rules))) {
3792 			SLIST_REMOVE_HEAD(&rules, entry);
3793 			pool_put(&pf_rule_item_pl, ri);
3794 		}
3795 	}
3796 
3797 	/* copy back packet headers if needed */
3798 	if (rewrite && pd->hdrlen) {
3799 		m_copyback(pd->m, pd->off, pd->hdrlen, &pd->hdr, M_NOWAIT);
3800 	}
3801 
3802 #if NPFSYNC > 0
3803 	if (*sm != NULL && !ISSET((*sm)->state_flags, PFSTATE_NOSYNC) &&
3804 	    pd->dir == PF_OUT && pfsync_up()) {
3805 		/*
3806 		 * We want the state created, but we dont
3807 		 * want to send this in case a partner
3808 		 * firewall has to know about it to allow
3809 		 * replies through it.
3810 		 */
3811 		if (pfsync_defer(*sm, pd->m))
3812 			return (PF_DEFER);
3813 	}
3814 #endif	/* NPFSYNC > 0 */
3815 
3816 	if (r->rule_flag & PFRULE_ONCE) {
3817 		r->rule_flag |= PFRULE_EXPIRED;
3818 		r->exptime = time_second;
3819 		SLIST_INSERT_HEAD(&pf_rule_gcl, r, gcle);
3820 	}
3821 
3822 	return (action);
3823 
3824 cleanup:
3825 	while ((ri = SLIST_FIRST(&rules))) {
3826 		SLIST_REMOVE_HEAD(&rules, entry);
3827 		pool_put(&pf_rule_item_pl, ri);
3828 	}
3829 
3830 	return (action);
3831 }
3832 
3833 static __inline int
3834 pf_create_state(struct pf_pdesc *pd, struct pf_rule *r, struct pf_rule *a,
3835     struct pf_rule *nr, struct pf_state_key **skw, struct pf_state_key **sks,
3836     int *rewrite, struct pf_state **sm, int tag, struct pf_rule_slist *rules,
3837     struct pf_rule_actions *act, struct pf_src_node *sns[PF_SN_MAX])
3838 {
3839 	struct pf_state		*s = NULL;
3840 	struct tcphdr		*th = &pd->hdr.tcp;
3841 	u_int16_t		 mss = tcp_mssdflt;
3842 	u_short			 reason;
3843 	u_int			 i;
3844 
3845 	s = pool_get(&pf_state_pl, PR_NOWAIT | PR_ZERO);
3846 	if (s == NULL) {
3847 		REASON_SET(&reason, PFRES_MEMORY);
3848 		goto csfailed;
3849 	}
3850 	s->rule.ptr = r;
3851 	s->anchor.ptr = a;
3852 	s->natrule.ptr = nr;
3853 	if (r->allow_opts)
3854 		s->state_flags |= PFSTATE_ALLOWOPTS;
3855 	if (r->rule_flag & PFRULE_STATESLOPPY)
3856 		s->state_flags |= PFSTATE_SLOPPY;
3857 	if (r->rule_flag & PFRULE_PFLOW)
3858 		s->state_flags |= PFSTATE_PFLOW;
3859 #if NPFLOG > 0
3860 	s->log = act->log & PF_LOG_ALL;
3861 #endif	/* NPFLOG > 0 */
3862 	s->qid = act->qid;
3863 	s->pqid = act->pqid;
3864 	s->rtableid[pd->didx] = act->rtableid;
3865 	s->rtableid[pd->sidx] = -1;	/* return traffic is routed normally */
3866 	s->min_ttl = act->min_ttl;
3867 	s->set_tos = act->set_tos;
3868 	s->max_mss = act->max_mss;
3869 	s->state_flags |= act->flags;
3870 #if NPFSYNC > 0
3871 	s->sync_state = PFSYNC_S_NONE;
3872 #endif	/* NPFSYNC > 0 */
3873 	s->set_prio[0] = act->set_prio[0];
3874 	s->set_prio[1] = act->set_prio[1];
3875 	SLIST_INIT(&s->src_nodes);
3876 
3877 	switch (pd->proto) {
3878 	case IPPROTO_TCP:
3879 		s->src.seqlo = ntohl(th->th_seq);
3880 		s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3881 		if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3882 		    r->keep_state == PF_STATE_MODULATE) {
3883 			/* Generate sequence number modulator */
3884 			if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3885 			    0)
3886 				s->src.seqdiff = 1;
3887 			pf_patch_32(pd,
3888 			    &th->th_seq, htonl(s->src.seqlo + s->src.seqdiff));
3889 			*rewrite = 1;
3890 		} else
3891 			s->src.seqdiff = 0;
3892 		if (th->th_flags & TH_SYN) {
3893 			s->src.seqhi++;
3894 			s->src.wscale = pf_get_wscale(pd);
3895 		}
3896 		s->src.max_win = MAX(ntohs(th->th_win), 1);
3897 		if (s->src.wscale & PF_WSCALE_MASK) {
3898 			/* Remove scale factor from initial window */
3899 			int win = s->src.max_win;
3900 			win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3901 			s->src.max_win = (win - 1) >>
3902 			    (s->src.wscale & PF_WSCALE_MASK);
3903 		}
3904 		if (th->th_flags & TH_FIN)
3905 			s->src.seqhi++;
3906 		s->dst.seqhi = 1;
3907 		s->dst.max_win = 1;
3908 		s->src.state = TCPS_SYN_SENT;
3909 		s->dst.state = TCPS_CLOSED;
3910 		s->timeout = PFTM_TCP_FIRST_PACKET;
3911 		break;
3912 	case IPPROTO_UDP:
3913 		s->src.state = PFUDPS_SINGLE;
3914 		s->dst.state = PFUDPS_NO_TRAFFIC;
3915 		s->timeout = PFTM_UDP_FIRST_PACKET;
3916 		break;
3917 	case IPPROTO_ICMP:
3918 #ifdef INET6
3919 	case IPPROTO_ICMPV6:
3920 #endif	/* INET6 */
3921 		s->timeout = PFTM_ICMP_FIRST_PACKET;
3922 		break;
3923 	default:
3924 		s->src.state = PFOTHERS_SINGLE;
3925 		s->dst.state = PFOTHERS_NO_TRAFFIC;
3926 		s->timeout = PFTM_OTHER_FIRST_PACKET;
3927 	}
3928 
3929 	s->creation = time_uptime;
3930 	s->expire = time_uptime;
3931 
3932 	if (pd->proto == IPPROTO_TCP) {
3933 		if (s->state_flags & PFSTATE_SCRUB_TCP &&
3934 		    pf_normalize_tcp_init(pd, &s->src)) {
3935 			REASON_SET(&reason, PFRES_MEMORY);
3936 			goto csfailed;
3937 		}
3938 		if (s->state_flags & PFSTATE_SCRUB_TCP && s->src.scrub &&
3939 		    pf_normalize_tcp_stateful(pd, &reason, s, &s->src, &s->dst,
3940 		    rewrite)) {
3941 			/* This really shouldn't happen!!! */
3942 			DPFPRINTF(LOG_ERR,
3943 			    "%s: tcp normalize failed on first pkt", __func__);
3944 			goto csfailed;
3945 		}
3946 	}
3947 	s->direction = pd->dir;
3948 
3949 	if (pf_state_key_setup(pd, skw, sks, act->rtableid)) {
3950 		REASON_SET(&reason, PFRES_MEMORY);
3951 		goto csfailed;
3952 	}
3953 
3954 	for (i = 0; i < PF_SN_MAX; i++)
3955 		if (sns[i] != NULL) {
3956 			struct pf_sn_item	*sni;
3957 
3958 			sni = pool_get(&pf_sn_item_pl, PR_NOWAIT);
3959 			if (sni == NULL) {
3960 				REASON_SET(&reason, PFRES_MEMORY);
3961 				goto csfailed;
3962 			}
3963 			sni->sn = sns[i];
3964 			SLIST_INSERT_HEAD(&s->src_nodes, sni, next);
3965 			sni->sn->states++;
3966 		}
3967 
3968 	if (pf_set_rt_ifp(s, pd->src, (*skw)->af) != 0) {
3969 		REASON_SET(&reason, PFRES_NOROUTE);
3970 		goto csfailed;
3971 	}
3972 
3973 	if (pf_state_insert(BOUND_IFACE(r, pd->kif), skw, sks, s)) {
3974 		pf_detach_state(s);
3975 		*sks = *skw = NULL;
3976 		REASON_SET(&reason, PFRES_STATEINS);
3977 		goto csfailed;
3978 	} else
3979 		*sm = s;
3980 
3981 	/*
3982 	 * Make state responsible for rules it binds here.
3983 	 */
3984 	memcpy(&s->match_rules, rules, sizeof(s->match_rules));
3985 	bzero(rules, sizeof(*rules));
3986 	STATE_INC_COUNTERS(s);
3987 
3988 	if (tag > 0) {
3989 		pf_tag_ref(tag);
3990 		s->tag = tag;
3991 	}
3992 	if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3993 	    TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3994 		int rtid = pd->rdomain;
3995 		if (act->rtableid >= 0)
3996 			rtid = act->rtableid;
3997 		s->src.state = PF_TCPS_PROXY_SRC;
3998 		s->src.seqhi = arc4random();
3999 		/* Find mss option */
4000 		mss = pf_get_mss(pd);
4001 		mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
4002 		mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
4003 		s->src.mss = mss;
4004 		pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4005 		    th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4006 		    TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, pd->rdomain);
4007 		REASON_SET(&reason, PFRES_SYNPROXY);
4008 		return (PF_SYNPROXY_DROP);
4009 	}
4010 
4011 	return (PF_PASS);
4012 
4013 csfailed:
4014 	if (s) {
4015 		pf_normalize_tcp_cleanup(s);	/* safe even w/o init */
4016 		pf_src_tree_remove_state(s);
4017 		pool_put(&pf_state_pl, s);
4018 	}
4019 
4020 	for (i = 0; i < PF_SN_MAX; i++)
4021 		if (sns[i] != NULL)
4022 			pf_remove_src_node(sns[i]);
4023 
4024 	return (PF_DROP);
4025 }
4026 
4027 int
4028 pf_translate(struct pf_pdesc *pd, struct pf_addr *saddr, u_int16_t sport,
4029     struct pf_addr *daddr, u_int16_t dport, u_int16_t virtual_type,
4030     int icmp_dir)
4031 {
4032 	/*
4033 	 * when called from bpf_mtap_pflog, there are extra constraints:
4034 	 * -mbuf is faked, m_data is the bpf buffer
4035 	 * -pd is not fully set up
4036 	 */
4037 	int	rewrite = 0;
4038 	int	afto = pd->af != pd->naf;
4039 
4040 	if (afto || PF_ANEQ(daddr, pd->dst, pd->af))
4041 		pd->destchg = 1;
4042 
4043 	switch (pd->proto) {
4044 	case IPPROTO_TCP:	/* FALLTHROUGH */
4045 	case IPPROTO_UDP:
4046 		rewrite += pf_patch_16(pd, pd->sport, sport);
4047 		rewrite += pf_patch_16(pd, pd->dport, dport);
4048 		break;
4049 
4050 	case IPPROTO_ICMP:
4051 		/* pf_translate() is also used when logging invalid packets */
4052 		if (pd->af != AF_INET)
4053 			return (0);
4054 
4055 		if (afto) {
4056 #ifdef INET6
4057 			if (pf_translate_icmp_af(pd, AF_INET6, &pd->hdr.icmp))
4058 				return (0);
4059 			pd->proto = IPPROTO_ICMPV6;
4060 			rewrite = 1;
4061 #endif /* INET6 */
4062 		}
4063 		if (virtual_type == htons(ICMP_ECHO)) {
4064 			u_int16_t icmpid = (icmp_dir == PF_IN) ? sport : dport;
4065 			rewrite += pf_patch_16(pd,
4066 			    &pd->hdr.icmp.icmp_id, icmpid);
4067 		}
4068 		break;
4069 
4070 #ifdef INET6
4071 	case IPPROTO_ICMPV6:
4072 		/* pf_translate() is also used when logging invalid packets */
4073 		if (pd->af != AF_INET6)
4074 			return (0);
4075 
4076 		if (afto) {
4077 			if (pf_translate_icmp_af(pd, AF_INET, &pd->hdr.icmp6))
4078 				return (0);
4079 			pd->proto = IPPROTO_ICMP;
4080 			rewrite = 1;
4081 		}
4082 		if (virtual_type == htons(ICMP6_ECHO_REQUEST)) {
4083 			u_int16_t icmpid = (icmp_dir == PF_IN) ? sport : dport;
4084 			rewrite += pf_patch_16(pd,
4085 			    &pd->hdr.icmp6.icmp6_id, icmpid);
4086 		}
4087 		break;
4088 #endif /* INET6 */
4089 	}
4090 
4091 	if (!afto) {
4092 		rewrite += pf_translate_a(pd, pd->src, saddr);
4093 		rewrite += pf_translate_a(pd, pd->dst, daddr);
4094 	}
4095 
4096 	return (rewrite);
4097 }
4098 
4099 int
4100 pf_tcp_track_full(struct pf_pdesc *pd, struct pf_state_peer *src,
4101     struct pf_state_peer *dst, struct pf_state **state, u_short *reason,
4102     int *copyback)
4103 {
4104 	struct tcphdr		*th = &pd->hdr.tcp;
4105 	u_int16_t		 win = ntohs(th->th_win);
4106 	u_int32_t		 ack, end, data_end, seq, orig_seq;
4107 	u_int8_t		 sws, dws;
4108 	int			 ackskew;
4109 
4110 	if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4111 		sws = src->wscale & PF_WSCALE_MASK;
4112 		dws = dst->wscale & PF_WSCALE_MASK;
4113 	} else
4114 		sws = dws = 0;
4115 
4116 	/*
4117 	 * Sequence tracking algorithm from Guido van Rooij's paper:
4118 	 *   http://www.madison-gurkha.com/publications/tcp_filtering/
4119 	 *	tcp_filtering.ps
4120 	 */
4121 
4122 	orig_seq = seq = ntohl(th->th_seq);
4123 	if (src->seqlo == 0) {
4124 		/* First packet from this end. Set its state */
4125 
4126 		if (((*state)->state_flags & PFSTATE_SCRUB_TCP || dst->scrub) &&
4127 		    src->scrub == NULL) {
4128 			if (pf_normalize_tcp_init(pd, src)) {
4129 				REASON_SET(reason, PFRES_MEMORY);
4130 				return (PF_DROP);
4131 			}
4132 		}
4133 
4134 		/* Deferred generation of sequence number modulator */
4135 		if (dst->seqdiff && !src->seqdiff) {
4136 			/* use random iss for the TCP server */
4137 			while ((src->seqdiff = arc4random() - seq) == 0)
4138 				continue;
4139 			ack = ntohl(th->th_ack) - dst->seqdiff;
4140 			pf_patch_32(pd, &th->th_seq, htonl(seq + src->seqdiff));
4141 			pf_patch_32(pd, &th->th_ack, htonl(ack));
4142 			*copyback = 1;
4143 		} else {
4144 			ack = ntohl(th->th_ack);
4145 		}
4146 
4147 		end = seq + pd->p_len;
4148 		if (th->th_flags & TH_SYN) {
4149 			end++;
4150 			if (dst->wscale & PF_WSCALE_FLAG) {
4151 				src->wscale = pf_get_wscale(pd);
4152 				if (src->wscale & PF_WSCALE_FLAG) {
4153 					/* Remove scale factor from initial
4154 					 * window */
4155 					sws = src->wscale & PF_WSCALE_MASK;
4156 					win = ((u_int32_t)win + (1 << sws) - 1)
4157 					    >> sws;
4158 					dws = dst->wscale & PF_WSCALE_MASK;
4159 				} else {
4160 					/* fixup other window */
4161 					dst->max_win = MIN(TCP_MAXWIN,
4162 					    (u_int32_t)dst->max_win <<
4163 					    (dst->wscale & PF_WSCALE_MASK));
4164 					/* in case of a retrans SYN|ACK */
4165 					dst->wscale = 0;
4166 				}
4167 			}
4168 		}
4169 		data_end = end;
4170 		if (th->th_flags & TH_FIN)
4171 			end++;
4172 
4173 		src->seqlo = seq;
4174 		if (src->state < TCPS_SYN_SENT)
4175 			src->state = TCPS_SYN_SENT;
4176 
4177 		/*
4178 		 * May need to slide the window (seqhi may have been set by
4179 		 * the crappy stack check or if we picked up the connection
4180 		 * after establishment)
4181 		 */
4182 		if (src->seqhi == 1 ||
4183 		    SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4184 			src->seqhi = end + MAX(1, dst->max_win << dws);
4185 		if (win > src->max_win)
4186 			src->max_win = win;
4187 
4188 	} else {
4189 		ack = ntohl(th->th_ack) - dst->seqdiff;
4190 		if (src->seqdiff) {
4191 			/* Modulate sequence numbers */
4192 			pf_patch_32(pd, &th->th_seq, htonl(seq + src->seqdiff));
4193 			pf_patch_32(pd, &th->th_ack, htonl(ack));
4194 			*copyback = 1;
4195 		}
4196 		end = seq + pd->p_len;
4197 		if (th->th_flags & TH_SYN)
4198 			end++;
4199 		data_end = end;
4200 		if (th->th_flags & TH_FIN)
4201 			end++;
4202 	}
4203 
4204 	if ((th->th_flags & TH_ACK) == 0) {
4205 		/* Let it pass through the ack skew check */
4206 		ack = dst->seqlo;
4207 	} else if ((ack == 0 &&
4208 	    (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4209 	    /* broken tcp stacks do not set ack */
4210 	    (dst->state < TCPS_SYN_SENT)) {
4211 		/*
4212 		 * Many stacks (ours included) will set the ACK number in an
4213 		 * FIN|ACK if the SYN times out -- no sequence to ACK.
4214 		 */
4215 		ack = dst->seqlo;
4216 	}
4217 
4218 	if (seq == end) {
4219 		/* Ease sequencing restrictions on no data packets */
4220 		seq = src->seqlo;
4221 		data_end = end = seq;
4222 	}
4223 
4224 	ackskew = dst->seqlo - ack;
4225 
4226 
4227 	/*
4228 	 * Need to demodulate the sequence numbers in any TCP SACK options
4229 	 * (Selective ACK). We could optionally validate the SACK values
4230 	 * against the current ACK window, either forwards or backwards, but
4231 	 * I'm not confident that SACK has been implemented properly
4232 	 * everywhere. It wouldn't surprise me if several stacks accidently
4233 	 * SACK too far backwards of previously ACKed data. There really aren't
4234 	 * any security implications of bad SACKing unless the target stack
4235 	 * doesn't validate the option length correctly. Someone trying to
4236 	 * spoof into a TCP connection won't bother blindly sending SACK
4237 	 * options anyway.
4238 	 */
4239 	if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4240 		if (pf_modulate_sack(pd, dst))
4241 			*copyback = 1;
4242 	}
4243 
4244 
4245 #define MAXACKWINDOW (0xffff + 1500)	/* 1500 is an arbitrary fudge factor */
4246 	if (SEQ_GEQ(src->seqhi, data_end) &&
4247 	    /* Last octet inside other's window space */
4248 	    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4249 	    /* Retrans: not more than one window back */
4250 	    (ackskew >= -MAXACKWINDOW) &&
4251 	    /* Acking not more than one reassembled fragment backwards */
4252 	    (ackskew <= (MAXACKWINDOW << sws)) &&
4253 	    /* Acking not more than one window forward */
4254 	    ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4255 	    (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo))) {
4256 	    /* Require an exact/+1 sequence match on resets when possible */
4257 
4258 		if (dst->scrub || src->scrub) {
4259 			if (pf_normalize_tcp_stateful(pd, reason, *state, src,
4260 			    dst, copyback))
4261 				return (PF_DROP);
4262 		}
4263 
4264 		/* update max window */
4265 		if (src->max_win < win)
4266 			src->max_win = win;
4267 		/* synchronize sequencing */
4268 		if (SEQ_GT(end, src->seqlo))
4269 			src->seqlo = end;
4270 		/* slide the window of what the other end can send */
4271 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4272 			dst->seqhi = ack + MAX((win << sws), 1);
4273 
4274 		/* update states */
4275 		if (th->th_flags & TH_SYN)
4276 			if (src->state < TCPS_SYN_SENT)
4277 				src->state = TCPS_SYN_SENT;
4278 		if (th->th_flags & TH_FIN)
4279 			if (src->state < TCPS_CLOSING)
4280 				src->state = TCPS_CLOSING;
4281 		if (th->th_flags & TH_ACK) {
4282 			if (dst->state == TCPS_SYN_SENT) {
4283 				dst->state = TCPS_ESTABLISHED;
4284 				if (src->state == TCPS_ESTABLISHED &&
4285 				    !SLIST_EMPTY(&(*state)->src_nodes) &&
4286 				    pf_src_connlimit(state)) {
4287 					REASON_SET(reason, PFRES_SRCLIMIT);
4288 					return (PF_DROP);
4289 				}
4290 			} else if (dst->state == TCPS_CLOSING)
4291 				dst->state = TCPS_FIN_WAIT_2;
4292 		}
4293 		if (th->th_flags & TH_RST)
4294 			src->state = dst->state = TCPS_TIME_WAIT;
4295 
4296 		/* update expire time */
4297 		(*state)->expire = time_uptime;
4298 		if (src->state >= TCPS_FIN_WAIT_2 &&
4299 		    dst->state >= TCPS_FIN_WAIT_2)
4300 			(*state)->timeout = PFTM_TCP_CLOSED;
4301 		else if (src->state >= TCPS_CLOSING &&
4302 		    dst->state >= TCPS_CLOSING)
4303 			(*state)->timeout = PFTM_TCP_FIN_WAIT;
4304 		else if (src->state < TCPS_ESTABLISHED ||
4305 		    dst->state < TCPS_ESTABLISHED)
4306 			(*state)->timeout = PFTM_TCP_OPENING;
4307 		else if (src->state >= TCPS_CLOSING ||
4308 		    dst->state >= TCPS_CLOSING)
4309 			(*state)->timeout = PFTM_TCP_CLOSING;
4310 		else
4311 			(*state)->timeout = PFTM_TCP_ESTABLISHED;
4312 
4313 		/* Fall through to PASS packet */
4314 	} else if ((dst->state < TCPS_SYN_SENT ||
4315 		dst->state >= TCPS_FIN_WAIT_2 ||
4316 		src->state >= TCPS_FIN_WAIT_2) &&
4317 	    SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) &&
4318 	    /* Within a window forward of the originating packet */
4319 	    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4320 	    /* Within a window backward of the originating packet */
4321 
4322 		/*
4323 		 * This currently handles three situations:
4324 		 *  1) Stupid stacks will shotgun SYNs before their peer
4325 		 *     replies.
4326 		 *  2) When PF catches an already established stream (the
4327 		 *     firewall rebooted, the state table was flushed, routes
4328 		 *     changed...)
4329 		 *  3) Packets get funky immediately after the connection
4330 		 *     closes (this should catch Solaris spurious ACK|FINs
4331 		 *     that web servers like to spew after a close)
4332 		 *
4333 		 * This must be a little more careful than the above code
4334 		 * since packet floods will also be caught here. We don't
4335 		 * update the TTL here to mitigate the damage of a packet
4336 		 * flood and so the same code can handle awkward establishment
4337 		 * and a loosened connection close.
4338 		 * In the establishment case, a correct peer response will
4339 		 * validate the connection, go through the normal state code
4340 		 * and keep updating the state TTL.
4341 		 */
4342 
4343 		if (pf_status.debug >= LOG_NOTICE) {
4344 			log(LOG_NOTICE, "pf: loose state match: ");
4345 			pf_print_state(*state);
4346 			pf_print_flags(th->th_flags);
4347 			addlog(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4348 			    "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4349 			    pd->p_len, ackskew, (*state)->packets[0],
4350 			    (*state)->packets[1],
4351 			    pd->dir == PF_IN ? "in" : "out",
4352 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4353 		}
4354 
4355 		if (dst->scrub || src->scrub) {
4356 			if (pf_normalize_tcp_stateful(pd, reason, *state, src,
4357 			    dst, copyback))
4358 				return (PF_DROP);
4359 		}
4360 
4361 		/* update max window */
4362 		if (src->max_win < win)
4363 			src->max_win = win;
4364 		/* synchronize sequencing */
4365 		if (SEQ_GT(end, src->seqlo))
4366 			src->seqlo = end;
4367 		/* slide the window of what the other end can send */
4368 		if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4369 			dst->seqhi = ack + MAX((win << sws), 1);
4370 
4371 		/*
4372 		 * Cannot set dst->seqhi here since this could be a shotgunned
4373 		 * SYN and not an already established connection.
4374 		 */
4375 		if (th->th_flags & TH_FIN)
4376 			if (src->state < TCPS_CLOSING)
4377 				src->state = TCPS_CLOSING;
4378 		if (th->th_flags & TH_RST)
4379 			src->state = dst->state = TCPS_TIME_WAIT;
4380 
4381 		/* Fall through to PASS packet */
4382 	} else {
4383 		if ((*state)->dst.state == TCPS_SYN_SENT &&
4384 		    (*state)->src.state == TCPS_SYN_SENT) {
4385 			/* Send RST for state mismatches during handshake */
4386 			if (!(th->th_flags & TH_RST))
4387 				pf_send_tcp((*state)->rule.ptr, pd->af,
4388 				    pd->dst, pd->src, th->th_dport,
4389 				    th->th_sport, ntohl(th->th_ack), 0,
4390 				    TH_RST, 0, 0,
4391 				    (*state)->rule.ptr->return_ttl, 1, 0,
4392 				    pd->rdomain);
4393 			src->seqlo = 0;
4394 			src->seqhi = 1;
4395 			src->max_win = 1;
4396 		} else if (pf_status.debug >= LOG_NOTICE) {
4397 			log(LOG_NOTICE, "pf: BAD state: ");
4398 			pf_print_state(*state);
4399 			pf_print_flags(th->th_flags);
4400 			addlog(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4401 			    "pkts=%llu:%llu dir=%s,%s\n",
4402 			    seq, orig_seq, ack, pd->p_len, ackskew,
4403 			    (*state)->packets[0], (*state)->packets[1],
4404 			    pd->dir == PF_IN ? "in" : "out",
4405 			    pd->dir == (*state)->direction ? "fwd" : "rev");
4406 			addlog("pf: State failure on: %c %c %c %c | %c %c\n",
4407 			    SEQ_GEQ(src->seqhi, data_end) ? ' ' : '1',
4408 			    SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4409 			    ' ': '2',
4410 			    (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4411 			    (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4412 			    SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) ?
4413 			    ' ' :'5',
4414 			    SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4415 		}
4416 		REASON_SET(reason, PFRES_BADSTATE);
4417 		return (PF_DROP);
4418 	}
4419 
4420 	return (PF_PASS);
4421 }
4422 
4423 int
4424 pf_tcp_track_sloppy(struct pf_pdesc *pd, struct pf_state_peer *src,
4425     struct pf_state_peer *dst, struct pf_state **state, u_short *reason)
4426 {
4427 	struct tcphdr		*th = &pd->hdr.tcp;
4428 
4429 	if (th->th_flags & TH_SYN)
4430 		if (src->state < TCPS_SYN_SENT)
4431 			src->state = TCPS_SYN_SENT;
4432 	if (th->th_flags & TH_FIN)
4433 		if (src->state < TCPS_CLOSING)
4434 			src->state = TCPS_CLOSING;
4435 	if (th->th_flags & TH_ACK) {
4436 		if (dst->state == TCPS_SYN_SENT) {
4437 			dst->state = TCPS_ESTABLISHED;
4438 			if (src->state == TCPS_ESTABLISHED &&
4439 			    !SLIST_EMPTY(&(*state)->src_nodes) &&
4440 			    pf_src_connlimit(state)) {
4441 				REASON_SET(reason, PFRES_SRCLIMIT);
4442 				return (PF_DROP);
4443 			}
4444 		} else if (dst->state == TCPS_CLOSING) {
4445 			dst->state = TCPS_FIN_WAIT_2;
4446 		} else if (src->state == TCPS_SYN_SENT &&
4447 		    dst->state < TCPS_SYN_SENT) {
4448 			/*
4449 			 * Handle a special sloppy case where we only see one
4450 			 * half of the connection. If there is a ACK after
4451 			 * the initial SYN without ever seeing a packet from
4452 			 * the destination, set the connection to established.
4453 			 */
4454 			dst->state = src->state = TCPS_ESTABLISHED;
4455 			if (!SLIST_EMPTY(&(*state)->src_nodes) &&
4456 			    pf_src_connlimit(state)) {
4457 				REASON_SET(reason, PFRES_SRCLIMIT);
4458 				return (PF_DROP);
4459 			}
4460 		} else if (src->state == TCPS_CLOSING &&
4461 		    dst->state == TCPS_ESTABLISHED &&
4462 		    dst->seqlo == 0) {
4463 			/*
4464 			 * Handle the closing of half connections where we
4465 			 * don't see the full bidirectional FIN/ACK+ACK
4466 			 * handshake.
4467 			 */
4468 			dst->state = TCPS_CLOSING;
4469 		}
4470 	}
4471 	if (th->th_flags & TH_RST)
4472 		src->state = dst->state = TCPS_TIME_WAIT;
4473 
4474 	/* update expire time */
4475 	(*state)->expire = time_uptime;
4476 	if (src->state >= TCPS_FIN_WAIT_2 &&
4477 	    dst->state >= TCPS_FIN_WAIT_2)
4478 		(*state)->timeout = PFTM_TCP_CLOSED;
4479 	else if (src->state >= TCPS_CLOSING &&
4480 	    dst->state >= TCPS_CLOSING)
4481 		(*state)->timeout = PFTM_TCP_FIN_WAIT;
4482 	else if (src->state < TCPS_ESTABLISHED ||
4483 	    dst->state < TCPS_ESTABLISHED)
4484 		(*state)->timeout = PFTM_TCP_OPENING;
4485 	else if (src->state >= TCPS_CLOSING ||
4486 	    dst->state >= TCPS_CLOSING)
4487 		(*state)->timeout = PFTM_TCP_CLOSING;
4488 	else
4489 		(*state)->timeout = PFTM_TCP_ESTABLISHED;
4490 
4491 	return (PF_PASS);
4492 }
4493 
4494 static __inline int
4495 pf_synproxy(struct pf_pdesc *pd, struct pf_state **state, u_short *reason)
4496 {
4497 	struct pf_state_key	*sk = (*state)->key[pd->didx];
4498 
4499 	if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4500 		struct tcphdr	*th = &pd->hdr.tcp;
4501 
4502 		if (pd->dir != (*state)->direction) {
4503 			REASON_SET(reason, PFRES_SYNPROXY);
4504 			return (PF_SYNPROXY_DROP);
4505 		}
4506 		if (th->th_flags & TH_SYN) {
4507 			if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4508 				REASON_SET(reason, PFRES_SYNPROXY);
4509 				return (PF_DROP);
4510 			}
4511 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4512 			    pd->src, th->th_dport, th->th_sport,
4513 			    (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4514 			    TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4515 			    0, pd->rdomain);
4516 			REASON_SET(reason, PFRES_SYNPROXY);
4517 			return (PF_SYNPROXY_DROP);
4518 		} else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4519 		    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4520 		    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4521 			REASON_SET(reason, PFRES_SYNPROXY);
4522 			return (PF_DROP);
4523 		} else if (!SLIST_EMPTY(&(*state)->src_nodes) &&
4524 		    pf_src_connlimit(state)) {
4525 			REASON_SET(reason, PFRES_SRCLIMIT);
4526 			return (PF_DROP);
4527 		} else
4528 			(*state)->src.state = PF_TCPS_PROXY_DST;
4529 	}
4530 	if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4531 		struct tcphdr	*th = &pd->hdr.tcp;
4532 
4533 		if (pd->dir == (*state)->direction) {
4534 			if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4535 			    (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4536 			    (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4537 				REASON_SET(reason, PFRES_SYNPROXY);
4538 				return (PF_DROP);
4539 			}
4540 			(*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4541 			if ((*state)->dst.seqhi == 1)
4542 				(*state)->dst.seqhi = arc4random();
4543 			pf_send_tcp((*state)->rule.ptr, pd->af,
4544 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4545 			    sk->port[pd->sidx], sk->port[pd->didx],
4546 			    (*state)->dst.seqhi, 0, TH_SYN, 0,
4547 			    (*state)->src.mss, 0, 0, (*state)->tag,
4548 			    sk->rdomain);
4549 			REASON_SET(reason, PFRES_SYNPROXY);
4550 			return (PF_SYNPROXY_DROP);
4551 		} else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4552 		    (TH_SYN|TH_ACK)) ||
4553 		    (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4554 			REASON_SET(reason, PFRES_SYNPROXY);
4555 			return (PF_DROP);
4556 		} else {
4557 			(*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4558 			(*state)->dst.seqlo = ntohl(th->th_seq);
4559 			pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4560 			    pd->src, th->th_dport, th->th_sport,
4561 			    ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4562 			    TH_ACK, (*state)->src.max_win, 0, 0, 0,
4563 			    (*state)->tag, pd->rdomain);
4564 			pf_send_tcp((*state)->rule.ptr, pd->af,
4565 			    &sk->addr[pd->sidx], &sk->addr[pd->didx],
4566 			    sk->port[pd->sidx], sk->port[pd->didx],
4567 			    (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4568 			    TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4569 			    0, sk->rdomain);
4570 			(*state)->src.seqdiff = (*state)->dst.seqhi -
4571 			    (*state)->src.seqlo;
4572 			(*state)->dst.seqdiff = (*state)->src.seqhi -
4573 			    (*state)->dst.seqlo;
4574 			(*state)->src.seqhi = (*state)->src.seqlo +
4575 			    (*state)->dst.max_win;
4576 			(*state)->dst.seqhi = (*state)->dst.seqlo +
4577 			    (*state)->src.max_win;
4578 			(*state)->src.wscale = (*state)->dst.wscale = 0;
4579 			(*state)->src.state = (*state)->dst.state =
4580 			    TCPS_ESTABLISHED;
4581 			REASON_SET(reason, PFRES_SYNPROXY);
4582 			return (PF_SYNPROXY_DROP);
4583 		}
4584 	}
4585 	return (PF_PASS);
4586 }
4587 
4588 int
4589 pf_test_state(struct pf_pdesc *pd, struct pf_state **state, u_short *reason)
4590 {
4591 	struct pf_state_key_cmp	 key;
4592 	int			 copyback = 0;
4593 	struct pf_state_peer	*src, *dst;
4594 	int			 action = PF_PASS;
4595 	struct inpcb		*inp;
4596 
4597 	key.af = pd->af;
4598 	key.proto = pd->virtual_proto;
4599 	key.rdomain = pd->rdomain;
4600 	PF_ACPY(&key.addr[pd->sidx], pd->src, key.af);
4601 	PF_ACPY(&key.addr[pd->didx], pd->dst, key.af);
4602 	key.port[pd->sidx] = pd->osport;
4603 	key.port[pd->didx] = pd->odport;
4604 	inp = pd->m->m_pkthdr.pf.inp;
4605 
4606 	STATE_LOOKUP(pd->kif, &key, pd->dir, *state, pd->m);
4607 
4608 	if (pd->dir == (*state)->direction) {
4609 		src = &(*state)->src;
4610 		dst = &(*state)->dst;
4611 	} else {
4612 		src = &(*state)->dst;
4613 		dst = &(*state)->src;
4614 	}
4615 
4616 	switch (pd->virtual_proto) {
4617 	case IPPROTO_TCP:
4618 		if ((action = pf_synproxy(pd, state, reason)) != PF_PASS)
4619 			return (action);
4620 		if ((pd->hdr.tcp.th_flags & (TH_SYN|TH_ACK)) == TH_SYN) {
4621 
4622 			if (dst->state >= TCPS_FIN_WAIT_2 &&
4623 			    src->state >= TCPS_FIN_WAIT_2) {
4624 				if (pf_status.debug >= LOG_NOTICE) {
4625 					log(LOG_NOTICE, "pf: state reuse ");
4626 					pf_print_state(*state);
4627 					pf_print_flags(pd->hdr.tcp.th_flags);
4628 					addlog("\n");
4629 				}
4630 				/* XXX make sure it's the same direction ?? */
4631 				(*state)->src.state = TCPS_CLOSED;
4632 				(*state)->dst.state = TCPS_CLOSED;
4633 				pf_remove_state(*state);
4634 				*state = NULL;
4635 				pd->m->m_pkthdr.pf.inp = inp;
4636 				return (PF_DROP);
4637 			} else if (dst->state >= TCPS_ESTABLISHED &&
4638 			    src->state >= TCPS_ESTABLISHED) {
4639 				/*
4640 				 * SYN matches existing state???
4641 				 * Typically happens when sender boots up after
4642 				 * sudden panic. Certain protocols (NFSv3) are
4643 				 * always using same port numbers. Challenge
4644 				 * ACK enables all parties (firewall and peers)
4645 				 * to get in sync again.
4646 				 */
4647 				pf_send_challenge_ack(pd, *state, src, dst);
4648 				return (PF_DROP);
4649 			}
4650 		}
4651 
4652 		if ((*state)->state_flags & PFSTATE_SLOPPY) {
4653 			if (pf_tcp_track_sloppy(pd, src, dst, state, reason) ==
4654 			    PF_DROP)
4655 				return (PF_DROP);
4656 		} else {
4657 			int	ret;
4658 
4659 			if (PF_REVERSED_KEY((*state)->key, pd->af))
4660 				ret = pf_tcp_track_full(pd, dst, src, state,
4661 				    reason, &copyback);
4662 			else
4663 				ret = pf_tcp_track_full(pd, src, dst, state,
4664 				    reason, &copyback);
4665 			if (ret == PF_DROP)
4666 				return (PF_DROP);
4667 		}
4668 		break;
4669 	case IPPROTO_UDP:
4670 		/* update states */
4671 		if (src->state < PFUDPS_SINGLE)
4672 			src->state = PFUDPS_SINGLE;
4673 		if (dst->state == PFUDPS_SINGLE)
4674 			dst->state = PFUDPS_MULTIPLE;
4675 
4676 		/* update expire time */
4677 		(*state)->expire = time_uptime;
4678 		if (src->state == PFUDPS_MULTIPLE &&
4679 		    dst->state == PFUDPS_MULTIPLE)
4680 			(*state)->timeout = PFTM_UDP_MULTIPLE;
4681 		else
4682 			(*state)->timeout = PFTM_UDP_SINGLE;
4683 		break;
4684 	default:
4685 		/* update states */
4686 		if (src->state < PFOTHERS_SINGLE)
4687 			src->state = PFOTHERS_SINGLE;
4688 		if (dst->state == PFOTHERS_SINGLE)
4689 			dst->state = PFOTHERS_MULTIPLE;
4690 
4691 		/* update expire time */
4692 		(*state)->expire = time_uptime;
4693 		if (src->state == PFOTHERS_MULTIPLE &&
4694 		    dst->state == PFOTHERS_MULTIPLE)
4695 			(*state)->timeout = PFTM_OTHER_MULTIPLE;
4696 		else
4697 			(*state)->timeout = PFTM_OTHER_SINGLE;
4698 		break;
4699 	}
4700 
4701 	/* translate source/destination address, if necessary */
4702 	if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4703 		struct pf_state_key	*nk;
4704 		int			 afto, sidx, didx;
4705 
4706 		if (PF_REVERSED_KEY((*state)->key, pd->af))
4707 			nk = (*state)->key[pd->sidx];
4708 		else
4709 			nk = (*state)->key[pd->didx];
4710 
4711 		afto = pd->af != nk->af;
4712 		sidx = afto ? pd->didx : pd->sidx;
4713 		didx = afto ? pd->sidx : pd->didx;
4714 
4715 #ifdef INET6
4716 		if (afto) {
4717 			PF_ACPY(&pd->nsaddr, &nk->addr[sidx], nk->af);
4718 			PF_ACPY(&pd->ndaddr, &nk->addr[didx], nk->af);
4719 			pd->naf = nk->af;
4720 			action = PF_AFRT;
4721 		}
4722 #endif /* INET6 */
4723 
4724 		if (!afto)
4725 			pf_translate_a(pd, pd->src, &nk->addr[sidx]);
4726 
4727 		if (pd->sport != NULL)
4728 			pf_patch_16(pd, pd->sport, nk->port[sidx]);
4729 
4730 		if (afto || PF_ANEQ(pd->dst, &nk->addr[didx], pd->af) ||
4731 		    pd->rdomain != nk->rdomain)
4732 			pd->destchg = 1;
4733 
4734 		if (!afto)
4735 			pf_translate_a(pd, pd->dst, &nk->addr[didx]);
4736 
4737 		if (pd->dport != NULL)
4738 			pf_patch_16(pd, pd->dport, nk->port[didx]);
4739 
4740 		pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
4741 		copyback = 1;
4742 	}
4743 
4744 	if (copyback && pd->hdrlen > 0) {
4745 		m_copyback(pd->m, pd->off, pd->hdrlen, &pd->hdr, M_NOWAIT);
4746 	}
4747 
4748 	return (action);
4749 }
4750 
4751 int
4752 pf_icmp_state_lookup(struct pf_pdesc *pd, struct pf_state_key_cmp *key,
4753     struct pf_state **state, u_int16_t icmpid, u_int16_t type,
4754     int icmp_dir, int *iidx, int multi, int inner)
4755 {
4756 	int direction;
4757 
4758 	key->af = pd->af;
4759 	key->proto = pd->proto;
4760 	key->rdomain = pd->rdomain;
4761 	if (icmp_dir == PF_IN) {
4762 		*iidx = pd->sidx;
4763 		key->port[pd->sidx] = icmpid;
4764 		key->port[pd->didx] = type;
4765 	} else {
4766 		*iidx = pd->didx;
4767 		key->port[pd->sidx] = type;
4768 		key->port[pd->didx] = icmpid;
4769 	}
4770 
4771 	if (pf_state_key_addr_setup(pd, key, pd->sidx, pd->src, pd->didx,
4772 	    pd->dst, pd->af, multi))
4773 		return (PF_DROP);
4774 
4775 	STATE_LOOKUP(pd->kif, key, pd->dir, *state, pd->m);
4776 
4777 	if ((*state)->state_flags & PFSTATE_SLOPPY)
4778 		return (-1);
4779 
4780 	/* Is this ICMP message flowing in right direction? */
4781 	if ((*state)->key[PF_SK_WIRE]->af != (*state)->key[PF_SK_STACK]->af)
4782 		direction = (pd->af == (*state)->key[PF_SK_WIRE]->af) ?
4783 		    PF_IN : PF_OUT;
4784 	else
4785 		direction = (*state)->direction;
4786 	if ((((!inner && direction == pd->dir) ||
4787 	    (inner && direction != pd->dir)) ?
4788 	    PF_IN : PF_OUT) != icmp_dir) {
4789 		if (pf_status.debug >= LOG_NOTICE) {
4790 			log(LOG_NOTICE,
4791 			    "pf: icmp type %d in wrong direction (%d): ",
4792 			    ntohs(type), icmp_dir);
4793 			pf_print_state(*state);
4794 			addlog("\n");
4795 		}
4796 		return (PF_DROP);
4797 	}
4798 	return (-1);
4799 }
4800 
4801 int
4802 pf_test_state_icmp(struct pf_pdesc *pd, struct pf_state **state,
4803     u_short *reason)
4804 {
4805 	u_int16_t	 virtual_id, virtual_type;
4806 	u_int8_t	 icmptype;
4807 	int		 icmp_dir, iidx, ret, copyback = 0;
4808 
4809 	struct pf_state_key_cmp key;
4810 
4811 	switch (pd->proto) {
4812 	case IPPROTO_ICMP:
4813 		icmptype = pd->hdr.icmp.icmp_type;
4814 		break;
4815 #ifdef INET6
4816 	case IPPROTO_ICMPV6:
4817 		icmptype = pd->hdr.icmp6.icmp6_type;
4818 		break;
4819 #endif /* INET6 */
4820 	default:
4821 		panic("unhandled proto %d", pd->proto);
4822 	}
4823 
4824 	if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &virtual_id,
4825 	    &virtual_type) == 0) {
4826 		/*
4827 		 * ICMP query/reply message not related to a TCP/UDP packet.
4828 		 * Search for an ICMP state.
4829 		 */
4830 		ret = pf_icmp_state_lookup(pd, &key, state,
4831 		    virtual_id, virtual_type, icmp_dir, &iidx,
4832 		    0, 0);
4833 		/* IPv6? try matching a multicast address */
4834 		if (ret == PF_DROP && pd->af == AF_INET6 && icmp_dir == PF_OUT)
4835 			ret = pf_icmp_state_lookup(pd, &key, state, virtual_id,
4836 			    virtual_type, icmp_dir, &iidx, 1, 0);
4837 		if (ret >= 0)
4838 			return (ret);
4839 
4840 		(*state)->expire = time_uptime;
4841 		(*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4842 
4843 		/* translate source/destination address, if necessary */
4844 		if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4845 			struct pf_state_key	*nk;
4846 			int			 afto, sidx, didx;
4847 
4848 			if (PF_REVERSED_KEY((*state)->key, pd->af))
4849 				nk = (*state)->key[pd->sidx];
4850 			else
4851 				nk = (*state)->key[pd->didx];
4852 
4853 			afto = pd->af != nk->af;
4854 			sidx = afto ? pd->didx : pd->sidx;
4855 			didx = afto ? pd->sidx : pd->didx;
4856 			iidx = afto ? !iidx : iidx;
4857 #ifdef	INET6
4858 			if (afto) {
4859 				PF_ACPY(&pd->nsaddr, &nk->addr[sidx], nk->af);
4860 				PF_ACPY(&pd->ndaddr, &nk->addr[didx], nk->af);
4861 				pd->naf = nk->af;
4862 			}
4863 #endif /* INET6 */
4864 			if (!afto) {
4865 				pf_translate_a(pd, pd->src, &nk->addr[sidx]);
4866 				pf_translate_a(pd, pd->dst, &nk->addr[didx]);
4867 			}
4868 
4869 			if (pd->rdomain != nk->rdomain)
4870 				pd->destchg = 1;
4871 			if (!afto && PF_ANEQ(pd->dst,
4872 				&nk->addr[didx], pd->af))
4873 				pd->destchg = 1;
4874 			pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
4875 
4876 			switch (pd->af) {
4877 			case AF_INET:
4878 #ifdef INET6
4879 				if (afto) {
4880 					if (pf_translate_icmp_af(pd, AF_INET6,
4881 					    &pd->hdr.icmp))
4882 						return (PF_DROP);
4883 					pd->proto = IPPROTO_ICMPV6;
4884 				}
4885 #endif /* INET6 */
4886 				pf_patch_16(pd,
4887 				    &pd->hdr.icmp.icmp_id, nk->port[iidx]);
4888 
4889 				m_copyback(pd->m, pd->off, ICMP_MINLEN,
4890 				    &pd->hdr.icmp, M_NOWAIT);
4891 				copyback = 1;
4892 				break;
4893 #ifdef INET6
4894 			case AF_INET6:
4895 				if (afto) {
4896 					if (pf_translate_icmp_af(pd, AF_INET,
4897 					    &pd->hdr.icmp6))
4898 						return (PF_DROP);
4899 					pd->proto = IPPROTO_ICMP;
4900 				}
4901 
4902 				pf_patch_16(pd,
4903 				    &pd->hdr.icmp6.icmp6_id, nk->port[iidx]);
4904 
4905 				m_copyback(pd->m, pd->off,
4906 				    sizeof(struct icmp6_hdr), &pd->hdr.icmp6,
4907 				    M_NOWAIT);
4908 				copyback = 1;
4909 				break;
4910 #endif /* INET6 */
4911 			}
4912 #ifdef	INET6
4913 			if (afto)
4914 				return (PF_AFRT);
4915 #endif /* INET6 */
4916 		}
4917 	} else {
4918 		/*
4919 		 * ICMP error message in response to a TCP/UDP packet.
4920 		 * Extract the inner TCP/UDP header and search for that state.
4921 		 */
4922 		struct pf_pdesc	 pd2;
4923 		struct ip	 h2;
4924 #ifdef INET6
4925 		struct ip6_hdr	 h2_6;
4926 #endif /* INET6 */
4927 		int		 ipoff2;
4928 
4929 		/* Initialize pd2 fields valid for both packets with pd. */
4930 		bzero(&pd2, sizeof(pd2));
4931 		pd2.af = pd->af;
4932 		pd2.dir = pd->dir;
4933 		pd2.kif = pd->kif;
4934 		pd2.m = pd->m;
4935 		pd2.rdomain = pd->rdomain;
4936 		/* Payload packet is from the opposite direction. */
4937 		pd2.sidx = (pd2.dir == PF_IN) ? 1 : 0;
4938 		pd2.didx = (pd2.dir == PF_IN) ? 0 : 1;
4939 		switch (pd->af) {
4940 		case AF_INET:
4941 			/* offset of h2 in mbuf chain */
4942 			ipoff2 = pd->off + ICMP_MINLEN;
4943 
4944 			if (!pf_pull_hdr(pd2.m, ipoff2, &h2, sizeof(h2),
4945 			    NULL, reason, pd2.af)) {
4946 				DPFPRINTF(LOG_NOTICE,
4947 				    "ICMP error message too short (ip)");
4948 				return (PF_DROP);
4949 			}
4950 			/*
4951 			 * ICMP error messages don't refer to non-first
4952 			 * fragments
4953 			 */
4954 			if (h2.ip_off & htons(IP_OFFMASK)) {
4955 				REASON_SET(reason, PFRES_FRAG);
4956 				return (PF_DROP);
4957 			}
4958 
4959 			/* offset of protocol header that follows h2 */
4960 			pd2.off = ipoff2 + (h2.ip_hl << 2);
4961 
4962 			pd2.proto = h2.ip_p;
4963 			pd2.tot_len = ntohs(h2.ip_len);
4964 			pd2.src = (struct pf_addr *)&h2.ip_src;
4965 			pd2.dst = (struct pf_addr *)&h2.ip_dst;
4966 			break;
4967 #ifdef INET6
4968 		case AF_INET6:
4969 			ipoff2 = pd->off + sizeof(struct icmp6_hdr);
4970 
4971 			if (!pf_pull_hdr(pd2.m, ipoff2, &h2_6, sizeof(h2_6),
4972 			    NULL, reason, pd2.af)) {
4973 				DPFPRINTF(LOG_NOTICE,
4974 				    "ICMP error message too short (ip6)");
4975 				return (PF_DROP);
4976 			}
4977 
4978 			pd2.off = ipoff2;
4979 			if (pf_walk_header6(&pd2, &h2_6, reason) != PF_PASS)
4980 				return (PF_DROP);
4981 
4982 			pd2.tot_len = ntohs(h2_6.ip6_plen) +
4983 			    sizeof(struct ip6_hdr);
4984 			pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4985 			pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4986 			break;
4987 #endif /* INET6 */
4988 		default:
4989 			unhandled_af(pd->af);
4990 		}
4991 
4992 		switch (pd2.proto) {
4993 		case IPPROTO_TCP: {
4994 			struct tcphdr		*th = &pd2.hdr.tcp;
4995 			u_int32_t		 seq;
4996 			struct pf_state_peer	*src, *dst;
4997 			u_int8_t		 dws;
4998 
4999 			/*
5000 			 * Only the first 8 bytes of the TCP header can be
5001 			 * expected. Don't access any TCP header fields after
5002 			 * th_seq, an ackskew test is not possible.
5003 			 */
5004 			if (!pf_pull_hdr(pd2.m, pd2.off, th, 8, NULL, reason,
5005 			    pd2.af)) {
5006 				DPFPRINTF(LOG_NOTICE,
5007 				    "ICMP error message too short (tcp)");
5008 				return (PF_DROP);
5009 			}
5010 
5011 			key.af = pd2.af;
5012 			key.proto = IPPROTO_TCP;
5013 			key.rdomain = pd2.rdomain;
5014 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5015 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5016 			key.port[pd2.sidx] = th->th_sport;
5017 			key.port[pd2.didx] = th->th_dport;
5018 
5019 			STATE_LOOKUP(pd2.kif, &key, pd2.dir, *state, pd2.m);
5020 
5021 			if (pd2.dir == (*state)->direction) {
5022 				if (PF_REVERSED_KEY((*state)->key, pd->af)) {
5023 					src = &(*state)->src;
5024 					dst = &(*state)->dst;
5025 				} else {
5026 					src = &(*state)->dst;
5027 					dst = &(*state)->src;
5028 				}
5029 			} else {
5030 				if (PF_REVERSED_KEY((*state)->key, pd->af)) {
5031 					src = &(*state)->dst;
5032 					dst = &(*state)->src;
5033 				} else {
5034 					src = &(*state)->src;
5035 					dst = &(*state)->dst;
5036 				}
5037 			}
5038 
5039 			if (src->wscale && dst->wscale)
5040 				dws = dst->wscale & PF_WSCALE_MASK;
5041 			else
5042 				dws = 0;
5043 
5044 			/* Demodulate sequence number */
5045 			seq = ntohl(th->th_seq) - src->seqdiff;
5046 			if (src->seqdiff) {
5047 				pf_patch_32(pd, &th->th_seq, htonl(seq));
5048 				copyback = 1;
5049 			}
5050 
5051 			if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5052 			    (!SEQ_GEQ(src->seqhi, seq) || !SEQ_GEQ(seq,
5053 			    src->seqlo - (dst->max_win << dws)))) {
5054 				if (pf_status.debug >= LOG_NOTICE) {
5055 					log(LOG_NOTICE,
5056 					    "pf: BAD ICMP %d:%d ",
5057 					    icmptype, pd->hdr.icmp.icmp_code);
5058 					pf_print_host(pd->src, 0, pd->af);
5059 					addlog(" -> ");
5060 					pf_print_host(pd->dst, 0, pd->af);
5061 					addlog(" state: ");
5062 					pf_print_state(*state);
5063 					addlog(" seq=%u\n", seq);
5064 				}
5065 				REASON_SET(reason, PFRES_BADSTATE);
5066 				return (PF_DROP);
5067 			} else {
5068 				if (pf_status.debug >= LOG_DEBUG) {
5069 					log(LOG_DEBUG,
5070 					    "pf: OK ICMP %d:%d ",
5071 					    icmptype, pd->hdr.icmp.icmp_code);
5072 					pf_print_host(pd->src, 0, pd->af);
5073 					addlog(" -> ");
5074 					pf_print_host(pd->dst, 0, pd->af);
5075 					addlog(" state: ");
5076 					pf_print_state(*state);
5077 					addlog(" seq=%u\n", seq);
5078 				}
5079 			}
5080 
5081 			/* translate source/destination address, if necessary */
5082 			if ((*state)->key[PF_SK_WIRE] !=
5083 			    (*state)->key[PF_SK_STACK]) {
5084 				struct pf_state_key	*nk;
5085 				int			 afto, sidx, didx;
5086 
5087 				if (PF_REVERSED_KEY((*state)->key, pd->af))
5088 					nk = (*state)->key[pd->sidx];
5089 				else
5090 					nk = (*state)->key[pd->didx];
5091 
5092 				afto = pd->af != nk->af;
5093 				sidx = afto ? pd2.didx : pd2.sidx;
5094 				didx = afto ? pd2.sidx : pd2.didx;
5095 
5096 #ifdef INET6
5097 				if (afto) {
5098 					if (pf_translate_icmp_af(pd, nk->af,
5099 					    &pd->hdr.icmp))
5100 						return (PF_DROP);
5101 					m_copyback(pd->m, pd->off,
5102 					    sizeof(struct icmp6_hdr),
5103 					    &pd->hdr.icmp6, M_NOWAIT);
5104 					if (pf_change_icmp_af(pd->m, ipoff2,
5105 					    pd, &pd2, &nk->addr[sidx],
5106 					    &nk->addr[didx], pd->af, nk->af))
5107 						return (PF_DROP);
5108 					if (nk->af == AF_INET)
5109 						pd->proto = IPPROTO_ICMP;
5110 					else
5111 						pd->proto = IPPROTO_ICMPV6;
5112 					pd->m->m_pkthdr.ph_rtableid =
5113 					    nk->rdomain;
5114 					pd->destchg = 1;
5115 					PF_ACPY(&pd->nsaddr,
5116 					    &nk->addr[pd2.sidx], nk->af);
5117 					PF_ACPY(&pd->ndaddr,
5118 					    &nk->addr[pd2.didx], nk->af);
5119 					pd->naf = nk->af;
5120 
5121 					pf_patch_16(pd,
5122 					    &th->th_sport, nk->port[sidx]);
5123 					pf_patch_16(pd,
5124 					    &th->th_dport, nk->port[didx]);
5125 
5126 					m_copyback(pd2.m, pd2.off, 8, th,
5127 					    M_NOWAIT);
5128 					return (PF_AFRT);
5129 				}
5130 #endif	/* INET6 */
5131 				if (PF_ANEQ(pd2.src,
5132 				    &nk->addr[pd2.sidx], pd2.af) ||
5133 				    nk->port[pd2.sidx] != th->th_sport)
5134 					pf_translate_icmp(pd, pd2.src,
5135 					    &th->th_sport, pd->dst,
5136 					    &nk->addr[pd2.sidx],
5137 					    nk->port[pd2.sidx]);
5138 
5139 				if (PF_ANEQ(pd2.dst, &nk->addr[pd2.didx],
5140 				    pd2.af) || pd2.rdomain != nk->rdomain)
5141 					pd->destchg = 1;
5142 				pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
5143 
5144 				if (PF_ANEQ(pd2.dst,
5145 				    &nk->addr[pd2.didx], pd2.af) ||
5146 				    nk->port[pd2.didx] != th->th_dport)
5147 					pf_translate_icmp(pd, pd2.dst,
5148 					    &th->th_dport, pd->src,
5149 					    &nk->addr[pd2.didx],
5150 					    nk->port[pd2.didx]);
5151 				copyback = 1;
5152 			}
5153 
5154 			if (copyback) {
5155 				switch (pd2.af) {
5156 				case AF_INET:
5157 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
5158 					    &pd->hdr.icmp, M_NOWAIT);
5159 					m_copyback(pd2.m, ipoff2, sizeof(h2),
5160 					    &h2, M_NOWAIT);
5161 					break;
5162 #ifdef INET6
5163 				case AF_INET6:
5164 					m_copyback(pd->m, pd->off,
5165 					    sizeof(struct icmp6_hdr),
5166 					    &pd->hdr.icmp6, M_NOWAIT);
5167 					m_copyback(pd2.m, ipoff2, sizeof(h2_6),
5168 					    &h2_6, M_NOWAIT);
5169 					break;
5170 #endif /* INET6 */
5171 				}
5172 				m_copyback(pd2.m, pd2.off, 8, th, M_NOWAIT);
5173 			}
5174 			break;
5175 		}
5176 		case IPPROTO_UDP: {
5177 			struct udphdr	*uh = &pd2.hdr.udp;
5178 
5179 			if (!pf_pull_hdr(pd2.m, pd2.off, uh, sizeof(*uh),
5180 			    NULL, reason, pd2.af)) {
5181 				DPFPRINTF(LOG_NOTICE,
5182 				    "ICMP error message too short (udp)");
5183 				return (PF_DROP);
5184 			}
5185 
5186 			key.af = pd2.af;
5187 			key.proto = IPPROTO_UDP;
5188 			key.rdomain = pd2.rdomain;
5189 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5190 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5191 			key.port[pd2.sidx] = uh->uh_sport;
5192 			key.port[pd2.didx] = uh->uh_dport;
5193 
5194 			STATE_LOOKUP(pd2.kif, &key, pd2.dir, *state, pd2.m);
5195 
5196 			/* translate source/destination address, if necessary */
5197 			if ((*state)->key[PF_SK_WIRE] !=
5198 			    (*state)->key[PF_SK_STACK]) {
5199 				struct pf_state_key	*nk;
5200 				int			 afto, sidx, didx;
5201 
5202 				if (PF_REVERSED_KEY((*state)->key, pd->af))
5203 					nk = (*state)->key[pd->sidx];
5204 				else
5205 					nk = (*state)->key[pd->didx];
5206 
5207 				afto = pd->af != nk->af;
5208 				sidx = afto ? pd2.didx : pd2.sidx;
5209 				didx = afto ? pd2.sidx : pd2.didx;
5210 
5211 #ifdef INET6
5212 				if (afto) {
5213 					if (pf_translate_icmp_af(pd, nk->af,
5214 					    &pd->hdr.icmp))
5215 						return (PF_DROP);
5216 					m_copyback(pd->m, pd->off,
5217 					    sizeof(struct icmp6_hdr),
5218 					    &pd->hdr.icmp6, M_NOWAIT);
5219 					if (pf_change_icmp_af(pd->m, ipoff2,
5220 					    pd, &pd2, &nk->addr[sidx],
5221 					    &nk->addr[didx], pd->af, nk->af))
5222 						return (PF_DROP);
5223 					if (nk->af == AF_INET)
5224 						pd->proto = IPPROTO_ICMP;
5225 					else
5226 						pd->proto = IPPROTO_ICMPV6;
5227 					pd->m->m_pkthdr.ph_rtableid =
5228 					    nk->rdomain;
5229 					pd->destchg = 1;
5230 					PF_ACPY(&pd->nsaddr,
5231 					    &nk->addr[pd2.sidx], nk->af);
5232 					PF_ACPY(&pd->ndaddr,
5233 					    &nk->addr[pd2.didx], nk->af);
5234 					pd->naf = nk->af;
5235 
5236 					pf_patch_16(pd,
5237 					    &uh->uh_sport, nk->port[sidx]);
5238 					pf_patch_16(pd,
5239 					    &uh->uh_dport, nk->port[didx]);
5240 
5241 					m_copyback(pd2.m, pd2.off, sizeof(*uh),
5242 					    uh, M_NOWAIT);
5243 					return (PF_AFRT);
5244 				}
5245 #endif /* INET6 */
5246 
5247 				if (PF_ANEQ(pd2.src,
5248 				    &nk->addr[pd2.sidx], pd2.af) ||
5249 				    nk->port[pd2.sidx] != uh->uh_sport)
5250 					pf_translate_icmp(pd, pd2.src,
5251 					    &uh->uh_sport, pd->dst,
5252 					    &nk->addr[pd2.sidx],
5253 					    nk->port[pd2.sidx]);
5254 
5255 				if (PF_ANEQ(pd2.dst, &nk->addr[pd2.didx],
5256 				    pd2.af) || pd2.rdomain != nk->rdomain)
5257 					pd->destchg = 1;
5258 				pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
5259 
5260 				if (PF_ANEQ(pd2.dst,
5261 				    &nk->addr[pd2.didx], pd2.af) ||
5262 				    nk->port[pd2.didx] != uh->uh_dport)
5263 					pf_translate_icmp(pd, pd2.dst,
5264 					    &uh->uh_dport, pd->src,
5265 					    &nk->addr[pd2.didx],
5266 					    nk->port[pd2.didx]);
5267 
5268 				switch (pd2.af) {
5269 				case AF_INET:
5270 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
5271 					    &pd->hdr.icmp, M_NOWAIT);
5272 					m_copyback(pd2.m, ipoff2, sizeof(h2),
5273 					    &h2, M_NOWAIT);
5274 					break;
5275 #ifdef INET6
5276 				case AF_INET6:
5277 					m_copyback(pd->m, pd->off,
5278 					    sizeof(struct icmp6_hdr),
5279 					    &pd->hdr.icmp6, M_NOWAIT);
5280 					m_copyback(pd2.m, ipoff2, sizeof(h2_6),
5281 					    &h2_6, M_NOWAIT);
5282 					break;
5283 #endif /* INET6 */
5284 				}
5285 				/* Avoid recomputing quoted UDP checksum.
5286 				 * note: udp6 0 csum invalid per rfc2460 p27.
5287 				 * but presumed nothing cares in this context */
5288 				pf_patch_16(pd, &uh->uh_sum, 0);
5289 				m_copyback(pd2.m, pd2.off, sizeof(*uh), uh,
5290 				    M_NOWAIT);
5291 				copyback = 1;
5292 			}
5293 			break;
5294 		}
5295 		case IPPROTO_ICMP: {
5296 			struct icmp	*iih = &pd2.hdr.icmp;
5297 
5298 			if (pd2.af != AF_INET) {
5299 				REASON_SET(reason, PFRES_NORM);
5300 				return (PF_DROP);
5301 			}
5302 
5303 			if (!pf_pull_hdr(pd2.m, pd2.off, iih, ICMP_MINLEN,
5304 			    NULL, reason, pd2.af)) {
5305 				DPFPRINTF(LOG_NOTICE,
5306 				    "ICMP error message too short (icmp)");
5307 				return (PF_DROP);
5308 			}
5309 
5310 			pf_icmp_mapping(&pd2, iih->icmp_type,
5311 			    &icmp_dir, &virtual_id, &virtual_type);
5312 
5313 			ret = pf_icmp_state_lookup(&pd2, &key, state,
5314 			    virtual_id, virtual_type, icmp_dir, &iidx, 0, 1);
5315 			if (ret >= 0)
5316 				return (ret);
5317 
5318 			/* translate source/destination address, if necessary */
5319 			if ((*state)->key[PF_SK_WIRE] !=
5320 			    (*state)->key[PF_SK_STACK]) {
5321 				struct pf_state_key	*nk;
5322 				int			 afto, sidx, didx;
5323 
5324 				if (PF_REVERSED_KEY((*state)->key, pd->af))
5325 					nk = (*state)->key[pd->sidx];
5326 				else
5327 					nk = (*state)->key[pd->didx];
5328 
5329 				afto = pd->af != nk->af;
5330 				sidx = afto ? pd2.didx : pd2.sidx;
5331 				didx = afto ? pd2.sidx : pd2.didx;
5332 				iidx = afto ? !iidx : iidx;
5333 
5334 #ifdef INET6
5335 				if (afto) {
5336 					if (nk->af != AF_INET6)
5337 						return (PF_DROP);
5338 					if (pf_translate_icmp_af(pd, nk->af,
5339 					    &pd->hdr.icmp))
5340 						return (PF_DROP);
5341 					m_copyback(pd->m, pd->off,
5342 					    sizeof(struct icmp6_hdr),
5343 					    &pd->hdr.icmp6, M_NOWAIT);
5344 					if (pf_change_icmp_af(pd->m, ipoff2,
5345 					    pd, &pd2, &nk->addr[sidx],
5346 					    &nk->addr[didx], pd->af, nk->af))
5347 						return (PF_DROP);
5348 					pd->proto = IPPROTO_ICMPV6;
5349 					if (pf_translate_icmp_af(pd,
5350 						nk->af, iih))
5351 						return (PF_DROP);
5352 					if (virtual_type == htons(ICMP_ECHO))
5353 						pf_patch_16(pd, &iih->icmp_id,
5354 						    nk->port[iidx]);
5355 					m_copyback(pd2.m, pd2.off, ICMP_MINLEN,
5356 					    iih, M_NOWAIT);
5357 					pd->m->m_pkthdr.ph_rtableid =
5358 					    nk->rdomain;
5359 					pd->destchg = 1;
5360 					PF_ACPY(&pd->nsaddr,
5361 					    &nk->addr[pd2.sidx], nk->af);
5362 					PF_ACPY(&pd->ndaddr,
5363 					    &nk->addr[pd2.didx], nk->af);
5364 					pd->naf = nk->af;
5365 					return (PF_AFRT);
5366 				}
5367 #endif /* INET6 */
5368 
5369 				if (PF_ANEQ(pd2.src,
5370 				    &nk->addr[pd2.sidx], pd2.af) ||
5371 				    (virtual_type == htons(ICMP_ECHO) &&
5372 				    nk->port[iidx] != iih->icmp_id))
5373 					pf_translate_icmp(pd, pd2.src,
5374 					    (virtual_type == htons(ICMP_ECHO)) ?
5375 					    &iih->icmp_id : NULL,
5376 					    pd->dst, &nk->addr[pd2.sidx],
5377 					    (virtual_type == htons(ICMP_ECHO)) ?
5378 					    nk->port[iidx] : 0);
5379 
5380 				if (PF_ANEQ(pd2.dst, &nk->addr[pd2.didx],
5381 				    pd2.af) || pd2.rdomain != nk->rdomain)
5382 					pd->destchg = 1;
5383 				pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
5384 
5385 				if (PF_ANEQ(pd2.dst,
5386 				    &nk->addr[pd2.didx], pd2.af))
5387 					pf_translate_icmp(pd, pd2.dst, NULL,
5388 					    pd->src, &nk->addr[pd2.didx], 0);
5389 
5390 				m_copyback(pd->m, pd->off, ICMP_MINLEN,
5391 				    &pd->hdr.icmp, M_NOWAIT);
5392 				m_copyback(pd2.m, ipoff2, sizeof(h2), &h2,
5393 				    M_NOWAIT);
5394 				m_copyback(pd2.m, pd2.off, ICMP_MINLEN, iih,
5395 				    M_NOWAIT);
5396 				copyback = 1;
5397 			}
5398 			break;
5399 		}
5400 #ifdef INET6
5401 		case IPPROTO_ICMPV6: {
5402 			struct icmp6_hdr	*iih = &pd2.hdr.icmp6;
5403 
5404 			if (pd2.af != AF_INET6) {
5405 				REASON_SET(reason, PFRES_NORM);
5406 				return (PF_DROP);
5407 			}
5408 
5409 			if (!pf_pull_hdr(pd2.m, pd2.off, iih,
5410 			    sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5411 				DPFPRINTF(LOG_NOTICE,
5412 				    "ICMP error message too short (icmp6)");
5413 				return (PF_DROP);
5414 			}
5415 
5416 			pf_icmp_mapping(&pd2, iih->icmp6_type,
5417 			    &icmp_dir, &virtual_id, &virtual_type);
5418 			ret = pf_icmp_state_lookup(&pd2, &key, state,
5419 			    virtual_id, virtual_type, icmp_dir, &iidx, 0, 1);
5420 			/* IPv6? try matching a multicast address */
5421 			if (ret == PF_DROP && pd2.af == AF_INET6 &&
5422 			    icmp_dir == PF_OUT)
5423 				ret = pf_icmp_state_lookup(&pd2, &key, state,
5424 				    virtual_id, virtual_type, icmp_dir, &iidx,
5425 				    1, 1);
5426 			if (ret >= 0)
5427 				return (ret);
5428 
5429 			/* translate source/destination address, if necessary */
5430 			if ((*state)->key[PF_SK_WIRE] !=
5431 			    (*state)->key[PF_SK_STACK]) {
5432 				struct pf_state_key	*nk;
5433 				int			 afto, sidx, didx;
5434 
5435 				if (PF_REVERSED_KEY((*state)->key, pd->af))
5436 					nk = (*state)->key[pd->sidx];
5437 				else
5438 					nk = (*state)->key[pd->didx];
5439 
5440 				afto = pd->af != nk->af;
5441 				sidx = afto ? pd2.didx : pd2.sidx;
5442 				didx = afto ? pd2.sidx : pd2.didx;
5443 				iidx = afto ? !iidx : iidx;
5444 
5445 				if (afto) {
5446 					if (nk->af != AF_INET)
5447 						return (PF_DROP);
5448 					if (pf_translate_icmp_af(pd, nk->af,
5449 					    &pd->hdr.icmp))
5450 						return (PF_DROP);
5451 					m_copyback(pd->m, pd->off,
5452 					    sizeof(struct icmp6_hdr),
5453 					    &pd->hdr.icmp6, M_NOWAIT);
5454 					if (pf_change_icmp_af(pd->m, ipoff2,
5455 					    pd, &pd2, &nk->addr[sidx],
5456 					    &nk->addr[didx], pd->af, nk->af))
5457 						return (PF_DROP);
5458 					pd->proto = IPPROTO_ICMP;
5459 					if (pf_translate_icmp_af(pd,
5460 						nk->af, iih))
5461 						return (PF_DROP);
5462 					if (virtual_type ==
5463 					    htons(ICMP6_ECHO_REQUEST))
5464 						pf_patch_16(pd, &iih->icmp6_id,
5465 						    nk->port[iidx]);
5466 					m_copyback(pd2.m, pd2.off,
5467 					    sizeof(struct icmp6_hdr), iih,
5468 					    M_NOWAIT);
5469 					pd->m->m_pkthdr.ph_rtableid =
5470 					    nk->rdomain;
5471 					pd->destchg = 1;
5472 					PF_ACPY(&pd->nsaddr,
5473 					    &nk->addr[pd2.sidx], nk->af);
5474 					PF_ACPY(&pd->ndaddr,
5475 					    &nk->addr[pd2.didx], nk->af);
5476 					pd->naf = nk->af;
5477 					return (PF_AFRT);
5478 				}
5479 
5480 				if (PF_ANEQ(pd2.src,
5481 				    &nk->addr[pd2.sidx], pd2.af) ||
5482 				    ((virtual_type ==
5483 				    htons(ICMP6_ECHO_REQUEST)) &&
5484 				    nk->port[pd2.sidx] != iih->icmp6_id))
5485 					pf_translate_icmp(pd, pd2.src,
5486 					    (virtual_type ==
5487 					    htons(ICMP6_ECHO_REQUEST))
5488 					    ? &iih->icmp6_id : NULL,
5489 					    pd->dst, &nk->addr[pd2.sidx],
5490 					    (virtual_type ==
5491 					    htons(ICMP6_ECHO_REQUEST))
5492 					    ? nk->port[iidx] : 0);
5493 
5494 				if (PF_ANEQ(pd2.dst, &nk->addr[pd2.didx],
5495 				    pd2.af) || pd2.rdomain != nk->rdomain)
5496 					pd->destchg = 1;
5497 				pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
5498 
5499 				if (PF_ANEQ(pd2.dst,
5500 				    &nk->addr[pd2.didx], pd2.af))
5501 					pf_translate_icmp(pd, pd2.dst, NULL,
5502 					    pd->src, &nk->addr[pd2.didx], 0);
5503 
5504 				m_copyback(pd->m, pd->off,
5505 				    sizeof(struct icmp6_hdr), &pd->hdr.icmp6,
5506 				    M_NOWAIT);
5507 				m_copyback(pd2.m, ipoff2, sizeof(h2_6), &h2_6,
5508 				    M_NOWAIT);
5509 				m_copyback(pd2.m, pd2.off,
5510 				    sizeof(struct icmp6_hdr), iih, M_NOWAIT);
5511 				copyback = 1;
5512 			}
5513 			break;
5514 		}
5515 #endif /* INET6 */
5516 		default: {
5517 			key.af = pd2.af;
5518 			key.proto = pd2.proto;
5519 			key.rdomain = pd2.rdomain;
5520 			PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5521 			PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5522 			key.port[0] = key.port[1] = 0;
5523 
5524 			STATE_LOOKUP(pd2.kif, &key, pd2.dir, *state, pd2.m);
5525 
5526 			/* translate source/destination address, if necessary */
5527 			if ((*state)->key[PF_SK_WIRE] !=
5528 			    (*state)->key[PF_SK_STACK]) {
5529 				struct pf_state_key *nk =
5530 				    (*state)->key[pd->didx];
5531 
5532 				if (PF_ANEQ(pd2.src,
5533 				    &nk->addr[pd2.sidx], pd2.af))
5534 					pf_translate_icmp(pd, pd2.src, NULL,
5535 					    pd->dst, &nk->addr[pd2.sidx], 0);
5536 
5537 				if (PF_ANEQ(pd2.dst, &nk->addr[pd2.didx],
5538 				    pd2.af) || pd2.rdomain != nk->rdomain)
5539 					pd->destchg = 1;
5540 				pd->m->m_pkthdr.ph_rtableid = nk->rdomain;
5541 
5542 				if (PF_ANEQ(pd2.dst,
5543 				    &nk->addr[pd2.didx], pd2.af))
5544 					pf_translate_icmp(pd, pd2.dst, NULL,
5545 					    pd->src, &nk->addr[pd2.didx], 0);
5546 
5547 				switch (pd2.af) {
5548 				case AF_INET:
5549 					m_copyback(pd->m, pd->off, ICMP_MINLEN,
5550 					    &pd->hdr.icmp, M_NOWAIT);
5551 					m_copyback(pd2.m, ipoff2, sizeof(h2),
5552 					    &h2, M_NOWAIT);
5553 					break;
5554 #ifdef INET6
5555 				case AF_INET6:
5556 					m_copyback(pd->m, pd->off,
5557 					    sizeof(struct icmp6_hdr),
5558 					    &pd->hdr.icmp6, M_NOWAIT);
5559 					m_copyback(pd2.m, ipoff2, sizeof(h2_6),
5560 					    &h2_6, M_NOWAIT);
5561 					break;
5562 #endif /* INET6 */
5563 				}
5564 				copyback = 1;
5565 			}
5566 			break;
5567 		}
5568 		}
5569 	}
5570 	if (copyback) {
5571 		m_copyback(pd->m, pd->off, pd->hdrlen, &pd->hdr, M_NOWAIT);
5572 	}
5573 
5574 	return (PF_PASS);
5575 }
5576 
5577 /*
5578  * ipoff and off are measured from the start of the mbuf chain.
5579  * h must be at "ipoff" on the mbuf chain.
5580  */
5581 void *
5582 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5583     u_short *actionp, u_short *reasonp, sa_family_t af)
5584 {
5585 	switch (af) {
5586 	case AF_INET: {
5587 		struct ip	*h = mtod(m, struct ip *);
5588 		u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5589 
5590 		if (fragoff) {
5591 			if (fragoff >= len)
5592 				ACTION_SET(actionp, PF_PASS);
5593 			else {
5594 				ACTION_SET(actionp, PF_DROP);
5595 				REASON_SET(reasonp, PFRES_FRAG);
5596 			}
5597 			return (NULL);
5598 		}
5599 		if (m->m_pkthdr.len < off + len ||
5600 		    ntohs(h->ip_len) < off + len) {
5601 			ACTION_SET(actionp, PF_DROP);
5602 			REASON_SET(reasonp, PFRES_SHORT);
5603 			return (NULL);
5604 		}
5605 		break;
5606 	}
5607 #ifdef INET6
5608 	case AF_INET6: {
5609 		struct ip6_hdr	*h = mtod(m, struct ip6_hdr *);
5610 
5611 		if (m->m_pkthdr.len < off + len ||
5612 		    (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5613 		    (unsigned)(off + len)) {
5614 			ACTION_SET(actionp, PF_DROP);
5615 			REASON_SET(reasonp, PFRES_SHORT);
5616 			return (NULL);
5617 		}
5618 		break;
5619 	}
5620 #endif /* INET6 */
5621 	}
5622 	m_copydata(m, off, len, p);
5623 	return (p);
5624 }
5625 
5626 int
5627 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5628     int rtableid)
5629 {
5630 	struct sockaddr_storage	 ss;
5631 	struct sockaddr_in	*dst;
5632 	int			 ret = 1;
5633 	int			 check_mpath;
5634 #ifdef INET6
5635 	struct sockaddr_in6	*dst6;
5636 #endif	/* INET6 */
5637 	struct rtentry		*rt = NULL;
5638 
5639 	check_mpath = 0;
5640 	memset(&ss, 0, sizeof(ss));
5641 	switch (af) {
5642 	case AF_INET:
5643 		dst = (struct sockaddr_in *)&ss;
5644 		dst->sin_family = AF_INET;
5645 		dst->sin_len = sizeof(*dst);
5646 		dst->sin_addr = addr->v4;
5647 		if (ipmultipath)
5648 			check_mpath = 1;
5649 		break;
5650 #ifdef INET6
5651 	case AF_INET6:
5652 		/*
5653 		 * Skip check for addresses with embedded interface scope,
5654 		 * as they would always match anyway.
5655 		 */
5656 		if (IN6_IS_SCOPE_EMBED(&addr->v6))
5657 			goto out;
5658 		dst6 = (struct sockaddr_in6 *)&ss;
5659 		dst6->sin6_family = AF_INET6;
5660 		dst6->sin6_len = sizeof(*dst6);
5661 		dst6->sin6_addr = addr->v6;
5662 		if (ip6_multipath)
5663 			check_mpath = 1;
5664 		break;
5665 #endif /* INET6 */
5666 	}
5667 
5668 	/* Skip checks for ipsec interfaces */
5669 	if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5670 		goto out;
5671 
5672 	rt = rtalloc((struct sockaddr *)&ss, 0, rtableid);
5673 	if (rt != NULL) {
5674 		/* No interface given, this is a no-route check */
5675 		if (kif == NULL)
5676 			goto out;
5677 
5678 		if (kif->pfik_ifp == NULL) {
5679 			ret = 0;
5680 			goto out;
5681 		}
5682 
5683 		/* Perform uRPF check if passed input interface */
5684 		ret = 0;
5685 		do {
5686 			if (rt->rt_ifidx == kif->pfik_ifp->if_index) {
5687 				ret = 1;
5688 #if NCARP > 0
5689 			} else {
5690 				struct ifnet	*ifp;
5691 
5692 				ifp = if_get(rt->rt_ifidx);
5693 				if (ifp != NULL && ifp->if_type == IFT_CARP &&
5694 				    ifp->if_carpdev == kif->pfik_ifp)
5695 					ret = 1;
5696 				if_put(ifp);
5697 #endif /* NCARP */
5698 			}
5699 
5700 			rt = rtable_iterate(rt);
5701 		} while (check_mpath == 1 && rt != NULL && ret == 0);
5702 	} else
5703 		ret = 0;
5704 out:
5705 	rtfree(rt);
5706 	return (ret);
5707 }
5708 
5709 int
5710 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw,
5711     int rtableid)
5712 {
5713 	struct sockaddr_storage	 ss;
5714 	struct sockaddr_in	*dst;
5715 #ifdef INET6
5716 	struct sockaddr_in6	*dst6;
5717 #endif	/* INET6 */
5718 	struct rtentry		*rt;
5719 	int			 ret = 0;
5720 
5721 	memset(&ss, 0, sizeof(ss));
5722 	switch (af) {
5723 	case AF_INET:
5724 		dst = (struct sockaddr_in *)&ss;
5725 		dst->sin_family = AF_INET;
5726 		dst->sin_len = sizeof(*dst);
5727 		dst->sin_addr = addr->v4;
5728 		break;
5729 #ifdef INET6
5730 	case AF_INET6:
5731 		dst6 = (struct sockaddr_in6 *)&ss;
5732 		dst6->sin6_family = AF_INET6;
5733 		dst6->sin6_len = sizeof(*dst6);
5734 		dst6->sin6_addr = addr->v6;
5735 		break;
5736 #endif /* INET6 */
5737 	}
5738 
5739 	rt = rtalloc((struct sockaddr *)&ss, RT_RESOLVE, rtableid);
5740 	if (rt != NULL) {
5741 		if (rt->rt_labelid == aw->v.rtlabel)
5742 			ret = 1;
5743 		rtfree(rt);
5744 	}
5745 
5746 	return (ret);
5747 }
5748 
5749 /* pf_route() may change pd->m, adjust local copies after calling */
5750 void
5751 pf_route(struct pf_pdesc *pd, struct pf_rule *r, struct pf_state *s)
5752 {
5753 	struct mbuf		*m0, *m1;
5754 	struct sockaddr_in	*dst, sin;
5755 	struct rtentry		*rt = NULL;
5756 	struct ip		*ip;
5757 	struct ifnet		*ifp = NULL;
5758 	struct pf_addr		 naddr;
5759 	struct pf_src_node	*sns[PF_SN_MAX];
5760 	int			 error = 0;
5761 	unsigned int		 rtableid;
5762 
5763 	if (pd->m->m_pkthdr.pf.routed++ > 3) {
5764 		m_freem(pd->m);
5765 		pd->m = NULL;
5766 		return;
5767 	}
5768 
5769 	if (r->rt == PF_DUPTO) {
5770 		if ((m0 = m_dup_pkt(pd->m, max_linkhdr, M_NOWAIT)) == NULL)
5771 			return;
5772 	} else {
5773 		if ((r->rt == PF_REPLYTO) == (r->direction == pd->dir))
5774 			return;
5775 		m0 = pd->m;
5776 	}
5777 
5778 	if (m0->m_len < sizeof(struct ip)) {
5779 		DPFPRINTF(LOG_ERR,
5780 		    "%s: m0->m_len < sizeof(struct ip)", __func__);
5781 		goto bad;
5782 	}
5783 
5784 	ip = mtod(m0, struct ip *);
5785 
5786 	memset(&sin, 0, sizeof(sin));
5787 	dst = &sin;
5788 	dst->sin_family = AF_INET;
5789 	dst->sin_len = sizeof(*dst);
5790 	dst->sin_addr = ip->ip_dst;
5791 	rtableid = m0->m_pkthdr.ph_rtableid;
5792 
5793 	if (s == NULL) {
5794 		bzero(sns, sizeof(sns));
5795 		if (pf_map_addr(AF_INET, r,
5796 		    (struct pf_addr *)&ip->ip_src,
5797 		    &naddr, NULL, sns, &r->route, PF_SN_ROUTE)) {
5798 			DPFPRINTF(LOG_ERR,
5799 			    "%s: pf_map_addr() failed", __func__);
5800 			goto bad;
5801 		}
5802 
5803 		if (!PF_AZERO(&naddr, AF_INET))
5804 			dst->sin_addr.s_addr = naddr.v4.s_addr;
5805 		ifp = r->route.kif ?
5806 		    r->route.kif->pfik_ifp : NULL;
5807 	} else {
5808 		if (!PF_AZERO(&s->rt_addr, AF_INET))
5809 			dst->sin_addr.s_addr =
5810 			    s->rt_addr.v4.s_addr;
5811 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5812 	}
5813 	if (ifp == NULL)
5814 		goto bad;
5815 
5816 	if (pd->kif->pfik_ifp != ifp) {
5817 		if (pf_test(AF_INET, PF_OUT, ifp, &m0) != PF_PASS)
5818 			goto bad;
5819 		else if (m0 == NULL)
5820 			goto done;
5821 		if (m0->m_len < sizeof(struct ip)) {
5822 			DPFPRINTF(LOG_ERR,
5823 			    "%s: m0->m_len < sizeof(struct ip)", __func__);
5824 			goto bad;
5825 		}
5826 		ip = mtod(m0, struct ip *);
5827 	}
5828 
5829 	in_proto_cksum_out(m0, ifp);
5830 
5831 	rt = rtalloc(sintosa(dst), RT_RESOLVE, rtableid);
5832 	if (!rtisvalid(rt)) {
5833 		ipstat_inc(ips_noroute);
5834 		goto bad;
5835 	}
5836 
5837 	if (ntohs(ip->ip_len) <= ifp->if_mtu) {
5838 		ip->ip_sum = 0;
5839 		if (ifp->if_capabilities & IFCAP_CSUM_IPv4)
5840 			m0->m_pkthdr.csum_flags |= M_IPV4_CSUM_OUT;
5841 		else {
5842 			ipstat_inc(ips_outswcsum);
5843 			ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5844 		}
5845 		error = ifp->if_output(ifp, m0, sintosa(dst), rt);
5846 		goto done;
5847 	}
5848 
5849 	/*
5850 	 * Too large for interface; fragment if possible.
5851 	 * Must be able to put at least 8 bytes per fragment.
5852 	 */
5853 	if (ip->ip_off & htons(IP_DF)) {
5854 		ipstat_inc(ips_cantfrag);
5855 		if (r->rt != PF_DUPTO) {
5856 			icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5857 			    ifp->if_mtu);
5858 			goto done;
5859 		} else
5860 			goto bad;
5861 	}
5862 
5863 	m1 = m0;
5864 	error = ip_fragment(m0, ifp, ifp->if_mtu);
5865 	if (error) {
5866 		m0 = NULL;
5867 		goto bad;
5868 	}
5869 
5870 	for (m0 = m1; m0; m0 = m1) {
5871 		m1 = m0->m_nextpkt;
5872 		m0->m_nextpkt = 0;
5873 		if (error == 0)
5874 			error = ifp->if_output(ifp, m0, sintosa(dst), rt);
5875 		else
5876 			m_freem(m0);
5877 	}
5878 
5879 	if (error == 0)
5880 		ipstat_inc(ips_fragmented);
5881 
5882 done:
5883 	if (r->rt != PF_DUPTO)
5884 		pd->m = NULL;
5885 	rtfree(rt);
5886 	return;
5887 
5888 bad:
5889 	m_freem(m0);
5890 	goto done;
5891 }
5892 
5893 #ifdef INET6
5894 /* pf_route6() may change pd->m, adjust local copies after calling */
5895 void
5896 pf_route6(struct pf_pdesc *pd, struct pf_rule *r, struct pf_state *s)
5897 {
5898 	struct mbuf		*m0;
5899 	struct sockaddr_in6	*dst, sin6;
5900 	struct rtentry		*rt = NULL;
5901 	struct ip6_hdr		*ip6;
5902 	struct ifnet		*ifp = NULL;
5903 	struct pf_addr		 naddr;
5904 	struct pf_src_node	*sns[PF_SN_MAX];
5905 	struct m_tag		*mtag;
5906 	unsigned int		 rtableid;
5907 
5908 	if (pd->m->m_pkthdr.pf.routed++ > 3) {
5909 		m_freem(pd->m);
5910 		pd->m = NULL;
5911 		return;
5912 	}
5913 
5914 	if (r->rt == PF_DUPTO) {
5915 		if ((m0 = m_dup_pkt(pd->m, max_linkhdr, M_NOWAIT)) == NULL)
5916 			return;
5917 	} else {
5918 		if ((r->rt == PF_REPLYTO) == (r->direction == pd->dir))
5919 			return;
5920 		m0 = pd->m;
5921 	}
5922 
5923 	if (m0->m_len < sizeof(struct ip6_hdr)) {
5924 		DPFPRINTF(LOG_ERR,
5925 		    "%s: m0->m_len < sizeof(struct ip6_hdr)", __func__);
5926 		goto bad;
5927 	}
5928 	ip6 = mtod(m0, struct ip6_hdr *);
5929 
5930 	memset(&sin6, 0, sizeof(sin6));
5931 	dst = &sin6;
5932 	dst->sin6_family = AF_INET6;
5933 	dst->sin6_len = sizeof(*dst);
5934 	dst->sin6_addr = ip6->ip6_dst;
5935 	rtableid = m0->m_pkthdr.ph_rtableid;
5936 
5937 	if (s == NULL) {
5938 		bzero(sns, sizeof(sns));
5939 		if (pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5940 		    &naddr, NULL, sns, &r->route, PF_SN_ROUTE)) {
5941 			DPFPRINTF(LOG_ERR,
5942 			    "%s: pf_map_addr() failed", __func__);
5943 			goto bad;
5944 		}
5945 		if (!PF_AZERO(&naddr, AF_INET6))
5946 			PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5947 			    &naddr, AF_INET6);
5948 		ifp = r->route.kif ? r->route.kif->pfik_ifp : NULL;
5949 	} else {
5950 		if (!PF_AZERO(&s->rt_addr, AF_INET6))
5951 			PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5952 			    &s->rt_addr, AF_INET6);
5953 		ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5954 	}
5955 	if (ifp == NULL)
5956 		goto bad;
5957 
5958 	if (pd->kif->pfik_ifp != ifp) {
5959 		if (pf_test(AF_INET6, PF_OUT, ifp, &m0) != PF_PASS)
5960 			goto bad;
5961 		else if (m0 == NULL)
5962 			goto done;
5963 		if (m0->m_len < sizeof(struct ip6_hdr)) {
5964 			DPFPRINTF(LOG_ERR,
5965 			    "%s: m0->m_len < sizeof(struct ip6_hdr)", __func__);
5966 			goto bad;
5967 		}
5968 	}
5969 
5970 	in6_proto_cksum_out(m0, ifp);
5971 
5972 	if (IN6_IS_SCOPE_EMBED(&dst->sin6_addr))
5973 		dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5974 
5975 	rt = rtalloc(sin6tosa(dst), RT_RESOLVE, rtableid);
5976 	if (!rtisvalid(rt)) {
5977 		ip6stat_inc(ip6s_noroute);
5978 		goto bad;
5979 	}
5980 
5981 	/*
5982 	 * If packet has been reassembled by PF earlier, we have to
5983 	 * use pf_refragment6() here to turn it back to fragments.
5984 	 */
5985 	if ((mtag = m_tag_find(m0, PACKET_TAG_PF_REASSEMBLED, NULL))) {
5986 		(void) pf_refragment6(&m0, mtag, dst, ifp, rt);
5987 	} else if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
5988 		ifp->if_output(ifp, m0, sin6tosa(dst), rt);
5989 	} else {
5990 		icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5991 	}
5992 
5993 done:
5994 	if (r->rt != PF_DUPTO)
5995 		pd->m = NULL;
5996 	rtfree(rt);
5997 	return;
5998 
5999 bad:
6000 	m_freem(m0);
6001 	goto done;
6002 }
6003 #endif /* INET6 */
6004 
6005 
6006 /*
6007  * check TCP checksum and set mbuf flag
6008  *   off is the offset where the protocol header starts
6009  *   len is the total length of protocol header plus payload
6010  * returns 0 when the checksum is valid, otherwise returns 1.
6011  * if the _OUT flag is set the checksum isn't done yet, consider these ok
6012  */
6013 int
6014 pf_check_tcp_cksum(struct mbuf *m, int off, int len, sa_family_t af)
6015 {
6016 	u_int16_t sum;
6017 
6018 	if (m->m_pkthdr.csum_flags &
6019 	    (M_TCP_CSUM_IN_OK | M_TCP_CSUM_OUT)) {
6020 		return (0);
6021 	}
6022 	if (m->m_pkthdr.csum_flags & M_TCP_CSUM_IN_BAD ||
6023 	    off < sizeof(struct ip) ||
6024 	    m->m_pkthdr.len < off + len) {
6025 		return (1);
6026 	}
6027 
6028 	/* need to do it in software */
6029 	tcpstat_inc(tcps_inswcsum);
6030 
6031 	switch (af) {
6032 	case AF_INET:
6033 		if (m->m_len < sizeof(struct ip))
6034 			return (1);
6035 
6036 		sum = in4_cksum(m, IPPROTO_TCP, off, len);
6037 		break;
6038 #ifdef INET6
6039 	case AF_INET6:
6040 		if (m->m_len < sizeof(struct ip6_hdr))
6041 			return (1);
6042 
6043 		sum = in6_cksum(m, IPPROTO_TCP, off, len);
6044 		break;
6045 #endif /* INET6 */
6046 	default:
6047 		unhandled_af(af);
6048 	}
6049 	if (sum) {
6050 		tcpstat_inc(tcps_rcvbadsum);
6051 		m->m_pkthdr.csum_flags |= M_TCP_CSUM_IN_BAD;
6052 		return (1);
6053 	}
6054 
6055 	m->m_pkthdr.csum_flags |= M_TCP_CSUM_IN_OK;
6056 	return (0);
6057 }
6058 
6059 struct pf_divert *
6060 pf_find_divert(struct mbuf *m)
6061 {
6062 	struct m_tag    *mtag;
6063 
6064 	if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
6065 		return (NULL);
6066 
6067 	return ((struct pf_divert *)(mtag + 1));
6068 }
6069 
6070 struct pf_divert *
6071 pf_get_divert(struct mbuf *m)
6072 {
6073 	struct m_tag    *mtag;
6074 
6075 	if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
6076 		mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
6077 		    M_NOWAIT);
6078 		if (mtag == NULL)
6079 			return (NULL);
6080 		bzero(mtag + 1, sizeof(struct pf_divert));
6081 		m_tag_prepend(m, mtag);
6082 	}
6083 
6084 	return ((struct pf_divert *)(mtag + 1));
6085 }
6086 
6087 #ifdef INET6
6088 int
6089 pf_walk_option6(struct pf_pdesc *pd, struct ip6_hdr *h, int off, int end,
6090     u_short *reason)
6091 {
6092 	struct ip6_opt		 opt;
6093 	struct ip6_opt_jumbo	 jumbo;
6094 
6095 	while (off < end) {
6096 		if (!pf_pull_hdr(pd->m, off, &opt.ip6o_type,
6097 		    sizeof(opt.ip6o_type), NULL, reason, AF_INET6)) {
6098 			DPFPRINTF(LOG_NOTICE, "IPv6 short opt type");
6099 			return (PF_DROP);
6100 		}
6101 		if (opt.ip6o_type == IP6OPT_PAD1) {
6102 			off++;
6103 			continue;
6104 		}
6105 		if (!pf_pull_hdr(pd->m, off, &opt, sizeof(opt),
6106 		    NULL, reason, AF_INET6)) {
6107 			DPFPRINTF(LOG_NOTICE, "IPv6 short opt");
6108 			return (PF_DROP);
6109 		}
6110 		if (off + sizeof(opt) + opt.ip6o_len > end) {
6111 			DPFPRINTF(LOG_NOTICE, "IPv6 long opt");
6112 			REASON_SET(reason, PFRES_IPOPTIONS);
6113 			return (PF_DROP);
6114 		}
6115 		switch (opt.ip6o_type) {
6116 		case IP6OPT_JUMBO:
6117 			if (pd->jumbolen != 0) {
6118 				DPFPRINTF(LOG_NOTICE, "IPv6 multiple jumbo");
6119 				REASON_SET(reason, PFRES_IPOPTIONS);
6120 				return (PF_DROP);
6121 			}
6122 			if (ntohs(h->ip6_plen) != 0) {
6123 				DPFPRINTF(LOG_NOTICE, "IPv6 bad jumbo plen");
6124 				REASON_SET(reason, PFRES_IPOPTIONS);
6125 				return (PF_DROP);
6126 			}
6127 			if (!pf_pull_hdr(pd->m, off, &jumbo, sizeof(jumbo),
6128 			    NULL, reason, AF_INET6)) {
6129 				DPFPRINTF(LOG_NOTICE, "IPv6 short jumbo");
6130 				return (PF_DROP);
6131 			}
6132 			memcpy(&pd->jumbolen, jumbo.ip6oj_jumbo_len,
6133 			    sizeof(pd->jumbolen));
6134 			pd->jumbolen = ntohl(pd->jumbolen);
6135 			if (pd->jumbolen < IPV6_MAXPACKET) {
6136 				DPFPRINTF(LOG_NOTICE, "IPv6 short jumbolen");
6137 				REASON_SET(reason, PFRES_IPOPTIONS);
6138 				return (PF_DROP);
6139 			}
6140 			break;
6141 		default:
6142 			break;
6143 		}
6144 		off += sizeof(opt) + opt.ip6o_len;
6145 	}
6146 
6147 	return (PF_PASS);
6148 }
6149 
6150 int
6151 pf_walk_header6(struct pf_pdesc *pd, struct ip6_hdr *h, u_short *reason)
6152 {
6153 	struct ip6_frag		 frag;
6154 	struct ip6_ext		 ext;
6155 	struct ip6_rthdr	 rthdr;
6156 	u_int32_t		 end;
6157 	int			 hdr_cnt = 0, fraghdr_cnt = 0, rthdr_cnt = 0;
6158 
6159 	pd->off += sizeof(struct ip6_hdr);
6160 	end = pd->off + ntohs(h->ip6_plen);
6161 	pd->fragoff = pd->extoff = pd->jumbolen = 0;
6162 	pd->proto = h->ip6_nxt;
6163 	for (;;) {
6164 		hdr_cnt++;
6165 		switch (pd->proto) {
6166 		case IPPROTO_FRAGMENT:
6167 			if (fraghdr_cnt++) {
6168 				DPFPRINTF(LOG_NOTICE, "IPv6 multiple fragment");
6169 				REASON_SET(reason, PFRES_FRAG);
6170 				return (PF_DROP);
6171 			}
6172 			/* jumbo payload packets cannot be fragmented */
6173 			if (pd->jumbolen != 0) {
6174 				DPFPRINTF(LOG_NOTICE, "IPv6 fragmented jumbo");
6175 				REASON_SET(reason, PFRES_FRAG);
6176 				return (PF_DROP);
6177 			}
6178 			if (!pf_pull_hdr(pd->m, pd->off, &frag, sizeof(frag),
6179 			    NULL, reason, AF_INET6)) {
6180 				DPFPRINTF(LOG_NOTICE, "IPv6 short fragment");
6181 				return (PF_DROP);
6182 			}
6183 			/* stop walking over non initial fragments */
6184 			if (ntohs((frag.ip6f_offlg & IP6F_OFF_MASK)) != 0) {
6185 				pd->fragoff = pd->off;
6186 				return (PF_PASS);
6187 			}
6188 			/* RFC6946:  reassemble only non atomic fragments */
6189 			if (frag.ip6f_offlg & IP6F_MORE_FRAG)
6190 				pd->fragoff = pd->off;
6191 			pd->off += sizeof(frag);
6192 			pd->proto = frag.ip6f_nxt;
6193 			break;
6194 		case IPPROTO_ROUTING:
6195 			if (rthdr_cnt++) {
6196 				DPFPRINTF(LOG_NOTICE, "IPv6 multiple rthdr");
6197 				REASON_SET(reason, PFRES_IPOPTIONS);
6198 				return (PF_DROP);
6199 			}
6200 			/* fragments may be short */
6201 			if (pd->fragoff != 0 && end < pd->off + sizeof(rthdr)) {
6202 				pd->off = pd->fragoff;
6203 				pd->proto = IPPROTO_FRAGMENT;
6204 				return (PF_PASS);
6205 			}
6206 			if (!pf_pull_hdr(pd->m, pd->off, &rthdr, sizeof(rthdr),
6207 			    NULL, reason, AF_INET6)) {
6208 				DPFPRINTF(LOG_NOTICE, "IPv6 short rthdr");
6209 				return (PF_DROP);
6210 			}
6211 			if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6212 				DPFPRINTF(LOG_NOTICE, "IPv6 rthdr0");
6213 				REASON_SET(reason, PFRES_IPOPTIONS);
6214 				return (PF_DROP);
6215 			}
6216 			/* FALLTHROUGH */
6217 		case IPPROTO_HOPOPTS:
6218 			/* RFC2460 4.1:  Hop-by-Hop only after IPv6 header */
6219 			if (pd->proto == IPPROTO_HOPOPTS && hdr_cnt > 1) {
6220 				DPFPRINTF(LOG_NOTICE, "IPv6 hopopts not first");
6221 				REASON_SET(reason, PFRES_IPOPTIONS);
6222 				return (PF_DROP);
6223 			}
6224 			/* FALLTHROUGH */
6225 		case IPPROTO_AH:
6226 		case IPPROTO_DSTOPTS:
6227 			/* fragments may be short */
6228 			if (pd->fragoff != 0 && end < pd->off + sizeof(ext)) {
6229 				pd->off = pd->fragoff;
6230 				pd->proto = IPPROTO_FRAGMENT;
6231 				return (PF_PASS);
6232 			}
6233 			if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
6234 			    NULL, reason, AF_INET6)) {
6235 				DPFPRINTF(LOG_NOTICE, "IPv6 short exthdr");
6236 				return (PF_DROP);
6237 			}
6238 			/* reassembly needs the ext header before the frag */
6239 			if (pd->fragoff == 0)
6240 				pd->extoff = pd->off;
6241 			if (pd->proto == IPPROTO_HOPOPTS && pd->fragoff == 0) {
6242 				if (pf_walk_option6(pd, h,
6243 				    pd->off + sizeof(ext),
6244 				    pd->off + (ext.ip6e_len + 1) * 8, reason)
6245 				    != PF_PASS)
6246 					return (PF_DROP);
6247 				if (ntohs(h->ip6_plen) == 0 &&
6248 				    pd->jumbolen != 0) {
6249 					DPFPRINTF(LOG_NOTICE,
6250 					    "IPv6 missing jumbo");
6251 					REASON_SET(reason, PFRES_IPOPTIONS);
6252 					return (PF_DROP);
6253 				}
6254 			}
6255 			if (pd->proto == IPPROTO_AH)
6256 				pd->off += (ext.ip6e_len + 2) * 4;
6257 			else
6258 				pd->off += (ext.ip6e_len + 1) * 8;
6259 			pd->proto = ext.ip6e_nxt;
6260 			break;
6261 		case IPPROTO_TCP:
6262 		case IPPROTO_UDP:
6263 		case IPPROTO_ICMPV6:
6264 			/* fragments may be short, ignore inner header then */
6265 			if (pd->fragoff != 0 && end < pd->off +
6266 			    (pd->proto == IPPROTO_TCP ? sizeof(struct tcphdr) :
6267 			    pd->proto == IPPROTO_UDP ? sizeof(struct udphdr) :
6268 			    sizeof(struct icmp6_hdr))) {
6269 				pd->off = pd->fragoff;
6270 				pd->proto = IPPROTO_FRAGMENT;
6271 			}
6272 			/* FALLTHROUGH */
6273 		default:
6274 			return (PF_PASS);
6275 		}
6276 	}
6277 }
6278 #endif /* INET6 */
6279 
6280 int
6281 pf_setup_pdesc(struct pf_pdesc *pd, sa_family_t af, int dir,
6282     struct pfi_kif *kif, struct mbuf *m, u_short *reason)
6283 {
6284 	bzero(pd, sizeof(*pd));
6285 	pd->dir = dir;
6286 	pd->kif = kif;		/* kif is NULL when called by pflog */
6287 	pd->m = m;
6288 	pd->sidx = (dir == PF_IN) ? 0 : 1;
6289 	pd->didx = (dir == PF_IN) ? 1 : 0;
6290 	pd->af = pd->naf = af;
6291 	pd->rdomain = rtable_l2(pd->m->m_pkthdr.ph_rtableid);
6292 
6293 	switch (pd->af) {
6294 	case AF_INET: {
6295 		struct ip	*h;
6296 
6297 		/* Check for illegal packets */
6298 		if (pd->m->m_pkthdr.len < (int)sizeof(struct ip)) {
6299 			REASON_SET(reason, PFRES_SHORT);
6300 			return (PF_DROP);
6301 		}
6302 
6303 		h = mtod(pd->m, struct ip *);
6304 		pd->off = h->ip_hl << 2;
6305 
6306 		if (pd->off < sizeof(struct ip) ||
6307 		    pd->off > ntohs(h->ip_len) ||
6308 		    pd->m->m_pkthdr.len < ntohs(h->ip_len)) {
6309 			REASON_SET(reason, PFRES_SHORT);
6310 			return (PF_DROP);
6311 		}
6312 
6313 		pd->src = (struct pf_addr *)&h->ip_src;
6314 		pd->dst = (struct pf_addr *)&h->ip_dst;
6315 		pd->virtual_proto = pd->proto = h->ip_p;
6316 		pd->tot_len = ntohs(h->ip_len);
6317 		pd->tos = h->ip_tos & ~IPTOS_ECN_MASK;
6318 		pd->ttl = h->ip_ttl;
6319 		if (h->ip_hl > 5)	/* has options */
6320 			pd->badopts++;
6321 
6322 		if (h->ip_off & htons(IP_MF | IP_OFFMASK))
6323 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
6324 
6325 		break;
6326 	}
6327 #ifdef INET6
6328 	case AF_INET6: {
6329 		struct ip6_hdr	*h;
6330 
6331 		/* Check for illegal packets */
6332 		if (pd->m->m_pkthdr.len < (int)sizeof(struct ip6_hdr)) {
6333 			REASON_SET(reason, PFRES_SHORT);
6334 			return (PF_DROP);
6335 		}
6336 
6337 		h = mtod(pd->m, struct ip6_hdr *);
6338 		pd->off = 0;
6339 
6340 		if (pd->m->m_pkthdr.len <
6341 		    sizeof(struct ip6_hdr) + ntohs(h->ip6_plen)) {
6342 			REASON_SET(reason, PFRES_SHORT);
6343 			return (PF_DROP);
6344 		}
6345 
6346 		if (pf_walk_header6(pd, h, reason) != PF_PASS)
6347 			return (PF_DROP);
6348 
6349 #if 1
6350 		/*
6351 		 * we do not support jumbogram yet.  if we keep going, zero
6352 		 * ip6_plen will do something bad, so drop the packet for now.
6353 		 */
6354 		if (pd->jumbolen != 0) {
6355 			REASON_SET(reason, PFRES_NORM);
6356 			return (PF_DROP);
6357 		}
6358 #endif	/* 1 */
6359 
6360 		pd->src = (struct pf_addr *)&h->ip6_src;
6361 		pd->dst = (struct pf_addr *)&h->ip6_dst;
6362 		pd->virtual_proto = pd->proto;
6363 		pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6364 		pd->tos = (ntohl(h->ip6_flow) & 0x0fc00000) >> 20;
6365 		pd->ttl = h->ip6_hlim;
6366 
6367 		if (pd->fragoff != 0)
6368 			pd->virtual_proto = PF_VPROTO_FRAGMENT;
6369 
6370 		break;
6371 	}
6372 #endif /* INET6 */
6373 	default:
6374 		panic("pf_setup_pdesc called with illegal af %u", pd->af);
6375 
6376 	}
6377 
6378 	PF_ACPY(&pd->nsaddr, pd->src, pd->af);
6379 	PF_ACPY(&pd->ndaddr, pd->dst, pd->af);
6380 
6381 	switch (pd->virtual_proto) {
6382 	case IPPROTO_TCP: {
6383 		struct tcphdr	*th = &pd->hdr.tcp;
6384 
6385 		if (!pf_pull_hdr(pd->m, pd->off, th, sizeof(*th),
6386 		    NULL, reason, pd->af))
6387 			return (PF_DROP);
6388 		pd->hdrlen = sizeof(*th);
6389 		if (pd->off + (th->th_off << 2) > pd->tot_len ||
6390 		    (th->th_off << 2) < sizeof(struct tcphdr)) {
6391 			REASON_SET(reason, PFRES_SHORT);
6392 			return (PF_DROP);
6393 		}
6394 		pd->p_len = pd->tot_len - pd->off - (th->th_off << 2);
6395 		pd->sport = &th->th_sport;
6396 		pd->dport = &th->th_dport;
6397 		pd->pcksum = &th->th_sum;
6398 		break;
6399 	}
6400 	case IPPROTO_UDP: {
6401 		struct udphdr	*uh = &pd->hdr.udp;
6402 
6403 		if (!pf_pull_hdr(pd->m, pd->off, uh, sizeof(*uh),
6404 		    NULL, reason, pd->af))
6405 			return (PF_DROP);
6406 		pd->hdrlen = sizeof(*uh);
6407 		if (uh->uh_dport == 0 ||
6408 		    pd->off + ntohs(uh->uh_ulen) > pd->tot_len ||
6409 		    ntohs(uh->uh_ulen) < sizeof(struct udphdr)) {
6410 			REASON_SET(reason, PFRES_SHORT);
6411 			return (PF_DROP);
6412 		}
6413 		pd->sport = &uh->uh_sport;
6414 		pd->dport = &uh->uh_dport;
6415 		pd->pcksum = &uh->uh_sum;
6416 		break;
6417 	}
6418 	case IPPROTO_ICMP: {
6419 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp, ICMP_MINLEN,
6420 		    NULL, reason, pd->af))
6421 			return (PF_DROP);
6422 		pd->hdrlen = ICMP_MINLEN;
6423 		if (pd->off + pd->hdrlen > pd->tot_len) {
6424 			REASON_SET(reason, PFRES_SHORT);
6425 			return (PF_DROP);
6426 		}
6427 		pd->pcksum = &pd->hdr.icmp.icmp_cksum;
6428 		break;
6429 	}
6430 #ifdef INET6
6431 	case IPPROTO_ICMPV6: {
6432 		size_t	icmp_hlen = sizeof(struct icmp6_hdr);
6433 
6434 		if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
6435 		    NULL, reason, pd->af))
6436 			return (PF_DROP);
6437 		/* ICMP headers we look further into to match state */
6438 		switch (pd->hdr.icmp6.icmp6_type) {
6439 		case MLD_LISTENER_QUERY:
6440 		case MLD_LISTENER_REPORT:
6441 			icmp_hlen = sizeof(struct mld_hdr);
6442 			break;
6443 		case ND_NEIGHBOR_SOLICIT:
6444 		case ND_NEIGHBOR_ADVERT:
6445 			icmp_hlen = sizeof(struct nd_neighbor_solicit);
6446 			break;
6447 		}
6448 		if (icmp_hlen > sizeof(struct icmp6_hdr) &&
6449 		    !pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
6450 		    NULL, reason, pd->af))
6451 			return (PF_DROP);
6452 		pd->hdrlen = icmp_hlen;
6453 		if (pd->off + pd->hdrlen > pd->tot_len) {
6454 			REASON_SET(reason, PFRES_SHORT);
6455 			return (PF_DROP);
6456 		}
6457 		pd->pcksum = &pd->hdr.icmp6.icmp6_cksum;
6458 		break;
6459 	}
6460 #endif	/* INET6 */
6461 	}
6462 
6463 	if (pd->sport)
6464 		pd->osport = pd->nsport = *pd->sport;
6465 	if (pd->dport)
6466 		pd->odport = pd->ndport = *pd->dport;
6467 
6468 	return (PF_PASS);
6469 }
6470 
6471 void
6472 pf_counters_inc(int action, struct pf_pdesc *pd, struct pf_state *s,
6473     struct pf_rule *r, struct pf_rule *a)
6474 {
6475 	int dirndx;
6476 	pd->kif->pfik_bytes[pd->af == AF_INET6][pd->dir == PF_OUT]
6477 	    [action != PF_PASS] += pd->tot_len;
6478 	pd->kif->pfik_packets[pd->af == AF_INET6][pd->dir == PF_OUT]
6479 	    [action != PF_PASS]++;
6480 
6481 	if (action == PF_PASS || action == PF_AFRT || r->action == PF_DROP) {
6482 		dirndx = (pd->dir == PF_OUT);
6483 		r->packets[dirndx]++;
6484 		r->bytes[dirndx] += pd->tot_len;
6485 		if (a != NULL) {
6486 			a->packets[dirndx]++;
6487 			a->bytes[dirndx] += pd->tot_len;
6488 		}
6489 		if (s != NULL) {
6490 			struct pf_rule_item	*ri;
6491 			struct pf_sn_item	*sni;
6492 
6493 			SLIST_FOREACH(sni, &s->src_nodes, next) {
6494 				sni->sn->packets[dirndx]++;
6495 				sni->sn->bytes[dirndx] += pd->tot_len;
6496 			}
6497 			dirndx = (pd->dir == s->direction) ? 0 : 1;
6498 			s->packets[dirndx]++;
6499 			s->bytes[dirndx] += pd->tot_len;
6500 
6501 			SLIST_FOREACH(ri, &s->match_rules, entry) {
6502 				ri->r->packets[dirndx]++;
6503 				ri->r->bytes[dirndx] += pd->tot_len;
6504 
6505 				if (ri->r->src.addr.type == PF_ADDR_TABLE)
6506 					pfr_update_stats(ri->r->src.addr.p.tbl,
6507 					    &s->key[(s->direction == PF_IN)]->
6508 						addr[(s->direction == PF_OUT)],
6509 					    pd, ri->r->action, ri->r->src.neg);
6510 				if (ri->r->dst.addr.type == PF_ADDR_TABLE)
6511 					pfr_update_stats(ri->r->dst.addr.p.tbl,
6512 					    &s->key[(s->direction == PF_IN)]->
6513 						addr[(s->direction == PF_IN)],
6514 					    pd, ri->r->action, ri->r->dst.neg);
6515 			}
6516 		}
6517 		if (r->src.addr.type == PF_ADDR_TABLE)
6518 			pfr_update_stats(r->src.addr.p.tbl,
6519 			    (s == NULL) ? pd->src :
6520 			    &s->key[(s->direction == PF_IN)]->
6521 				addr[(s->direction == PF_OUT)],
6522 			    pd, r->action, r->src.neg);
6523 		if (r->dst.addr.type == PF_ADDR_TABLE)
6524 			pfr_update_stats(r->dst.addr.p.tbl,
6525 			    (s == NULL) ? pd->dst :
6526 			    &s->key[(s->direction == PF_IN)]->
6527 				addr[(s->direction == PF_IN)],
6528 			    pd, r->action, r->dst.neg);
6529 	}
6530 }
6531 
6532 int
6533 pf_test(sa_family_t af, int fwdir, struct ifnet *ifp, struct mbuf **m0)
6534 {
6535 	struct pfi_kif		*kif;
6536 	u_short			 action, reason = 0;
6537 	struct pf_rule		*a = NULL, *r = &pf_default_rule;
6538 	struct pf_state		*s = NULL;
6539 	struct pf_ruleset	*ruleset = NULL;
6540 	struct pf_pdesc		 pd;
6541 	int			 dir = (fwdir == PF_FWD) ? PF_OUT : fwdir;
6542 	u_int32_t		 qid, pqid = 0;
6543 
6544 	if (!pf_status.running)
6545 		return (PF_PASS);
6546 
6547 #if NCARP > 0
6548 	if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6549 		kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6550 	else
6551 #endif /* NCARP */
6552 		kif = (struct pfi_kif *)ifp->if_pf_kif;
6553 
6554 	if (kif == NULL) {
6555 		DPFPRINTF(LOG_ERR,
6556 		    "%s: kif == NULL, if_xname %s", __func__, ifp->if_xname);
6557 		return (PF_DROP);
6558 	}
6559 	if (kif->pfik_flags & PFI_IFLAG_SKIP)
6560 		return (PF_PASS);
6561 
6562 #ifdef DIAGNOSTIC
6563 	if (((*m0)->m_flags & M_PKTHDR) == 0)
6564 		panic("non-M_PKTHDR is passed to pf_test");
6565 #endif /* DIAGNOSTIC */
6566 
6567 	if ((*m0)->m_pkthdr.pf.flags & PF_TAG_GENERATED)
6568 		return (PF_PASS);
6569 
6570 	if ((*m0)->m_pkthdr.pf.flags & PF_TAG_DIVERTED_PACKET)
6571 		return (PF_PASS);
6572 
6573 	if ((*m0)->m_pkthdr.pf.flags & PF_TAG_REFRAGMENTED) {
6574 		(*m0)->m_pkthdr.pf.flags &= ~PF_TAG_REFRAGMENTED;
6575 		return (PF_PASS);
6576 	}
6577 
6578 	action = pf_setup_pdesc(&pd, af, dir, kif, *m0, &reason);
6579 	if (action != PF_PASS) {
6580 #if NPFLOG > 0
6581 		pd.pflog |= PF_LOG_FORCE;
6582 #endif	/* NPFLOG > 0 */
6583 		goto done;
6584 	}
6585 
6586 	/* packet normalization and reassembly */
6587 	switch (pd.af) {
6588 	case AF_INET:
6589 		action = pf_normalize_ip(&pd, &reason);
6590 		break;
6591 #ifdef INET6
6592 	case AF_INET6:
6593 		action = pf_normalize_ip6(&pd, &reason);
6594 		break;
6595 #endif	/* INET6 */
6596 	}
6597 	*m0 = pd.m;
6598 	/* if packet sits in reassembly queue, return without error */
6599 	if (pd.m == NULL)
6600 		return PF_PASS;
6601 	if (action != PF_PASS) {
6602 #if NPFLOG > 0
6603 		pd.pflog |= PF_LOG_FORCE;
6604 #endif	/* NPFLOG > 0 */
6605 		goto done;
6606 	}
6607 
6608 	/* if packet has been reassembled, update packet description */
6609 	if (pf_status.reass && pd.virtual_proto == PF_VPROTO_FRAGMENT) {
6610 		action = pf_setup_pdesc(&pd, af, dir, kif, pd.m, &reason);
6611 		if (action != PF_PASS) {
6612 #if NPFLOG > 0
6613 			pd.pflog |= PF_LOG_FORCE;
6614 #endif	/* NPFLOG > 0 */
6615 			goto done;
6616 		}
6617 	}
6618 	pd.m->m_pkthdr.pf.flags |= PF_TAG_PROCESSED;
6619 
6620 	switch (pd.virtual_proto) {
6621 
6622 	case PF_VPROTO_FRAGMENT: {
6623 		/*
6624 		 * handle fragments that aren't reassembled by
6625 		 * normalization
6626 		 */
6627 		action = pf_test_rule(&pd, &r, &s, &a, &ruleset, &reason);
6628 		if (action != PF_PASS)
6629 			REASON_SET(&reason, PFRES_FRAG);
6630 		break;
6631 	}
6632 
6633 	case IPPROTO_ICMP: {
6634 		if (pd.af != AF_INET) {
6635 			action = PF_DROP;
6636 			REASON_SET(&reason, PFRES_NORM);
6637 			DPFPRINTF(LOG_NOTICE,
6638 			    "dropping IPv6 packet with ICMPv4 payload");
6639 			goto done;
6640 		}
6641 		action = pf_test_state_icmp(&pd, &s, &reason);
6642 		if (action == PF_PASS || action == PF_AFRT) {
6643 #if NPFSYNC > 0
6644 			pfsync_update_state(s);
6645 #endif /* NPFSYNC > 0 */
6646 			r = s->rule.ptr;
6647 			a = s->anchor.ptr;
6648 #if NPFLOG > 0
6649 			pd.pflog |= s->log;
6650 #endif	/* NPFLOG > 0 */
6651 		} else if (s == NULL)
6652 			action = pf_test_rule(&pd, &r, &s, &a, &ruleset,
6653 			    &reason);
6654 		break;
6655 	}
6656 
6657 #ifdef INET6
6658 	case IPPROTO_ICMPV6: {
6659 		if (pd.af != AF_INET6) {
6660 			action = PF_DROP;
6661 			REASON_SET(&reason, PFRES_NORM);
6662 			DPFPRINTF(LOG_NOTICE,
6663 			    "dropping IPv4 packet with ICMPv6 payload");
6664 			goto done;
6665 		}
6666 		action = pf_test_state_icmp(&pd, &s, &reason);
6667 		if (action == PF_PASS || action == PF_AFRT) {
6668 #if NPFSYNC > 0
6669 			pfsync_update_state(s);
6670 #endif /* NPFSYNC > 0 */
6671 			r = s->rule.ptr;
6672 			a = s->anchor.ptr;
6673 #if NPFLOG > 0
6674 			pd.pflog |= s->log;
6675 #endif	/* NPFLOG > 0 */
6676 		} else if (s == NULL)
6677 			action = pf_test_rule(&pd, &r, &s, &a, &ruleset,
6678 			    &reason);
6679 		break;
6680 	}
6681 #endif /* INET6 */
6682 
6683 	default:
6684 		if (pd.virtual_proto == IPPROTO_TCP) {
6685 			if ((pd.hdr.tcp.th_flags & TH_ACK) && pd.p_len == 0)
6686 				pqid = 1;
6687 			action = pf_normalize_tcp(&pd);
6688 			if (action == PF_DROP)
6689 				goto done;
6690 		}
6691 		action = pf_test_state(&pd, &s, &reason);
6692 		if (action == PF_PASS || action == PF_AFRT) {
6693 #if NPFSYNC > 0
6694 			pfsync_update_state(s);
6695 #endif /* NPFSYNC > 0 */
6696 			r = s->rule.ptr;
6697 			a = s->anchor.ptr;
6698 #if NPFLOG > 0
6699 			pd.pflog |= s->log;
6700 #endif	/* NPFLOG > 0 */
6701 		} else if (s == NULL)
6702 			action = pf_test_rule(&pd, &r, &s, &a, &ruleset,
6703 			    &reason);
6704 
6705 		if (pd.virtual_proto == IPPROTO_TCP) {
6706 			if (s) {
6707 				if (s->max_mss)
6708 					pf_normalize_mss(&pd, s->max_mss);
6709 			} else if (r->max_mss)
6710 				pf_normalize_mss(&pd, r->max_mss);
6711 		}
6712 
6713 		break;
6714 	}
6715 
6716 done:
6717 	if (action != PF_DROP) {
6718 		if (s) {
6719 			/* The non-state case is handled in pf_test_rule() */
6720 			if (action == PF_PASS && pd.badopts &&
6721 			    !(s->state_flags & PFSTATE_ALLOWOPTS)) {
6722 				action = PF_DROP;
6723 				REASON_SET(&reason, PFRES_IPOPTIONS);
6724 #if NPFLOG > 0
6725 				pd.pflog |= PF_LOG_FORCE;
6726 #endif	/* NPFLOG > 0 */
6727 				DPFPRINTF(LOG_NOTICE, "dropping packet with "
6728 				    "ip/ipv6 options in pf_test()");
6729 			}
6730 
6731 			pf_scrub(pd.m, s->state_flags, pd.af, s->min_ttl,
6732 			    s->set_tos);
6733 			pf_tag_packet(pd.m, s->tag, s->rtableid[pd.didx]);
6734 			if (pqid || (pd.tos & IPTOS_LOWDELAY)) {
6735 				qid = s->pqid;
6736 				if (s->state_flags & PFSTATE_SETPRIO)
6737 					pd.m->m_pkthdr.pf.prio = s->set_prio[1];
6738 			} else {
6739 				qid = s->qid;
6740 				if (s->state_flags & PFSTATE_SETPRIO)
6741 					pd.m->m_pkthdr.pf.prio = s->set_prio[0];
6742 			}
6743 		} else {
6744 			pf_scrub(pd.m, r->scrub_flags, pd.af, r->min_ttl,
6745 			    r->set_tos);
6746 			if (pqid || (pd.tos & IPTOS_LOWDELAY)) {
6747 				qid = r->pqid;
6748 				if (r->scrub_flags & PFSTATE_SETPRIO)
6749 					pd.m->m_pkthdr.pf.prio = r->set_prio[1];
6750 			} else {
6751 				qid = r->qid;
6752 				if (r->scrub_flags & PFSTATE_SETPRIO)
6753 					pd.m->m_pkthdr.pf.prio = r->set_prio[0];
6754 			}
6755 		}
6756 	}
6757 
6758 	if (action == PF_PASS && qid)
6759 		pd.m->m_pkthdr.pf.qid = qid;
6760 	if (pd.dir == PF_IN && s && s->key[PF_SK_STACK]) {
6761 		/*
6762 		 * Check below fires whenever caller forgets to call
6763 		 * pf_pkt_addr_changed(). This might happen when we
6764 		 * deal with IP tunnels.
6765 		 */
6766 		if (pd.m->m_pkthdr.pf.statekey != NULL) {
6767 #ifdef DDB
6768 			m_print(pd.m, printf);
6769 #endif
6770 			panic("incoming mbuf already has a statekey");
6771 		}
6772 		pd.m->m_pkthdr.pf.statekey =
6773 		    pf_state_key_ref(s->key[PF_SK_STACK]);
6774 	}
6775 	if (pd.dir == PF_OUT &&
6776 	    pd.m->m_pkthdr.pf.inp && !pd.m->m_pkthdr.pf.inp->inp_pf_sk &&
6777 	    s && s->key[PF_SK_STACK] && !s->key[PF_SK_STACK]->inp) {
6778 		pd.m->m_pkthdr.pf.inp->inp_pf_sk =
6779 		    pf_state_key_ref(s->key[PF_SK_STACK]);
6780 		s->key[PF_SK_STACK]->inp = pd.m->m_pkthdr.pf.inp;
6781 	}
6782 
6783 	if (s) {
6784 		pd.m->m_pkthdr.ph_flowid = M_FLOWID_VALID |
6785 		    (M_FLOWID_MASK & bemtoh64(&s->id));
6786 	}
6787 
6788 	/*
6789 	 * connections redirected to loopback should not match sockets
6790 	 * bound specifically to loopback due to security implications,
6791 	 * see tcp_input() and in_pcblookup_listen().
6792 	 */
6793 	if (pd.destchg)
6794 		if ((pd.af == AF_INET && (ntohl(pd.dst->v4.s_addr) >>
6795 		    IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
6796 		    (pd.af == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&pd.dst->v6)))
6797 			pd.m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6798 	/* We need to redo the route lookup on outgoing routes. */
6799 	if (pd.destchg && pd.dir == PF_OUT)
6800 		pd.m->m_pkthdr.pf.flags |= PF_TAG_REROUTE;
6801 
6802 	if (pd.dir == PF_IN && action == PF_PASS && r->divert.port) {
6803 		struct pf_divert *divert;
6804 
6805 		if ((divert = pf_get_divert(pd.m))) {
6806 			pd.m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6807 			divert->port = r->divert.port;
6808 			divert->rdomain = pd.rdomain;
6809 			divert->addr = r->divert.addr;
6810 		}
6811 	}
6812 
6813 	if (action == PF_PASS && r->divert_packet.port)
6814 		action = PF_DIVERT;
6815 
6816 #if NPFLOG > 0
6817 	if (pd.pflog) {
6818 		struct pf_rule_item	*ri;
6819 
6820 		if (pd.pflog & PF_LOG_FORCE || r->log & PF_LOG_ALL)
6821 			PFLOG_PACKET(&pd, reason, r, a, ruleset, NULL);
6822 		if (s) {
6823 			SLIST_FOREACH(ri, &s->match_rules, entry)
6824 				if (ri->r->log & PF_LOG_ALL)
6825 					PFLOG_PACKET(&pd, reason, ri->r, a,
6826 					    ruleset, NULL);
6827 		}
6828 	}
6829 #endif	/* NPFLOG > 0 */
6830 
6831 	pf_counters_inc(action, &pd, s, r, a);
6832 
6833 	switch (action) {
6834 	case PF_SYNPROXY_DROP:
6835 		m_freem(pd.m);
6836 		/* FALLTHROUGH */
6837 	case PF_DEFER:
6838 		pd.m = NULL;
6839 		action = PF_PASS;
6840 		break;
6841 	case PF_DIVERT:
6842 		switch (pd.af) {
6843 		case AF_INET:
6844 			if (!divert_packet(pd.m, pd.dir, r->divert_packet.port))
6845 				pd.m = NULL;
6846 			break;
6847 #ifdef INET6
6848 		case AF_INET6:
6849 			if (!divert6_packet(pd.m, pd.dir,
6850 			    r->divert_packet.port))
6851 				pd.m = NULL;
6852 			break;
6853 #endif /* INET6 */
6854 		}
6855 		action = PF_PASS;
6856 		break;
6857 #ifdef INET6
6858 	case PF_AFRT:
6859 		if (pf_translate_af(&pd)) {
6860 			action = PF_DROP;
6861 			break;
6862 		}
6863 		pd.m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
6864 		switch (pd.naf) {
6865 		case AF_INET:
6866 			if (pd.dir == PF_IN)
6867 				ip_forward(pd.m, ifp, NULL, 1);
6868 			else
6869 				ip_output(pd.m, NULL, NULL, 0, NULL, NULL, 0);
6870 			break;
6871 		case AF_INET6:
6872 			if (pd.dir == PF_IN)
6873 				ip6_forward(pd.m, NULL, 1);
6874 			else
6875 				ip6_output(pd.m, NULL, NULL, 0, NULL, NULL);
6876 			break;
6877 		}
6878 		pd.m = NULL;
6879 		action = PF_PASS;
6880 		break;
6881 #endif /* INET6 */
6882 	case PF_DROP:
6883 		m_freem(pd.m);
6884 		pd.m = NULL;
6885 		break;
6886 	default:
6887 		if (r->rt) {
6888 			switch (pd.af) {
6889 			case AF_INET:
6890 				pf_route(&pd, r, s);
6891 				break;
6892 #ifdef INET6
6893 			case AF_INET6:
6894 				pf_route6(&pd, r, s);
6895 				break;
6896 #endif /* INET6 */
6897 			}
6898 		}
6899 		break;
6900 	}
6901 
6902 #ifdef INET6
6903 	/* if reassembled packet passed, create new fragments */
6904 	if (pf_status.reass && action == PF_PASS && pd.m && fwdir == PF_FWD) {
6905 		struct m_tag	*mtag;
6906 
6907 		if ((mtag = m_tag_find(pd.m, PACKET_TAG_PF_REASSEMBLED, NULL)))
6908 			action = pf_refragment6(&pd.m, mtag, NULL, NULL, NULL);
6909 	}
6910 #endif	/* INET6 */
6911 	if (s && action != PF_DROP) {
6912 		if (!s->if_index_in && dir == PF_IN)
6913 			s->if_index_in = ifp->if_index;
6914 		else if (!s->if_index_out && dir == PF_OUT)
6915 			s->if_index_out = ifp->if_index;
6916 	}
6917 
6918 	*m0 = pd.m;
6919 	return (action);
6920 }
6921 
6922 int
6923 pf_ouraddr(struct mbuf *m)
6924 {
6925 	struct pf_state_key	*sk;
6926 
6927 	if (m->m_pkthdr.pf.flags & PF_TAG_DIVERTED)
6928 		return (1);
6929 
6930 	sk = m->m_pkthdr.pf.statekey;
6931 	if (sk != NULL) {
6932 		if (sk->inp != NULL)
6933 			return (1);
6934 
6935 		/* If we have linked state keys it is certainly forwarded. */
6936 		if (sk->reverse != NULL)
6937 			return (0);
6938 	}
6939 
6940 	return (-1);
6941 }
6942 
6943 /*
6944  * must be called whenever any addressing information such as
6945  * address, port, protocol has changed
6946  */
6947 void
6948 pf_pkt_addr_changed(struct mbuf *m)
6949 {
6950 	pf_pkt_unlink_state_key(m);
6951 	m->m_pkthdr.pf.inp = NULL;
6952 }
6953 
6954 struct inpcb *
6955 pf_inp_lookup(struct mbuf *m)
6956 {
6957 	struct inpcb *inp = NULL;
6958 	struct pf_state_key *sk = m->m_pkthdr.pf.statekey;
6959 
6960 	if (!pf_state_key_isvalid(sk))
6961 		pf_pkt_unlink_state_key(m);
6962 	else
6963 		inp = m->m_pkthdr.pf.statekey->inp;
6964 
6965 	if (inp && inp->inp_pf_sk)
6966 		KASSERT(m->m_pkthdr.pf.statekey == inp->inp_pf_sk);
6967 
6968 	return (inp);
6969 }
6970 
6971 void
6972 pf_inp_link(struct mbuf *m, struct inpcb *inp)
6973 {
6974 	struct pf_state_key *sk = m->m_pkthdr.pf.statekey;
6975 
6976 	if (!pf_state_key_isvalid(sk)) {
6977 		pf_pkt_unlink_state_key(m);
6978 		return;
6979 	}
6980 
6981 	/*
6982 	 * we don't need to grab PF-lock here. At worst case we link inp to
6983 	 * state, which might be just being marked as deleted by another
6984 	 * thread.
6985 	 */
6986 	if (inp && !sk->inp && !inp->inp_pf_sk) {
6987 		sk->inp = inp;
6988 		inp->inp_pf_sk = pf_state_key_ref(sk);
6989 	}
6990 	/* The statekey has finished finding the inp, it is no longer needed. */
6991 	pf_pkt_unlink_state_key(m);
6992 }
6993 
6994 void
6995 pf_inp_unlink(struct inpcb *inp)
6996 {
6997 	if (inp->inp_pf_sk) {
6998 		inp->inp_pf_sk->inp = NULL;
6999 		pf_inpcb_unlink_state_key(inp);
7000 	}
7001 }
7002 
7003 void
7004 pf_state_key_link(struct pf_state_key *sk, struct pf_state_key *pkt_sk)
7005 {
7006 	/*
7007 	 * Assert will not wire as long as we are called by pf_find_state()
7008 	 */
7009 	KASSERT((pkt_sk->reverse == NULL) && (sk->reverse == NULL));
7010 	pkt_sk->reverse = pf_state_key_ref(sk);
7011 	sk->reverse = pf_state_key_ref(pkt_sk);
7012 }
7013 
7014 #if NPFLOG > 0
7015 void
7016 pf_log_matches(struct pf_pdesc *pd, struct pf_rule *rm, struct pf_rule *am,
7017     struct pf_ruleset *ruleset, struct pf_rule_slist *matchrules)
7018 {
7019 	struct pf_rule_item	*ri;
7020 
7021 	/* if this is the log(matches) rule, packet has been logged already */
7022 	if (rm->log & PF_LOG_MATCHES)
7023 		return;
7024 
7025 	SLIST_FOREACH(ri, matchrules, entry)
7026 		if (ri->r->log & PF_LOG_MATCHES)
7027 			PFLOG_PACKET(pd, PFRES_MATCH, rm, am, ruleset, ri->r);
7028 }
7029 #endif	/* NPFLOG > 0 */
7030 
7031 struct pf_state_key *
7032 pf_state_key_ref(struct pf_state_key *sk)
7033 {
7034 	if (sk != NULL)
7035 		PF_REF_TAKE(sk->refcnt);
7036 
7037 	return (sk);
7038 }
7039 
7040 void
7041 pf_state_key_unref(struct pf_state_key *sk)
7042 {
7043 	if ((sk != NULL) && PF_REF_RELE(sk->refcnt)) {
7044 		/* state key must be removed from tree */
7045 		KASSERT(!pf_state_key_isvalid(sk));
7046 		/* state key must be unlinked from reverse key */
7047 		KASSERT(sk->reverse == NULL);
7048 		/* state key must be unlinked from socket */
7049 		KASSERT((sk->inp == NULL) || (sk->inp->inp_pf_sk == NULL));
7050 		sk->inp = NULL;
7051 		pool_put(&pf_state_key_pl, sk);
7052 	}
7053 }
7054 
7055 int
7056 pf_state_key_isvalid(struct pf_state_key *sk)
7057 {
7058 	return ((sk != NULL) && (sk->removed == 0));
7059 }
7060 
7061 void
7062 pf_pkt_unlink_state_key(struct mbuf *m)
7063 {
7064 	pf_state_key_unref(m->m_pkthdr.pf.statekey);
7065 	m->m_pkthdr.pf.statekey = NULL;
7066 }
7067 
7068 void
7069 pf_pkt_state_key_ref(struct mbuf *m)
7070 {
7071 	pf_state_key_ref(m->m_pkthdr.pf.statekey);
7072 }
7073 
7074 void
7075 pf_inpcb_unlink_state_key(struct inpcb *inp)
7076 {
7077 	if (inp != NULL) {
7078 		pf_state_key_unref(inp->inp_pf_sk);
7079 		inp->inp_pf_sk = NULL;
7080 	}
7081 }
7082 
7083 void
7084 pf_state_key_unlink_reverse(struct pf_state_key *sk)
7085 {
7086 	if ((sk != NULL) && (sk->reverse != NULL)) {
7087 		pf_state_key_unref(sk->reverse->reverse);
7088 		sk->reverse->reverse = NULL;
7089 		pf_state_key_unref(sk->reverse);
7090 		sk->reverse = NULL;
7091 	}
7092 }
7093