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