]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netpfil/pf/pf.c
The r48589 promised to remove implicit inclusion of if_var.h soon. Prepare
[FreeBSD/FreeBSD.git] / sys / netpfil / pf / pf.c
1 /*-
2  * Copyright (c) 2001 Daniel Hartmeier
3  * Copyright (c) 2002 - 2008 Henning Brauer
4  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  *    - Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *    - Redistributions in binary form must reproduce the above
14  *      copyright notice, this list of conditions and the following
15  *      disclaimer in the documentation and/or other materials provided
16  *      with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  * Effort sponsored in part by the Defense Advanced Research Projects
32  * Agency (DARPA) and Air Force Research Laboratory, Air Force
33  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
34  *
35  *      $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
36  */
37
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include "opt_inet.h"
42 #include "opt_inet6.h"
43 #include "opt_bpf.h"
44 #include "opt_pf.h"
45
46 #include <sys/param.h>
47 #include <sys/bus.h>
48 #include <sys/endian.h>
49 #include <sys/hash.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/limits.h>
54 #include <sys/mbuf.h>
55 #include <sys/md5.h>
56 #include <sys/random.h>
57 #include <sys/refcount.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/taskqueue.h>
61 #include <sys/ucred.h>
62
63 #include <net/if.h>
64 #include <net/if_var.h>
65 #include <net/if_types.h>
66 #include <net/route.h>
67 #include <net/radix_mpath.h>
68 #include <net/vnet.h>
69
70 #include <net/pfvar.h>
71 #include <net/pf_mtag.h>
72 #include <net/if_pflog.h>
73 #include <net/if_pfsync.h>
74
75 #include <netinet/in_pcb.h>
76 #include <netinet/in_var.h>
77 #include <netinet/ip.h>
78 #include <netinet/ip_fw.h>
79 #include <netinet/ip_icmp.h>
80 #include <netinet/icmp_var.h>
81 #include <netinet/ip_var.h>
82 #include <netinet/tcp.h>
83 #include <netinet/tcp_fsm.h>
84 #include <netinet/tcp_seq.h>
85 #include <netinet/tcp_timer.h>
86 #include <netinet/tcp_var.h>
87 #include <netinet/udp.h>
88 #include <netinet/udp_var.h>
89
90 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
91
92 #ifdef INET6
93 #include <netinet/ip6.h>
94 #include <netinet/icmp6.h>
95 #include <netinet6/nd6.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet6/in6_pcb.h>
98 #endif /* INET6 */
99
100 #include <machine/in_cksum.h>
101 #include <security/mac/mac_framework.h>
102
103 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
104
105 /*
106  * Global variables
107  */
108
109 /* state tables */
110 VNET_DEFINE(struct pf_altqqueue,         pf_altqs[2]);
111 VNET_DEFINE(struct pf_palist,            pf_pabuf);
112 VNET_DEFINE(struct pf_altqqueue *,       pf_altqs_active);
113 VNET_DEFINE(struct pf_altqqueue *,       pf_altqs_inactive);
114 VNET_DEFINE(struct pf_status,            pf_status);
115
116 VNET_DEFINE(u_int32_t,                   ticket_altqs_active);
117 VNET_DEFINE(u_int32_t,                   ticket_altqs_inactive);
118 VNET_DEFINE(int,                         altqs_inactive_open);
119 VNET_DEFINE(u_int32_t,                   ticket_pabuf);
120
121 VNET_DEFINE(MD5_CTX,                     pf_tcp_secret_ctx);
122 #define V_pf_tcp_secret_ctx              VNET(pf_tcp_secret_ctx)
123 VNET_DEFINE(u_char,                      pf_tcp_secret[16]);
124 #define V_pf_tcp_secret                  VNET(pf_tcp_secret)
125 VNET_DEFINE(int,                         pf_tcp_secret_init);
126 #define V_pf_tcp_secret_init             VNET(pf_tcp_secret_init)
127 VNET_DEFINE(int,                         pf_tcp_iss_off);
128 #define V_pf_tcp_iss_off                 VNET(pf_tcp_iss_off)
129
130 /*
131  * Queue for pf_intr() sends.
132  */
133 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
134 struct pf_send_entry {
135         STAILQ_ENTRY(pf_send_entry)     pfse_next;
136         struct mbuf                     *pfse_m;
137         enum {
138                 PFSE_IP,
139                 PFSE_IP6,
140                 PFSE_ICMP,
141                 PFSE_ICMP6,
142         }                               pfse_type;
143         union {
144                 struct route            ro;
145                 struct {
146                         int             type;
147                         int             code;
148                         int             mtu;
149                 } icmpopts;
150         } u;
151 #define pfse_ro         u.ro
152 #define pfse_icmp_type  u.icmpopts.type
153 #define pfse_icmp_code  u.icmpopts.code
154 #define pfse_icmp_mtu   u.icmpopts.mtu
155 };
156
157 STAILQ_HEAD(pf_send_head, pf_send_entry);
158 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
159 #define V_pf_sendqueue  VNET(pf_sendqueue)
160
161 static struct mtx pf_sendqueue_mtx;
162 #define PF_SENDQ_LOCK()         mtx_lock(&pf_sendqueue_mtx)
163 #define PF_SENDQ_UNLOCK()       mtx_unlock(&pf_sendqueue_mtx)
164
165 /*
166  * Queue for pf_overload_task() tasks.
167  */
168 struct pf_overload_entry {
169         SLIST_ENTRY(pf_overload_entry)  next;
170         struct pf_addr                  addr;
171         sa_family_t                     af;
172         uint8_t                         dir;
173         struct pf_rule                  *rule;
174 };
175
176 SLIST_HEAD(pf_overload_head, pf_overload_entry);
177 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
178 #define V_pf_overloadqueue      VNET(pf_overloadqueue)
179 static VNET_DEFINE(struct task, pf_overloadtask);
180 #define V_pf_overloadtask       VNET(pf_overloadtask)
181
182 static struct mtx pf_overloadqueue_mtx;
183 #define PF_OVERLOADQ_LOCK()     mtx_lock(&pf_overloadqueue_mtx)
184 #define PF_OVERLOADQ_UNLOCK()   mtx_unlock(&pf_overloadqueue_mtx)
185
186 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
187 struct mtx pf_unlnkdrules_mtx;
188
189 static VNET_DEFINE(uma_zone_t,  pf_sources_z);
190 #define V_pf_sources_z  VNET(pf_sources_z)
191 static VNET_DEFINE(uma_zone_t,  pf_mtag_z);
192 #define V_pf_mtag_z     VNET(pf_mtag_z)
193 VNET_DEFINE(uma_zone_t,  pf_state_z);
194 VNET_DEFINE(uma_zone_t,  pf_state_key_z);
195
196 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
197 #define PFID_CPUBITS    8
198 #define PFID_CPUSHIFT   (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
199 #define PFID_CPUMASK    ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
200 #define PFID_MAXID      (~PFID_CPUMASK)
201 CTASSERT((1 << PFID_CPUBITS) > MAXCPU);
202
203 static void              pf_src_tree_remove_state(struct pf_state *);
204 static void              pf_init_threshold(struct pf_threshold *, u_int32_t,
205                             u_int32_t);
206 static void              pf_add_threshold(struct pf_threshold *);
207 static int               pf_check_threshold(struct pf_threshold *);
208
209 static void              pf_change_ap(struct pf_addr *, u_int16_t *,
210                             u_int16_t *, u_int16_t *, struct pf_addr *,
211                             u_int16_t, u_int8_t, sa_family_t);
212 static int               pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
213                             struct tcphdr *, struct pf_state_peer *);
214 static void              pf_change_icmp(struct pf_addr *, u_int16_t *,
215                             struct pf_addr *, struct pf_addr *, u_int16_t,
216                             u_int16_t *, u_int16_t *, u_int16_t *,
217                             u_int16_t *, u_int8_t, sa_family_t);
218 static void              pf_send_tcp(struct mbuf *,
219                             const struct pf_rule *, sa_family_t,
220                             const struct pf_addr *, const struct pf_addr *,
221                             u_int16_t, u_int16_t, u_int32_t, u_int32_t,
222                             u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
223                             u_int16_t, struct ifnet *);
224 static void              pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
225                             sa_family_t, struct pf_rule *);
226 static void              pf_detach_state(struct pf_state *);
227 static int               pf_state_key_attach(struct pf_state_key *,
228                             struct pf_state_key *, struct pf_state *);
229 static void              pf_state_key_detach(struct pf_state *, int);
230 static int               pf_state_key_ctor(void *, int, void *, int);
231 static u_int32_t         pf_tcp_iss(struct pf_pdesc *);
232 static int               pf_test_rule(struct pf_rule **, struct pf_state **,
233                             int, struct pfi_kif *, struct mbuf *, int,
234                             struct pf_pdesc *, struct pf_rule **,
235                             struct pf_ruleset **, struct inpcb *);
236 static int               pf_create_state(struct pf_rule *, struct pf_rule *,
237                             struct pf_rule *, struct pf_pdesc *,
238                             struct pf_src_node *, struct pf_state_key *,
239                             struct pf_state_key *, struct mbuf *, int,
240                             u_int16_t, u_int16_t, int *, struct pfi_kif *,
241                             struct pf_state **, int, u_int16_t, u_int16_t,
242                             int);
243 static int               pf_test_fragment(struct pf_rule **, int,
244                             struct pfi_kif *, struct mbuf *, void *,
245                             struct pf_pdesc *, struct pf_rule **,
246                             struct pf_ruleset **);
247 static int               pf_tcp_track_full(struct pf_state_peer *,
248                             struct pf_state_peer *, struct pf_state **,
249                             struct pfi_kif *, struct mbuf *, int,
250                             struct pf_pdesc *, u_short *, int *);
251 static int               pf_tcp_track_sloppy(struct pf_state_peer *,
252                             struct pf_state_peer *, struct pf_state **,
253                             struct pf_pdesc *, u_short *);
254 static int               pf_test_state_tcp(struct pf_state **, int,
255                             struct pfi_kif *, struct mbuf *, int,
256                             void *, struct pf_pdesc *, u_short *);
257 static int               pf_test_state_udp(struct pf_state **, int,
258                             struct pfi_kif *, struct mbuf *, int,
259                             void *, struct pf_pdesc *);
260 static int               pf_test_state_icmp(struct pf_state **, int,
261                             struct pfi_kif *, struct mbuf *, int,
262                             void *, struct pf_pdesc *, u_short *);
263 static int               pf_test_state_other(struct pf_state **, int,
264                             struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
265 static u_int8_t          pf_get_wscale(struct mbuf *, int, u_int16_t,
266                             sa_family_t);
267 static u_int16_t         pf_get_mss(struct mbuf *, int, u_int16_t,
268                             sa_family_t);
269 static u_int16_t         pf_calc_mss(struct pf_addr *, sa_family_t,
270                                 int, u_int16_t);
271 static void              pf_set_rt_ifp(struct pf_state *,
272                             struct pf_addr *);
273 static int               pf_check_proto_cksum(struct mbuf *, int, int,
274                             u_int8_t, sa_family_t);
275 static void              pf_print_state_parts(struct pf_state *,
276                             struct pf_state_key *, struct pf_state_key *);
277 static int               pf_addr_wrap_neq(struct pf_addr_wrap *,
278                             struct pf_addr_wrap *);
279 static struct pf_state  *pf_find_state(struct pfi_kif *,
280                             struct pf_state_key_cmp *, u_int);
281 static int               pf_src_connlimit(struct pf_state **);
282 static void              pf_overload_task(void *c, int pending);
283 static int               pf_insert_src_node(struct pf_src_node **,
284                             struct pf_rule *, struct pf_addr *, sa_family_t);
285 static u_int             pf_purge_expired_states(u_int, int);
286 static void              pf_purge_unlinked_rules(void);
287 static int               pf_mtag_init(void *, int, int);
288 static void              pf_mtag_free(struct m_tag *);
289 #ifdef INET
290 static void              pf_route(struct mbuf **, struct pf_rule *, int,
291                             struct ifnet *, struct pf_state *,
292                             struct pf_pdesc *);
293 #endif /* INET */
294 #ifdef INET6
295 static void              pf_change_a6(struct pf_addr *, u_int16_t *,
296                             struct pf_addr *, u_int8_t);
297 static void              pf_route6(struct mbuf **, struct pf_rule *, int,
298                             struct ifnet *, struct pf_state *,
299                             struct pf_pdesc *);
300 #endif /* INET6 */
301
302 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
303
304 VNET_DECLARE(int, pf_end_threads);
305
306 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
307
308 #define PACKET_LOOPED(pd)       ((pd)->pf_mtag &&                       \
309                                  (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
310
311 #define STATE_LOOKUP(i, k, d, s, pd)                                    \
312         do {                                                            \
313                 (s) = pf_find_state((i), (k), (d));                     \
314                 if ((s) == NULL || (s)->timeout == PFTM_PURGE)          \
315                         return (PF_DROP);                               \
316                 if (PACKET_LOOPED(pd))                                  \
317                         return (PF_PASS);                               \
318                 if ((d) == PF_OUT &&                                    \
319                     (((s)->rule.ptr->rt == PF_ROUTETO &&                \
320                     (s)->rule.ptr->direction == PF_OUT) ||              \
321                     ((s)->rule.ptr->rt == PF_REPLYTO &&                 \
322                     (s)->rule.ptr->direction == PF_IN)) &&              \
323                     (s)->rt_kif != NULL &&                              \
324                     (s)->rt_kif != (i))                                 \
325                         return (PF_PASS);                               \
326         } while (0)
327
328 #define BOUND_IFACE(r, k) \
329         ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
330
331 #define STATE_INC_COUNTERS(s)                           \
332         do {                                            \
333                 s->rule.ptr->states_cur++;              \
334                 s->rule.ptr->states_tot++;              \
335                 if (s->anchor.ptr != NULL) {            \
336                         s->anchor.ptr->states_cur++;    \
337                         s->anchor.ptr->states_tot++;    \
338                 }                                       \
339                 if (s->nat_rule.ptr != NULL) {          \
340                         s->nat_rule.ptr->states_cur++;  \
341                         s->nat_rule.ptr->states_tot++;  \
342                 }                                       \
343         } while (0)
344
345 #define STATE_DEC_COUNTERS(s)                           \
346         do {                                            \
347                 if (s->nat_rule.ptr != NULL)            \
348                         s->nat_rule.ptr->states_cur--;  \
349                 if (s->anchor.ptr != NULL)              \
350                         s->anchor.ptr->states_cur--;    \
351                 s->rule.ptr->states_cur--;              \
352         } while (0)
353
354 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
355 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
356 VNET_DEFINE(struct pf_idhash *, pf_idhash);
357 VNET_DEFINE(u_long, pf_hashmask);
358 VNET_DEFINE(struct pf_srchash *, pf_srchash);
359 VNET_DEFINE(u_long, pf_srchashmask);
360
361 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
362
363 VNET_DEFINE(u_long, pf_hashsize);
364 #define V_pf_hashsize   VNET(pf_hashsize)
365 SYSCTL_VNET_UINT(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
366     &VNET_NAME(pf_hashsize), 0, "Size of pf(4) states hashtable");
367
368 VNET_DEFINE(u_long, pf_srchashsize);
369 #define V_pf_srchashsize        VNET(pf_srchashsize)
370 SYSCTL_VNET_UINT(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
371     &VNET_NAME(pf_srchashsize), 0, "Size of pf(4) source nodes hashtable");
372
373 VNET_DEFINE(void *, pf_swi_cookie);
374
375 VNET_DEFINE(uint32_t, pf_hashseed);
376 #define V_pf_hashseed   VNET(pf_hashseed)
377
378 static __inline uint32_t
379 pf_hashkey(struct pf_state_key *sk)
380 {
381         uint32_t h;
382
383         h = jenkins_hash32((uint32_t *)sk,
384             sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
385             V_pf_hashseed);
386
387         return (h & V_pf_hashmask);
388 }
389
390 static __inline uint32_t
391 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
392 {
393         uint32_t h;
394
395         switch (af) {
396         case AF_INET:
397                 h = jenkins_hash32((uint32_t *)&addr->v4,
398                     sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
399                 break;
400         case AF_INET6:
401                 h = jenkins_hash32((uint32_t *)&addr->v6,
402                     sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
403                 break;
404         default:
405                 panic("%s: unknown address family %u", __func__, af);
406         }
407
408         return (h & V_pf_srchashmask);
409 }
410
411 #ifdef INET6
412 void
413 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
414 {
415         switch (af) {
416 #ifdef INET
417         case AF_INET:
418                 dst->addr32[0] = src->addr32[0];
419                 break;
420 #endif /* INET */
421         case AF_INET6:
422                 dst->addr32[0] = src->addr32[0];
423                 dst->addr32[1] = src->addr32[1];
424                 dst->addr32[2] = src->addr32[2];
425                 dst->addr32[3] = src->addr32[3];
426                 break;
427         }
428 }
429 #endif /* INET6 */
430
431 static void
432 pf_init_threshold(struct pf_threshold *threshold,
433     u_int32_t limit, u_int32_t seconds)
434 {
435         threshold->limit = limit * PF_THRESHOLD_MULT;
436         threshold->seconds = seconds;
437         threshold->count = 0;
438         threshold->last = time_uptime;
439 }
440
441 static void
442 pf_add_threshold(struct pf_threshold *threshold)
443 {
444         u_int32_t t = time_uptime, diff = t - threshold->last;
445
446         if (diff >= threshold->seconds)
447                 threshold->count = 0;
448         else
449                 threshold->count -= threshold->count * diff /
450                     threshold->seconds;
451         threshold->count += PF_THRESHOLD_MULT;
452         threshold->last = t;
453 }
454
455 static int
456 pf_check_threshold(struct pf_threshold *threshold)
457 {
458         return (threshold->count > threshold->limit);
459 }
460
461 static int
462 pf_src_connlimit(struct pf_state **state)
463 {
464         struct pf_overload_entry *pfoe;
465         int bad = 0;
466
467         PF_STATE_LOCK_ASSERT(*state);
468
469         (*state)->src_node->conn++;
470         (*state)->src.tcp_est = 1;
471         pf_add_threshold(&(*state)->src_node->conn_rate);
472
473         if ((*state)->rule.ptr->max_src_conn &&
474             (*state)->rule.ptr->max_src_conn <
475             (*state)->src_node->conn) {
476                 V_pf_status.lcounters[LCNT_SRCCONN]++;
477                 bad++;
478         }
479
480         if ((*state)->rule.ptr->max_src_conn_rate.limit &&
481             pf_check_threshold(&(*state)->src_node->conn_rate)) {
482                 V_pf_status.lcounters[LCNT_SRCCONNRATE]++;
483                 bad++;
484         }
485
486         if (!bad)
487                 return (0);
488
489         /* Kill this state. */
490         (*state)->timeout = PFTM_PURGE;
491         (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
492
493         if ((*state)->rule.ptr->overload_tbl == NULL)
494                 return (1);
495
496         /* Schedule overloading and flushing task. */
497         pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
498         if (pfoe == NULL)
499                 return (1);     /* too bad :( */
500
501         bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
502         pfoe->af = (*state)->key[PF_SK_WIRE]->af;
503         pfoe->rule = (*state)->rule.ptr;
504         pfoe->dir = (*state)->direction;
505         PF_OVERLOADQ_LOCK();
506         SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
507         PF_OVERLOADQ_UNLOCK();
508         taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
509
510         return (1);
511 }
512
513 static void
514 pf_overload_task(void *c, int pending)
515 {
516         struct pf_overload_head queue;
517         struct pfr_addr p;
518         struct pf_overload_entry *pfoe, *pfoe1;
519         uint32_t killed = 0;
520
521         PF_OVERLOADQ_LOCK();
522         queue = *(struct pf_overload_head *)c;
523         SLIST_INIT((struct pf_overload_head *)c);
524         PF_OVERLOADQ_UNLOCK();
525
526         bzero(&p, sizeof(p));
527         SLIST_FOREACH(pfoe, &queue, next) {
528                 V_pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
529                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
530                         printf("%s: blocking address ", __func__);
531                         pf_print_host(&pfoe->addr, 0, pfoe->af);
532                         printf("\n");
533                 }
534
535                 p.pfra_af = pfoe->af;
536                 switch (pfoe->af) {
537 #ifdef INET
538                 case AF_INET:
539                         p.pfra_net = 32;
540                         p.pfra_ip4addr = pfoe->addr.v4;
541                         break;
542 #endif
543 #ifdef INET6
544                 case AF_INET6:
545                         p.pfra_net = 128;
546                         p.pfra_ip6addr = pfoe->addr.v6;
547                         break;
548 #endif
549                 }
550
551                 PF_RULES_WLOCK();
552                 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
553                 PF_RULES_WUNLOCK();
554         }
555
556         /*
557          * Remove those entries, that don't need flushing.
558          */
559         SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
560                 if (pfoe->rule->flush == 0) {
561                         SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
562                         free(pfoe, M_PFTEMP);
563                 } else
564                         V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
565
566         /* If nothing to flush, return. */
567         if (SLIST_EMPTY(&queue))
568                 return;
569
570         for (int i = 0; i <= V_pf_hashmask; i++) {
571                 struct pf_idhash *ih = &V_pf_idhash[i];
572                 struct pf_state_key *sk;
573                 struct pf_state *s;
574
575                 PF_HASHROW_LOCK(ih);
576                 LIST_FOREACH(s, &ih->states, entry) {
577                     sk = s->key[PF_SK_WIRE];
578                     SLIST_FOREACH(pfoe, &queue, next)
579                         if (sk->af == pfoe->af &&
580                             ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
581                             pfoe->rule == s->rule.ptr) &&
582                             ((pfoe->dir == PF_OUT &&
583                             PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
584                             (pfoe->dir == PF_IN &&
585                             PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
586                                 s->timeout = PFTM_PURGE;
587                                 s->src.state = s->dst.state = TCPS_CLOSED;
588                                 killed++;
589                         }
590                 }
591                 PF_HASHROW_UNLOCK(ih);
592         }
593         SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
594                 free(pfoe, M_PFTEMP);
595         if (V_pf_status.debug >= PF_DEBUG_MISC)
596                 printf("%s: %u states killed", __func__, killed);
597 }
598
599 /*
600  * Can return locked on failure, so that we can consistently
601  * allocate and insert a new one.
602  */
603 struct pf_src_node *
604 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
605         int returnlocked)
606 {
607         struct pf_srchash *sh;
608         struct pf_src_node *n;
609
610         V_pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
611
612         sh = &V_pf_srchash[pf_hashsrc(src, af)];
613         PF_HASHROW_LOCK(sh);
614         LIST_FOREACH(n, &sh->nodes, entry)
615                 if (n->rule.ptr == rule && n->af == af &&
616                     ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
617                     (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
618                         break;
619         if (n != NULL || returnlocked == 0)
620                 PF_HASHROW_UNLOCK(sh);
621
622         return (n);
623 }
624
625 static int
626 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
627     struct pf_addr *src, sa_family_t af)
628 {
629
630         KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
631             rule->rpool.opts & PF_POOL_STICKYADDR),
632             ("%s for non-tracking rule %p", __func__, rule));
633
634         if (*sn == NULL)
635                 *sn = pf_find_src_node(src, rule, af, 1);
636
637         if (*sn == NULL) {
638                 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
639
640                 PF_HASHROW_ASSERT(sh);
641
642                 if (!rule->max_src_nodes ||
643                     rule->src_nodes < rule->max_src_nodes)
644                         (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
645                 else
646                         V_pf_status.lcounters[LCNT_SRCNODES]++;
647                 if ((*sn) == NULL) {
648                         PF_HASHROW_UNLOCK(sh);
649                         return (-1);
650                 }
651
652                 pf_init_threshold(&(*sn)->conn_rate,
653                     rule->max_src_conn_rate.limit,
654                     rule->max_src_conn_rate.seconds);
655
656                 (*sn)->af = af;
657                 (*sn)->rule.ptr = rule;
658                 PF_ACPY(&(*sn)->addr, src, af);
659                 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
660                 (*sn)->creation = time_uptime;
661                 (*sn)->ruletype = rule->action;
662                 if ((*sn)->rule.ptr != NULL)
663                         (*sn)->rule.ptr->src_nodes++;
664                 PF_HASHROW_UNLOCK(sh);
665                 V_pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
666                 V_pf_status.src_nodes++;
667         } else {
668                 if (rule->max_src_states &&
669                     (*sn)->states >= rule->max_src_states) {
670                         V_pf_status.lcounters[LCNT_SRCSTATES]++;
671                         return (-1);
672                 }
673         }
674         return (0);
675 }
676
677 static void
678 pf_remove_src_node(struct pf_src_node *src)
679 {
680         struct pf_srchash *sh;
681
682         sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
683         PF_HASHROW_LOCK(sh);
684         LIST_REMOVE(src, entry);
685         PF_HASHROW_UNLOCK(sh);
686
687         V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
688         V_pf_status.src_nodes--;
689
690         uma_zfree(V_pf_sources_z, src);
691 }
692
693 /* Data storage structures initialization. */
694 void
695 pf_initialize()
696 {
697         struct pf_keyhash       *kh;
698         struct pf_idhash        *ih;
699         struct pf_srchash       *sh;
700         u_int i;
701
702         TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &V_pf_hashsize);
703         if (V_pf_hashsize == 0 || !powerof2(V_pf_hashsize))
704                 V_pf_hashsize = PF_HASHSIZ;
705         TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &V_pf_srchashsize);
706         if (V_pf_srchashsize == 0 || !powerof2(V_pf_srchashsize))
707                 V_pf_srchashsize = PF_HASHSIZ / 4;
708
709         V_pf_hashseed = arc4random();
710
711         /* States and state keys storage. */
712         V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
713             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
714         V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
715         uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
716         uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
717
718         V_pf_state_key_z = uma_zcreate("pf state keys",
719             sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
720             UMA_ALIGN_PTR, 0);
721         V_pf_keyhash = malloc(V_pf_hashsize * sizeof(struct pf_keyhash),
722             M_PFHASH, M_WAITOK | M_ZERO);
723         V_pf_idhash = malloc(V_pf_hashsize * sizeof(struct pf_idhash),
724             M_PFHASH, M_WAITOK | M_ZERO);
725         V_pf_hashmask = V_pf_hashsize - 1;
726         for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
727             i++, kh++, ih++) {
728                 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
729                 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
730         }
731
732         /* Source nodes. */
733         V_pf_sources_z = uma_zcreate("pf source nodes",
734             sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
735             0);
736         V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
737         uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
738         uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
739         V_pf_srchash = malloc(V_pf_srchashsize * sizeof(struct pf_srchash),
740           M_PFHASH, M_WAITOK|M_ZERO);
741         V_pf_srchashmask = V_pf_srchashsize - 1;
742         for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++)
743                 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
744
745         /* ALTQ */
746         TAILQ_INIT(&V_pf_altqs[0]);
747         TAILQ_INIT(&V_pf_altqs[1]);
748         TAILQ_INIT(&V_pf_pabuf);
749         V_pf_altqs_active = &V_pf_altqs[0];
750         V_pf_altqs_inactive = &V_pf_altqs[1];
751
752         /* Mbuf tags */
753         V_pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
754             sizeof(struct pf_mtag), NULL, NULL, pf_mtag_init, NULL,
755             UMA_ALIGN_PTR, 0);
756
757         /* Send & overload+flush queues. */
758         STAILQ_INIT(&V_pf_sendqueue);
759         SLIST_INIT(&V_pf_overloadqueue);
760         TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, &V_pf_overloadqueue);
761         mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
762         mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
763             MTX_DEF);
764
765         /* Unlinked, but may be referenced rules. */
766         TAILQ_INIT(&V_pf_unlinked_rules);
767         mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
768 }
769
770 void
771 pf_cleanup()
772 {
773         struct pf_keyhash       *kh;
774         struct pf_idhash        *ih;
775         struct pf_srchash       *sh;
776         struct pf_send_entry    *pfse, *next;
777         u_int i;
778
779         for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
780             i++, kh++, ih++) {
781                 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
782                     __func__));
783                 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
784                     __func__));
785                 mtx_destroy(&kh->lock);
786                 mtx_destroy(&ih->lock);
787         }
788         free(V_pf_keyhash, M_PFHASH);
789         free(V_pf_idhash, M_PFHASH);
790
791         for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
792                 KASSERT(LIST_EMPTY(&sh->nodes),
793                     ("%s: source node hash not empty", __func__));
794                 mtx_destroy(&sh->lock);
795         }
796         free(V_pf_srchash, M_PFHASH);
797
798         STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
799                 m_freem(pfse->pfse_m);
800                 free(pfse, M_PFTEMP);
801         }
802
803         mtx_destroy(&pf_sendqueue_mtx);
804         mtx_destroy(&pf_overloadqueue_mtx);
805         mtx_destroy(&pf_unlnkdrules_mtx);
806
807         uma_zdestroy(V_pf_mtag_z);
808         uma_zdestroy(V_pf_sources_z);
809         uma_zdestroy(V_pf_state_z);
810         uma_zdestroy(V_pf_state_key_z);
811 }
812
813 static int
814 pf_mtag_init(void *mem, int size, int how)
815 {
816         struct m_tag *t;
817
818         t = (struct m_tag *)mem;
819         t->m_tag_cookie = MTAG_ABI_COMPAT;
820         t->m_tag_id = PACKET_TAG_PF;
821         t->m_tag_len = sizeof(struct pf_mtag);
822         t->m_tag_free = pf_mtag_free;
823
824         return (0);
825 }
826
827 static void
828 pf_mtag_free(struct m_tag *t)
829 {
830
831         uma_zfree(V_pf_mtag_z, t);
832 }
833
834 struct pf_mtag *
835 pf_get_mtag(struct mbuf *m)
836 {
837         struct m_tag *mtag;
838
839         if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
840                 return ((struct pf_mtag *)(mtag + 1));
841
842         mtag = uma_zalloc(V_pf_mtag_z, M_NOWAIT);
843         if (mtag == NULL)
844                 return (NULL);
845         bzero(mtag + 1, sizeof(struct pf_mtag));
846         m_tag_prepend(m, mtag);
847
848         return ((struct pf_mtag *)(mtag + 1));
849 }
850
851 static int
852 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
853     struct pf_state *s)
854 {
855         struct pf_keyhash       *khs, *khw, *kh;
856         struct pf_state_key     *sk, *cur;
857         struct pf_state         *si, *olds = NULL;
858         int idx;
859
860         KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
861         KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
862         KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
863
864         /*
865          * We need to lock hash slots of both keys. To avoid deadlock
866          * we always lock the slot with lower address first. Unlock order
867          * isn't important.
868          *
869          * We also need to lock ID hash slot before dropping key
870          * locks. On success we return with ID hash slot locked.
871          */
872
873         if (skw == sks) {
874                 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
875                 PF_HASHROW_LOCK(khs);
876         } else {
877                 khs = &V_pf_keyhash[pf_hashkey(sks)];
878                 khw = &V_pf_keyhash[pf_hashkey(skw)];
879                 if (khs == khw) {
880                         PF_HASHROW_LOCK(khs);
881                 } else if (khs < khw) {
882                         PF_HASHROW_LOCK(khs);
883                         PF_HASHROW_LOCK(khw);
884                 } else {
885                         PF_HASHROW_LOCK(khw);
886                         PF_HASHROW_LOCK(khs);
887                 }
888         }
889
890 #define KEYS_UNLOCK()   do {                    \
891         if (khs != khw) {                       \
892                 PF_HASHROW_UNLOCK(khs);         \
893                 PF_HASHROW_UNLOCK(khw);         \
894         } else                                  \
895                 PF_HASHROW_UNLOCK(khs);         \
896 } while (0)
897
898         /*
899          * First run: start with wire key.
900          */
901         sk = skw;
902         kh = khw;
903         idx = PF_SK_WIRE;
904
905 keyattach:
906         LIST_FOREACH(cur, &kh->keys, entry)
907                 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
908                         break;
909
910         if (cur != NULL) {
911                 /* Key exists. Check for same kif, if none, add to key. */
912                 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
913                         struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
914
915                         PF_HASHROW_LOCK(ih);
916                         if (si->kif == s->kif &&
917                             si->direction == s->direction) {
918                                 if (sk->proto == IPPROTO_TCP &&
919                                     si->src.state >= TCPS_FIN_WAIT_2 &&
920                                     si->dst.state >= TCPS_FIN_WAIT_2) {
921                                         /*
922                                          * New state matches an old >FIN_WAIT_2
923                                          * state. We can't drop key hash locks,
924                                          * thus we can't unlink it properly.
925                                          *
926                                          * As a workaround we drop it into
927                                          * TCPS_CLOSED state, schedule purge
928                                          * ASAP and push it into the very end
929                                          * of the slot TAILQ, so that it won't
930                                          * conflict with our new state.
931                                          */
932                                         si->src.state = si->dst.state =
933                                             TCPS_CLOSED;
934                                         si->timeout = PFTM_PURGE;
935                                         olds = si;
936                                 } else {
937                                         if (V_pf_status.debug >= PF_DEBUG_MISC) {
938                                                 printf("pf: %s key attach "
939                                                     "failed on %s: ",
940                                                     (idx == PF_SK_WIRE) ?
941                                                     "wire" : "stack",
942                                                     s->kif->pfik_name);
943                                                 pf_print_state_parts(s,
944                                                     (idx == PF_SK_WIRE) ?
945                                                     sk : NULL,
946                                                     (idx == PF_SK_STACK) ?
947                                                     sk : NULL);
948                                                 printf(", existing: ");
949                                                 pf_print_state_parts(si,
950                                                     (idx == PF_SK_WIRE) ?
951                                                     sk : NULL,
952                                                     (idx == PF_SK_STACK) ?
953                                                     sk : NULL);
954                                                 printf("\n");
955                                         }
956                                         PF_HASHROW_UNLOCK(ih);
957                                         KEYS_UNLOCK();
958                                         uma_zfree(V_pf_state_key_z, sk);
959                                         if (idx == PF_SK_STACK)
960                                                 pf_detach_state(s);
961                                         return (EEXIST); /* collision! */
962                                 }
963                         }
964                         PF_HASHROW_UNLOCK(ih);
965                 }
966                 uma_zfree(V_pf_state_key_z, sk);
967                 s->key[idx] = cur;
968         } else {
969                 LIST_INSERT_HEAD(&kh->keys, sk, entry);
970                 s->key[idx] = sk;
971         }
972
973 stateattach:
974         /* List is sorted, if-bound states before floating. */
975         if (s->kif == V_pfi_all)
976                 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
977         else
978                 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
979
980         if (olds) {
981                 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
982                 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
983                     key_list[idx]);
984                 olds = NULL;
985         }
986
987         /*
988          * Attach done. See how should we (or should not?)
989          * attach a second key.
990          */
991         if (sks == skw) {
992                 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
993                 idx = PF_SK_STACK;
994                 sks = NULL;
995                 goto stateattach;
996         } else if (sks != NULL) {
997                 /*
998                  * Continue attaching with stack key.
999                  */
1000                 sk = sks;
1001                 kh = khs;
1002                 idx = PF_SK_STACK;
1003                 sks = NULL;
1004                 goto keyattach;
1005         }
1006
1007         PF_STATE_LOCK(s);
1008         KEYS_UNLOCK();
1009
1010         KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1011             ("%s failure", __func__));
1012
1013         return (0);
1014 #undef  KEYS_UNLOCK
1015 }
1016
1017 static void
1018 pf_detach_state(struct pf_state *s)
1019 {
1020         struct pf_state_key *sks = s->key[PF_SK_STACK];
1021         struct pf_keyhash *kh;
1022
1023         if (sks != NULL) {
1024                 kh = &V_pf_keyhash[pf_hashkey(sks)];
1025                 PF_HASHROW_LOCK(kh);
1026                 if (s->key[PF_SK_STACK] != NULL)
1027                         pf_state_key_detach(s, PF_SK_STACK);
1028                 /*
1029                  * If both point to same key, then we are done.
1030                  */
1031                 if (sks == s->key[PF_SK_WIRE]) {
1032                         pf_state_key_detach(s, PF_SK_WIRE);
1033                         PF_HASHROW_UNLOCK(kh);
1034                         return;
1035                 }
1036                 PF_HASHROW_UNLOCK(kh);
1037         }
1038
1039         if (s->key[PF_SK_WIRE] != NULL) {
1040                 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1041                 PF_HASHROW_LOCK(kh);
1042                 if (s->key[PF_SK_WIRE] != NULL)
1043                         pf_state_key_detach(s, PF_SK_WIRE);
1044                 PF_HASHROW_UNLOCK(kh);
1045         }
1046 }
1047
1048 static void
1049 pf_state_key_detach(struct pf_state *s, int idx)
1050 {
1051         struct pf_state_key *sk = s->key[idx];
1052 #ifdef INVARIANTS
1053         struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1054
1055         PF_HASHROW_ASSERT(kh);
1056 #endif
1057         TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1058         s->key[idx] = NULL;
1059
1060         if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1061                 LIST_REMOVE(sk, entry);
1062                 uma_zfree(V_pf_state_key_z, sk);
1063         }
1064 }
1065
1066 static int
1067 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1068 {
1069         struct pf_state_key *sk = mem;
1070
1071         bzero(sk, sizeof(struct pf_state_key_cmp));
1072         TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1073         TAILQ_INIT(&sk->states[PF_SK_STACK]);
1074
1075         return (0);
1076 }
1077
1078 struct pf_state_key *
1079 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1080         struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1081 {
1082         struct pf_state_key *sk;
1083
1084         sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1085         if (sk == NULL)
1086                 return (NULL);
1087
1088         PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1089         PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1090         sk->port[pd->sidx] = sport;
1091         sk->port[pd->didx] = dport;
1092         sk->proto = pd->proto;
1093         sk->af = pd->af;
1094
1095         return (sk);
1096 }
1097
1098 struct pf_state_key *
1099 pf_state_key_clone(struct pf_state_key *orig)
1100 {
1101         struct pf_state_key *sk;
1102
1103         sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1104         if (sk == NULL)
1105                 return (NULL);
1106
1107         bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1108
1109         return (sk);
1110 }
1111
1112 int
1113 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1114     struct pf_state_key *sks, struct pf_state *s)
1115 {
1116         struct pf_idhash *ih;
1117         struct pf_state *cur;
1118         int error;
1119
1120         KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1121             ("%s: sks not pristine", __func__));
1122         KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1123             ("%s: skw not pristine", __func__));
1124         KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1125
1126         s->kif = kif;
1127
1128         if (s->id == 0 && s->creatorid == 0) {
1129                 /* XXX: should be atomic, but probability of collision low */
1130                 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1131                         V_pf_stateid[curcpu] = 1;
1132                 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1133                 s->id = htobe64(s->id);
1134                 s->creatorid = V_pf_status.hostid;
1135         }
1136
1137         /* Returns with ID locked on success. */
1138         if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1139                 return (error);
1140
1141         ih = &V_pf_idhash[PF_IDHASH(s)];
1142         PF_HASHROW_ASSERT(ih);
1143         LIST_FOREACH(cur, &ih->states, entry)
1144                 if (cur->id == s->id && cur->creatorid == s->creatorid)
1145                         break;
1146
1147         if (cur != NULL) {
1148                 PF_HASHROW_UNLOCK(ih);
1149                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1150                         printf("pf: state ID collision: "
1151                             "id: %016llx creatorid: %08x\n",
1152                             (unsigned long long)be64toh(s->id),
1153                             ntohl(s->creatorid));
1154                 }
1155                 pf_detach_state(s);
1156                 return (EEXIST);
1157         }
1158         LIST_INSERT_HEAD(&ih->states, s, entry);
1159         /* One for keys, one for ID hash. */
1160         refcount_init(&s->refs, 2);
1161
1162         V_pf_status.fcounters[FCNT_STATE_INSERT]++;
1163         if (pfsync_insert_state_ptr != NULL)
1164                 pfsync_insert_state_ptr(s);
1165
1166         /* Returns locked. */
1167         return (0);
1168 }
1169
1170 /*
1171  * Find state by ID: returns with locked row on success.
1172  */
1173 struct pf_state *
1174 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1175 {
1176         struct pf_idhash *ih;
1177         struct pf_state *s;
1178
1179         V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1180
1181         ih = &V_pf_idhash[(be64toh(id) % (V_pf_hashmask + 1))];
1182
1183         PF_HASHROW_LOCK(ih);
1184         LIST_FOREACH(s, &ih->states, entry)
1185                 if (s->id == id && s->creatorid == creatorid)
1186                         break;
1187
1188         if (s == NULL)
1189                 PF_HASHROW_UNLOCK(ih);
1190
1191         return (s);
1192 }
1193
1194 /*
1195  * Find state by key.
1196  * Returns with ID hash slot locked on success.
1197  */
1198 static struct pf_state *
1199 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1200 {
1201         struct pf_keyhash       *kh;
1202         struct pf_state_key     *sk;
1203         struct pf_state         *s;
1204         int idx;
1205
1206         V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1207
1208         kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1209
1210         PF_HASHROW_LOCK(kh);
1211         LIST_FOREACH(sk, &kh->keys, entry)
1212                 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1213                         break;
1214         if (sk == NULL) {
1215                 PF_HASHROW_UNLOCK(kh);
1216                 return (NULL);
1217         }
1218
1219         idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1220
1221         /* List is sorted, if-bound states before floating ones. */
1222         TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1223                 if (s->kif == V_pfi_all || s->kif == kif) {
1224                         PF_STATE_LOCK(s);
1225                         PF_HASHROW_UNLOCK(kh);
1226                         if (s->timeout == PFTM_UNLINKED) {
1227                                 /*
1228                                  * State is being processed
1229                                  * by pf_unlink_state() in
1230                                  * an other thread.
1231                                  */
1232                                 PF_STATE_UNLOCK(s);
1233                                 return (NULL);
1234                         }
1235                         return (s);
1236                 }
1237         PF_HASHROW_UNLOCK(kh);
1238
1239         return (NULL);
1240 }
1241
1242 struct pf_state *
1243 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1244 {
1245         struct pf_keyhash       *kh;
1246         struct pf_state_key     *sk;
1247         struct pf_state         *s, *ret = NULL;
1248         int                      idx, inout = 0;
1249
1250         V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1251
1252         kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1253
1254         PF_HASHROW_LOCK(kh);
1255         LIST_FOREACH(sk, &kh->keys, entry)
1256                 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1257                         break;
1258         if (sk == NULL) {
1259                 PF_HASHROW_UNLOCK(kh);
1260                 return (NULL);
1261         }
1262         switch (dir) {
1263         case PF_IN:
1264                 idx = PF_SK_WIRE;
1265                 break;
1266         case PF_OUT:
1267                 idx = PF_SK_STACK;
1268                 break;
1269         case PF_INOUT:
1270                 idx = PF_SK_WIRE;
1271                 inout = 1;
1272                 break;
1273         default:
1274                 panic("%s: dir %u", __func__, dir);
1275         }
1276 second_run:
1277         TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1278                 if (more == NULL) {
1279                         PF_HASHROW_UNLOCK(kh);
1280                         return (s);
1281                 }
1282
1283                 if (ret)
1284                         (*more)++;
1285                 else
1286                         ret = s;
1287         }
1288         if (inout == 1) {
1289                 inout = 0;
1290                 idx = PF_SK_STACK;
1291                 goto second_run;
1292         }
1293         PF_HASHROW_UNLOCK(kh);
1294
1295         return (ret);
1296 }
1297
1298 /* END state table stuff */
1299
1300 static void
1301 pf_send(struct pf_send_entry *pfse)
1302 {
1303
1304         PF_SENDQ_LOCK();
1305         STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1306         PF_SENDQ_UNLOCK();
1307         swi_sched(V_pf_swi_cookie, 0);
1308 }
1309
1310 void
1311 pf_intr(void *v)
1312 {
1313         struct pf_send_head queue;
1314         struct pf_send_entry *pfse, *next;
1315
1316         CURVNET_SET((struct vnet *)v);
1317
1318         PF_SENDQ_LOCK();
1319         queue = V_pf_sendqueue;
1320         STAILQ_INIT(&V_pf_sendqueue);
1321         PF_SENDQ_UNLOCK();
1322
1323         STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1324                 switch (pfse->pfse_type) {
1325 #ifdef INET
1326                 case PFSE_IP:
1327                         ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1328                         break;
1329                 case PFSE_ICMP:
1330                         icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1331                             pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1332                         break;
1333 #endif /* INET */
1334 #ifdef INET6
1335                 case PFSE_IP6:
1336                         ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1337                             NULL);
1338                         break;
1339                 case PFSE_ICMP6:
1340                         icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1341                             pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1342                         break;
1343 #endif /* INET6 */
1344                 default:
1345                         panic("%s: unknown type", __func__);
1346                 }
1347                 free(pfse, M_PFTEMP);
1348         }
1349         CURVNET_RESTORE();
1350 }
1351
1352 void
1353 pf_purge_thread(void *v)
1354 {
1355         u_int idx = 0;
1356
1357         CURVNET_SET((struct vnet *)v);
1358
1359         for (;;) {
1360                 PF_RULES_RLOCK();
1361                 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1362
1363                 if (V_pf_end_threads) {
1364                         /*
1365                          * To cleanse up all kifs and rules we need
1366                          * two runs: first one clears reference flags,
1367                          * then pf_purge_expired_states() doesn't
1368                          * raise them, and then second run frees.
1369                          */
1370                         PF_RULES_RUNLOCK();
1371                         pf_purge_unlinked_rules();
1372                         pfi_kif_purge();
1373
1374                         /*
1375                          * Now purge everything.
1376                          */
1377                         pf_purge_expired_states(0, V_pf_hashmask);
1378                         pf_purge_expired_fragments();
1379                         pf_purge_expired_src_nodes();
1380
1381                         /*
1382                          * Now all kifs & rules should be unreferenced,
1383                          * thus should be successfully freed.
1384                          */
1385                         pf_purge_unlinked_rules();
1386                         pfi_kif_purge();
1387
1388                         /*
1389                          * Announce success and exit.
1390                          */
1391                         PF_RULES_RLOCK();
1392                         V_pf_end_threads++;
1393                         PF_RULES_RUNLOCK();
1394                         wakeup(pf_purge_thread);
1395                         kproc_exit(0);
1396                 }
1397                 PF_RULES_RUNLOCK();
1398
1399                 /* Process 1/interval fraction of the state table every run. */
1400                 idx = pf_purge_expired_states(idx, V_pf_hashmask /
1401                             (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1402
1403                 /* Purge other expired types every PFTM_INTERVAL seconds. */
1404                 if (idx == 0) {
1405                         /*
1406                          * Order is important:
1407                          * - states and src nodes reference rules
1408                          * - states and rules reference kifs
1409                          */
1410                         pf_purge_expired_fragments();
1411                         pf_purge_expired_src_nodes();
1412                         pf_purge_unlinked_rules();
1413                         pfi_kif_purge();
1414                 }
1415         }
1416         /* not reached */
1417         CURVNET_RESTORE();
1418 }
1419
1420 u_int32_t
1421 pf_state_expires(const struct pf_state *state)
1422 {
1423         u_int32_t       timeout;
1424         u_int32_t       start;
1425         u_int32_t       end;
1426         u_int32_t       states;
1427
1428         /* handle all PFTM_* > PFTM_MAX here */
1429         if (state->timeout == PFTM_PURGE)
1430                 return (time_uptime);
1431         if (state->timeout == PFTM_UNTIL_PACKET)
1432                 return (0);
1433         KASSERT(state->timeout != PFTM_UNLINKED,
1434             ("pf_state_expires: timeout == PFTM_UNLINKED"));
1435         KASSERT((state->timeout < PFTM_MAX),
1436             ("pf_state_expires: timeout > PFTM_MAX"));
1437         timeout = state->rule.ptr->timeout[state->timeout];
1438         if (!timeout)
1439                 timeout = V_pf_default_rule.timeout[state->timeout];
1440         start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1441         if (start) {
1442                 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1443                 states = state->rule.ptr->states_cur;   /* XXXGL */
1444         } else {
1445                 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1446                 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1447                 states = V_pf_status.states;
1448         }
1449         if (end && states > start && start < end) {
1450                 if (states < end)
1451                         return (state->expire + timeout * (end - states) /
1452                             (end - start));
1453                 else
1454                         return (time_uptime);
1455         }
1456         return (state->expire + timeout);
1457 }
1458
1459 void
1460 pf_purge_expired_src_nodes()
1461 {
1462         struct pf_srchash       *sh;
1463         struct pf_src_node      *cur, *next;
1464         int i;
1465
1466         for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
1467             PF_HASHROW_LOCK(sh);
1468             LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1469                 if (cur->states <= 0 && cur->expire <= time_uptime) {
1470                         if (cur->rule.ptr != NULL)
1471                                 cur->rule.ptr->src_nodes--;
1472                         LIST_REMOVE(cur, entry);
1473                         V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1474                         V_pf_status.src_nodes--;
1475                         uma_zfree(V_pf_sources_z, cur);
1476                 } else if (cur->rule.ptr != NULL)
1477                         cur->rule.ptr->rule_flag |= PFRULE_REFS;
1478             PF_HASHROW_UNLOCK(sh);
1479         }
1480 }
1481
1482 static void
1483 pf_src_tree_remove_state(struct pf_state *s)
1484 {
1485         u_int32_t timeout;
1486
1487         if (s->src_node != NULL) {
1488                 if (s->src.tcp_est)
1489                         --s->src_node->conn;
1490                 if (--s->src_node->states <= 0) {
1491                         timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1492                         if (!timeout)
1493                                 timeout =
1494                                     V_pf_default_rule.timeout[PFTM_SRC_NODE];
1495                         s->src_node->expire = time_uptime + timeout;
1496                 }
1497         }
1498         if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1499                 if (--s->nat_src_node->states <= 0) {
1500                         timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1501                         if (!timeout)
1502                                 timeout =
1503                                     V_pf_default_rule.timeout[PFTM_SRC_NODE];
1504                         s->nat_src_node->expire = time_uptime + timeout;
1505                 }
1506         }
1507         s->src_node = s->nat_src_node = NULL;
1508 }
1509
1510 /*
1511  * Unlink and potentilly free a state. Function may be
1512  * called with ID hash row locked, but always returns
1513  * unlocked, since it needs to go through key hash locking.
1514  */
1515 int
1516 pf_unlink_state(struct pf_state *s, u_int flags)
1517 {
1518         struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1519
1520         if ((flags & PF_ENTER_LOCKED) == 0)
1521                 PF_HASHROW_LOCK(ih);
1522         else
1523                 PF_HASHROW_ASSERT(ih);
1524
1525         if (s->timeout == PFTM_UNLINKED) {
1526                 /*
1527                  * State is being processed
1528                  * by pf_unlink_state() in
1529                  * an other thread.
1530                  */
1531                 PF_HASHROW_UNLOCK(ih);
1532                 return (0);     /* XXXGL: undefined actually */
1533         }
1534
1535         if (s->src.state == PF_TCPS_PROXY_DST) {
1536                 /* XXX wire key the right one? */
1537                 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1538                     &s->key[PF_SK_WIRE]->addr[1],
1539                     &s->key[PF_SK_WIRE]->addr[0],
1540                     s->key[PF_SK_WIRE]->port[1],
1541                     s->key[PF_SK_WIRE]->port[0],
1542                     s->src.seqhi, s->src.seqlo + 1,
1543                     TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1544         }
1545
1546         LIST_REMOVE(s, entry);
1547         pf_src_tree_remove_state(s);
1548
1549         if (pfsync_delete_state_ptr != NULL)
1550                 pfsync_delete_state_ptr(s);
1551
1552         --s->rule.ptr->states_cur;
1553         if (s->nat_rule.ptr != NULL)
1554                 --s->nat_rule.ptr->states_cur;
1555         if (s->anchor.ptr != NULL)
1556                 --s->anchor.ptr->states_cur;
1557
1558         s->timeout = PFTM_UNLINKED;
1559
1560         PF_HASHROW_UNLOCK(ih);
1561
1562         pf_detach_state(s);
1563         refcount_release(&s->refs);
1564
1565         return (pf_release_state(s));
1566 }
1567
1568 void
1569 pf_free_state(struct pf_state *cur)
1570 {
1571
1572         KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1573         KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1574             cur->timeout));
1575
1576         pf_normalize_tcp_cleanup(cur);
1577         uma_zfree(V_pf_state_z, cur);
1578         V_pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1579 }
1580
1581 /*
1582  * Called only from pf_purge_thread(), thus serialized.
1583  */
1584 static u_int
1585 pf_purge_expired_states(u_int i, int maxcheck)
1586 {
1587         struct pf_idhash *ih;
1588         struct pf_state *s;
1589
1590         V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1591
1592         /*
1593          * Go through hash and unlink states that expire now.
1594          */
1595         while (maxcheck > 0) {
1596
1597                 ih = &V_pf_idhash[i];
1598 relock:
1599                 PF_HASHROW_LOCK(ih);
1600                 LIST_FOREACH(s, &ih->states, entry) {
1601                         if (pf_state_expires(s) <= time_uptime) {
1602                                 V_pf_status.states -=
1603                                     pf_unlink_state(s, PF_ENTER_LOCKED);
1604                                 goto relock;
1605                         }
1606                         s->rule.ptr->rule_flag |= PFRULE_REFS;
1607                         if (s->nat_rule.ptr != NULL)
1608                                 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1609                         if (s->anchor.ptr != NULL)
1610                                 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1611                         s->kif->pfik_flags |= PFI_IFLAG_REFS;
1612                         if (s->rt_kif)
1613                                 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1614                 }
1615                 PF_HASHROW_UNLOCK(ih);
1616
1617                 /* Return when we hit end of hash. */
1618                 if (++i > V_pf_hashmask) {
1619                         V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1620                         return (0);
1621                 }
1622
1623                 maxcheck--;
1624         }
1625
1626         V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1627
1628         return (i);
1629 }
1630
1631 static void
1632 pf_purge_unlinked_rules()
1633 {
1634         struct pf_rulequeue tmpq;
1635         struct pf_rule *r, *r1;
1636
1637         /*
1638          * If we have overloading task pending, then we'd
1639          * better skip purging this time. There is a tiny
1640          * probability that overloading task references
1641          * an already unlinked rule.
1642          */
1643         PF_OVERLOADQ_LOCK();
1644         if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1645                 PF_OVERLOADQ_UNLOCK();
1646                 return;
1647         }
1648         PF_OVERLOADQ_UNLOCK();
1649
1650         /*
1651          * Do naive mark-and-sweep garbage collecting of old rules.
1652          * Reference flag is raised by pf_purge_expired_states()
1653          * and pf_purge_expired_src_nodes().
1654          *
1655          * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1656          * use a temporary queue.
1657          */
1658         TAILQ_INIT(&tmpq);
1659         PF_UNLNKDRULES_LOCK();
1660         TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1661                 if (!(r->rule_flag & PFRULE_REFS)) {
1662                         TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1663                         TAILQ_INSERT_TAIL(&tmpq, r, entries);
1664                 } else
1665                         r->rule_flag &= ~PFRULE_REFS;
1666         }
1667         PF_UNLNKDRULES_UNLOCK();
1668
1669         if (!TAILQ_EMPTY(&tmpq)) {
1670                 PF_RULES_WLOCK();
1671                 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1672                         TAILQ_REMOVE(&tmpq, r, entries);
1673                         pf_free_rule(r);
1674                 }
1675                 PF_RULES_WUNLOCK();
1676         }
1677 }
1678
1679 void
1680 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1681 {
1682         switch (af) {
1683 #ifdef INET
1684         case AF_INET: {
1685                 u_int32_t a = ntohl(addr->addr32[0]);
1686                 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1687                     (a>>8)&255, a&255);
1688                 if (p) {
1689                         p = ntohs(p);
1690                         printf(":%u", p);
1691                 }
1692                 break;
1693         }
1694 #endif /* INET */
1695 #ifdef INET6
1696         case AF_INET6: {
1697                 u_int16_t b;
1698                 u_int8_t i, curstart, curend, maxstart, maxend;
1699                 curstart = curend = maxstart = maxend = 255;
1700                 for (i = 0; i < 8; i++) {
1701                         if (!addr->addr16[i]) {
1702                                 if (curstart == 255)
1703                                         curstart = i;
1704                                 curend = i;
1705                         } else {
1706                                 if ((curend - curstart) >
1707                                     (maxend - maxstart)) {
1708                                         maxstart = curstart;
1709                                         maxend = curend;
1710                                 }
1711                                 curstart = curend = 255;
1712                         }
1713                 }
1714                 if ((curend - curstart) >
1715                     (maxend - maxstart)) {
1716                         maxstart = curstart;
1717                         maxend = curend;
1718                 }
1719                 for (i = 0; i < 8; i++) {
1720                         if (i >= maxstart && i <= maxend) {
1721                                 if (i == 0)
1722                                         printf(":");
1723                                 if (i == maxend)
1724                                         printf(":");
1725                         } else {
1726                                 b = ntohs(addr->addr16[i]);
1727                                 printf("%x", b);
1728                                 if (i < 7)
1729                                         printf(":");
1730                         }
1731                 }
1732                 if (p) {
1733                         p = ntohs(p);
1734                         printf("[%u]", p);
1735                 }
1736                 break;
1737         }
1738 #endif /* INET6 */
1739         }
1740 }
1741
1742 void
1743 pf_print_state(struct pf_state *s)
1744 {
1745         pf_print_state_parts(s, NULL, NULL);
1746 }
1747
1748 static void
1749 pf_print_state_parts(struct pf_state *s,
1750     struct pf_state_key *skwp, struct pf_state_key *sksp)
1751 {
1752         struct pf_state_key *skw, *sks;
1753         u_int8_t proto, dir;
1754
1755         /* Do our best to fill these, but they're skipped if NULL */
1756         skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1757         sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1758         proto = skw ? skw->proto : (sks ? sks->proto : 0);
1759         dir = s ? s->direction : 0;
1760
1761         switch (proto) {
1762         case IPPROTO_IPV4:
1763                 printf("IPv4");
1764                 break;
1765         case IPPROTO_IPV6:
1766                 printf("IPv6");
1767                 break;
1768         case IPPROTO_TCP:
1769                 printf("TCP");
1770                 break;
1771         case IPPROTO_UDP:
1772                 printf("UDP");
1773                 break;
1774         case IPPROTO_ICMP:
1775                 printf("ICMP");
1776                 break;
1777         case IPPROTO_ICMPV6:
1778                 printf("ICMPv6");
1779                 break;
1780         default:
1781                 printf("%u", skw->proto);
1782                 break;
1783         }
1784         switch (dir) {
1785         case PF_IN:
1786                 printf(" in");
1787                 break;
1788         case PF_OUT:
1789                 printf(" out");
1790                 break;
1791         }
1792         if (skw) {
1793                 printf(" wire: ");
1794                 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1795                 printf(" ");
1796                 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1797         }
1798         if (sks) {
1799                 printf(" stack: ");
1800                 if (sks != skw) {
1801                         pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1802                         printf(" ");
1803                         pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1804                 } else
1805                         printf("-");
1806         }
1807         if (s) {
1808                 if (proto == IPPROTO_TCP) {
1809                         printf(" [lo=%u high=%u win=%u modulator=%u",
1810                             s->src.seqlo, s->src.seqhi,
1811                             s->src.max_win, s->src.seqdiff);
1812                         if (s->src.wscale && s->dst.wscale)
1813                                 printf(" wscale=%u",
1814                                     s->src.wscale & PF_WSCALE_MASK);
1815                         printf("]");
1816                         printf(" [lo=%u high=%u win=%u modulator=%u",
1817                             s->dst.seqlo, s->dst.seqhi,
1818                             s->dst.max_win, s->dst.seqdiff);
1819                         if (s->src.wscale && s->dst.wscale)
1820                                 printf(" wscale=%u",
1821                                 s->dst.wscale & PF_WSCALE_MASK);
1822                         printf("]");
1823                 }
1824                 printf(" %u:%u", s->src.state, s->dst.state);
1825         }
1826 }
1827
1828 void
1829 pf_print_flags(u_int8_t f)
1830 {
1831         if (f)
1832                 printf(" ");
1833         if (f & TH_FIN)
1834                 printf("F");
1835         if (f & TH_SYN)
1836                 printf("S");
1837         if (f & TH_RST)
1838                 printf("R");
1839         if (f & TH_PUSH)
1840                 printf("P");
1841         if (f & TH_ACK)
1842                 printf("A");
1843         if (f & TH_URG)
1844                 printf("U");
1845         if (f & TH_ECE)
1846                 printf("E");
1847         if (f & TH_CWR)
1848                 printf("W");
1849 }
1850
1851 #define PF_SET_SKIP_STEPS(i)                                    \
1852         do {                                                    \
1853                 while (head[i] != cur) {                        \
1854                         head[i]->skip[i].ptr = cur;             \
1855                         head[i] = TAILQ_NEXT(head[i], entries); \
1856                 }                                               \
1857         } while (0)
1858
1859 void
1860 pf_calc_skip_steps(struct pf_rulequeue *rules)
1861 {
1862         struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1863         int i;
1864
1865         cur = TAILQ_FIRST(rules);
1866         prev = cur;
1867         for (i = 0; i < PF_SKIP_COUNT; ++i)
1868                 head[i] = cur;
1869         while (cur != NULL) {
1870
1871                 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1872                         PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1873                 if (cur->direction != prev->direction)
1874                         PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1875                 if (cur->af != prev->af)
1876                         PF_SET_SKIP_STEPS(PF_SKIP_AF);
1877                 if (cur->proto != prev->proto)
1878                         PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1879                 if (cur->src.neg != prev->src.neg ||
1880                     pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1881                         PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1882                 if (cur->src.port[0] != prev->src.port[0] ||
1883                     cur->src.port[1] != prev->src.port[1] ||
1884                     cur->src.port_op != prev->src.port_op)
1885                         PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1886                 if (cur->dst.neg != prev->dst.neg ||
1887                     pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1888                         PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1889                 if (cur->dst.port[0] != prev->dst.port[0] ||
1890                     cur->dst.port[1] != prev->dst.port[1] ||
1891                     cur->dst.port_op != prev->dst.port_op)
1892                         PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1893
1894                 prev = cur;
1895                 cur = TAILQ_NEXT(cur, entries);
1896         }
1897         for (i = 0; i < PF_SKIP_COUNT; ++i)
1898                 PF_SET_SKIP_STEPS(i);
1899 }
1900
1901 static int
1902 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1903 {
1904         if (aw1->type != aw2->type)
1905                 return (1);
1906         switch (aw1->type) {
1907         case PF_ADDR_ADDRMASK:
1908         case PF_ADDR_RANGE:
1909                 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1910                         return (1);
1911                 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1912                         return (1);
1913                 return (0);
1914         case PF_ADDR_DYNIFTL:
1915                 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1916         case PF_ADDR_NOROUTE:
1917         case PF_ADDR_URPFFAILED:
1918                 return (0);
1919         case PF_ADDR_TABLE:
1920                 return (aw1->p.tbl != aw2->p.tbl);
1921         default:
1922                 printf("invalid address type: %d\n", aw1->type);
1923                 return (1);
1924         }
1925 }
1926
1927 u_int16_t
1928 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1929 {
1930         u_int32_t       l;
1931
1932         if (udp && !cksum)
1933                 return (0x0000);
1934         l = cksum + old - new;
1935         l = (l >> 16) + (l & 65535);
1936         l = l & 65535;
1937         if (udp && !l)
1938                 return (0xFFFF);
1939         return (l);
1940 }
1941
1942 static void
1943 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1944     struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1945 {
1946         struct pf_addr  ao;
1947         u_int16_t       po = *p;
1948
1949         PF_ACPY(&ao, a, af);
1950         PF_ACPY(a, an, af);
1951
1952         *p = pn;
1953
1954         switch (af) {
1955 #ifdef INET
1956         case AF_INET:
1957                 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1958                     ao.addr16[0], an->addr16[0], 0),
1959                     ao.addr16[1], an->addr16[1], 0);
1960                 *p = pn;
1961                 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1962                     ao.addr16[0], an->addr16[0], u),
1963                     ao.addr16[1], an->addr16[1], u),
1964                     po, pn, u);
1965                 break;
1966 #endif /* INET */
1967 #ifdef INET6
1968         case AF_INET6:
1969                 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1970                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1971                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1972                     ao.addr16[0], an->addr16[0], u),
1973                     ao.addr16[1], an->addr16[1], u),
1974                     ao.addr16[2], an->addr16[2], u),
1975                     ao.addr16[3], an->addr16[3], u),
1976                     ao.addr16[4], an->addr16[4], u),
1977                     ao.addr16[5], an->addr16[5], u),
1978                     ao.addr16[6], an->addr16[6], u),
1979                     ao.addr16[7], an->addr16[7], u),
1980                     po, pn, u);
1981                 break;
1982 #endif /* INET6 */
1983         }
1984 }
1985
1986
1987 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
1988 void
1989 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1990 {
1991         u_int32_t       ao;
1992
1993         memcpy(&ao, a, sizeof(ao));
1994         memcpy(a, &an, sizeof(u_int32_t));
1995         *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1996             ao % 65536, an % 65536, u);
1997 }
1998
1999 #ifdef INET6
2000 static void
2001 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2002 {
2003         struct pf_addr  ao;
2004
2005         PF_ACPY(&ao, a, AF_INET6);
2006         PF_ACPY(a, an, AF_INET6);
2007
2008         *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2009             pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2010             pf_cksum_fixup(pf_cksum_fixup(*c,
2011             ao.addr16[0], an->addr16[0], u),
2012             ao.addr16[1], an->addr16[1], u),
2013             ao.addr16[2], an->addr16[2], u),
2014             ao.addr16[3], an->addr16[3], u),
2015             ao.addr16[4], an->addr16[4], u),
2016             ao.addr16[5], an->addr16[5], u),
2017             ao.addr16[6], an->addr16[6], u),
2018             ao.addr16[7], an->addr16[7], u);
2019 }
2020 #endif /* INET6 */
2021
2022 static void
2023 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2024     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2025     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2026 {
2027         struct pf_addr  oia, ooa;
2028
2029         PF_ACPY(&oia, ia, af);
2030         if (oa)
2031                 PF_ACPY(&ooa, oa, af);
2032
2033         /* Change inner protocol port, fix inner protocol checksum. */
2034         if (ip != NULL) {
2035                 u_int16_t       oip = *ip;
2036                 u_int32_t       opc;
2037
2038                 if (pc != NULL)
2039                         opc = *pc;
2040                 *ip = np;
2041                 if (pc != NULL)
2042                         *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2043                 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2044                 if (pc != NULL)
2045                         *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2046         }
2047         /* Change inner ip address, fix inner ip and icmp checksums. */
2048         PF_ACPY(ia, na, af);
2049         switch (af) {
2050 #ifdef INET
2051         case AF_INET: {
2052                 u_int32_t        oh2c = *h2c;
2053
2054                 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2055                     oia.addr16[0], ia->addr16[0], 0),
2056                     oia.addr16[1], ia->addr16[1], 0);
2057                 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2058                     oia.addr16[0], ia->addr16[0], 0),
2059                     oia.addr16[1], ia->addr16[1], 0);
2060                 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2061                 break;
2062         }
2063 #endif /* INET */
2064 #ifdef INET6
2065         case AF_INET6:
2066                 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2067                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2068                     pf_cksum_fixup(pf_cksum_fixup(*ic,
2069                     oia.addr16[0], ia->addr16[0], u),
2070                     oia.addr16[1], ia->addr16[1], u),
2071                     oia.addr16[2], ia->addr16[2], u),
2072                     oia.addr16[3], ia->addr16[3], u),
2073                     oia.addr16[4], ia->addr16[4], u),
2074                     oia.addr16[5], ia->addr16[5], u),
2075                     oia.addr16[6], ia->addr16[6], u),
2076                     oia.addr16[7], ia->addr16[7], u);
2077                 break;
2078 #endif /* INET6 */
2079         }
2080         /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2081         if (oa) {
2082                 PF_ACPY(oa, na, af);
2083                 switch (af) {
2084 #ifdef INET
2085                 case AF_INET:
2086                         *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2087                             ooa.addr16[0], oa->addr16[0], 0),
2088                             ooa.addr16[1], oa->addr16[1], 0);
2089                         break;
2090 #endif /* INET */
2091 #ifdef INET6
2092                 case AF_INET6:
2093                         *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2094                             pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2095                             pf_cksum_fixup(pf_cksum_fixup(*ic,
2096                             ooa.addr16[0], oa->addr16[0], u),
2097                             ooa.addr16[1], oa->addr16[1], u),
2098                             ooa.addr16[2], oa->addr16[2], u),
2099                             ooa.addr16[3], oa->addr16[3], u),
2100                             ooa.addr16[4], oa->addr16[4], u),
2101                             ooa.addr16[5], oa->addr16[5], u),
2102                             ooa.addr16[6], oa->addr16[6], u),
2103                             ooa.addr16[7], oa->addr16[7], u);
2104                         break;
2105 #endif /* INET6 */
2106                 }
2107         }
2108 }
2109
2110
2111 /*
2112  * Need to modulate the sequence numbers in the TCP SACK option
2113  * (credits to Krzysztof Pfaff for report and patch)
2114  */
2115 static int
2116 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2117     struct tcphdr *th, struct pf_state_peer *dst)
2118 {
2119         int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2120         u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2121         int copyback = 0, i, olen;
2122         struct sackblk sack;
2123
2124 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2125         if (hlen < TCPOLEN_SACKLEN ||
2126             !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2127                 return 0;
2128
2129         while (hlen >= TCPOLEN_SACKLEN) {
2130                 olen = opt[1];
2131                 switch (*opt) {
2132                 case TCPOPT_EOL:        /* FALLTHROUGH */
2133                 case TCPOPT_NOP:
2134                         opt++;
2135                         hlen--;
2136                         break;
2137                 case TCPOPT_SACK:
2138                         if (olen > hlen)
2139                                 olen = hlen;
2140                         if (olen >= TCPOLEN_SACKLEN) {
2141                                 for (i = 2; i + TCPOLEN_SACK <= olen;
2142                                     i += TCPOLEN_SACK) {
2143                                         memcpy(&sack, &opt[i], sizeof(sack));
2144                                         pf_change_a(&sack.start, &th->th_sum,
2145                                             htonl(ntohl(sack.start) -
2146                                             dst->seqdiff), 0);
2147                                         pf_change_a(&sack.end, &th->th_sum,
2148                                             htonl(ntohl(sack.end) -
2149                                             dst->seqdiff), 0);
2150                                         memcpy(&opt[i], &sack, sizeof(sack));
2151                                 }
2152                                 copyback = 1;
2153                         }
2154                         /* FALLTHROUGH */
2155                 default:
2156                         if (olen < 2)
2157                                 olen = 2;
2158                         hlen -= olen;
2159                         opt += olen;
2160                 }
2161         }
2162
2163         if (copyback)
2164                 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2165         return (copyback);
2166 }
2167
2168 static void
2169 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2170     const struct pf_addr *saddr, const struct pf_addr *daddr,
2171     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2172     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2173     u_int16_t rtag, struct ifnet *ifp)
2174 {
2175         struct pf_send_entry *pfse;
2176         struct mbuf     *m;
2177         int              len, tlen;
2178 #ifdef INET
2179         struct ip       *h = NULL;
2180 #endif /* INET */
2181 #ifdef INET6
2182         struct ip6_hdr  *h6 = NULL;
2183 #endif /* INET6 */
2184         struct tcphdr   *th;
2185         char            *opt;
2186         struct pf_mtag  *pf_mtag;
2187
2188         len = 0;
2189         th = NULL;
2190
2191         /* maximum segment size tcp option */
2192         tlen = sizeof(struct tcphdr);
2193         if (mss)
2194                 tlen += 4;
2195
2196         switch (af) {
2197 #ifdef INET
2198         case AF_INET:
2199                 len = sizeof(struct ip) + tlen;
2200                 break;
2201 #endif /* INET */
2202 #ifdef INET6
2203         case AF_INET6:
2204                 len = sizeof(struct ip6_hdr) + tlen;
2205                 break;
2206 #endif /* INET6 */
2207         default:
2208                 panic("%s: unsupported af %d", __func__, af);
2209         }
2210
2211         /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2212         pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2213         if (pfse == NULL)
2214                 return;
2215         m = m_gethdr(M_NOWAIT, MT_DATA);
2216         if (m == NULL) {
2217                 free(pfse, M_PFTEMP);
2218                 return;
2219         }
2220 #ifdef MAC
2221         mac_netinet_firewall_send(m);
2222 #endif
2223         if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2224                 free(pfse, M_PFTEMP);
2225                 m_freem(m);
2226                 return;
2227         }
2228         if (tag)
2229                 m->m_flags |= M_SKIP_FIREWALL;
2230         pf_mtag->tag = rtag;
2231
2232         if (r != NULL && r->rtableid >= 0)
2233                 M_SETFIB(m, r->rtableid);
2234
2235 #ifdef ALTQ
2236         if (r != NULL && r->qid) {
2237                 pf_mtag->qid = r->qid;
2238
2239                 /* add hints for ecn */
2240                 pf_mtag->hdr = mtod(m, struct ip *);
2241         }
2242 #endif /* ALTQ */
2243         m->m_data += max_linkhdr;
2244         m->m_pkthdr.len = m->m_len = len;
2245         m->m_pkthdr.rcvif = NULL;
2246         bzero(m->m_data, len);
2247         switch (af) {
2248 #ifdef INET
2249         case AF_INET:
2250                 h = mtod(m, struct ip *);
2251
2252                 /* IP header fields included in the TCP checksum */
2253                 h->ip_p = IPPROTO_TCP;
2254                 h->ip_len = htons(tlen);
2255                 h->ip_src.s_addr = saddr->v4.s_addr;
2256                 h->ip_dst.s_addr = daddr->v4.s_addr;
2257
2258                 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2259                 break;
2260 #endif /* INET */
2261 #ifdef INET6
2262         case AF_INET6:
2263                 h6 = mtod(m, struct ip6_hdr *);
2264
2265                 /* IP header fields included in the TCP checksum */
2266                 h6->ip6_nxt = IPPROTO_TCP;
2267                 h6->ip6_plen = htons(tlen);
2268                 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2269                 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2270
2271                 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2272                 break;
2273 #endif /* INET6 */
2274         }
2275
2276         /* TCP header */
2277         th->th_sport = sport;
2278         th->th_dport = dport;
2279         th->th_seq = htonl(seq);
2280         th->th_ack = htonl(ack);
2281         th->th_off = tlen >> 2;
2282         th->th_flags = flags;
2283         th->th_win = htons(win);
2284
2285         if (mss) {
2286                 opt = (char *)(th + 1);
2287                 opt[0] = TCPOPT_MAXSEG;
2288                 opt[1] = 4;
2289                 HTONS(mss);
2290                 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2291         }
2292
2293         switch (af) {
2294 #ifdef INET
2295         case AF_INET:
2296                 /* TCP checksum */
2297                 th->th_sum = in_cksum(m, len);
2298
2299                 /* Finish the IP header */
2300                 h->ip_v = 4;
2301                 h->ip_hl = sizeof(*h) >> 2;
2302                 h->ip_tos = IPTOS_LOWDELAY;
2303                 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2304                 h->ip_len = htons(len);
2305                 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2306                 h->ip_sum = 0;
2307
2308                 pfse->pfse_type = PFSE_IP;
2309                 break;
2310 #endif /* INET */
2311 #ifdef INET6
2312         case AF_INET6:
2313                 /* TCP checksum */
2314                 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2315                     sizeof(struct ip6_hdr), tlen);
2316
2317                 h6->ip6_vfc |= IPV6_VERSION;
2318                 h6->ip6_hlim = IPV6_DEFHLIM;
2319
2320                 pfse->pfse_type = PFSE_IP6;
2321                 break;
2322 #endif /* INET6 */
2323         }
2324         pfse->pfse_m = m;
2325         pf_send(pfse);
2326 }
2327
2328 static void
2329 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2330     struct pf_rule *r)
2331 {
2332         struct pf_send_entry *pfse;
2333         struct mbuf *m0;
2334         struct pf_mtag *pf_mtag;
2335
2336         /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2337         pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2338         if (pfse == NULL)
2339                 return;
2340
2341         if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2342                 free(pfse, M_PFTEMP);
2343                 return;
2344         }
2345
2346         if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2347                 free(pfse, M_PFTEMP);
2348                 return;
2349         }
2350         /* XXX: revisit */
2351         m0->m_flags |= M_SKIP_FIREWALL;
2352
2353         if (r->rtableid >= 0)
2354                 M_SETFIB(m0, r->rtableid);
2355
2356 #ifdef ALTQ
2357         if (r->qid) {
2358                 pf_mtag->qid = r->qid;
2359                 /* add hints for ecn */
2360                 pf_mtag->hdr = mtod(m0, struct ip *);
2361         }
2362 #endif /* ALTQ */
2363
2364         switch (af) {
2365 #ifdef INET
2366         case AF_INET:
2367                 pfse->pfse_type = PFSE_ICMP;
2368                 break;
2369 #endif /* INET */
2370 #ifdef INET6
2371         case AF_INET6:
2372                 pfse->pfse_type = PFSE_ICMP6;
2373                 break;
2374 #endif /* INET6 */
2375         }
2376         pfse->pfse_m = m0;
2377         pfse->pfse_icmp_type = type;
2378         pfse->pfse_icmp_code = code;
2379         pf_send(pfse);
2380 }
2381
2382 /*
2383  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2384  * If n is 0, they match if they are equal. If n is != 0, they match if they
2385  * are different.
2386  */
2387 int
2388 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2389     struct pf_addr *b, sa_family_t af)
2390 {
2391         int     match = 0;
2392
2393         switch (af) {
2394 #ifdef INET
2395         case AF_INET:
2396                 if ((a->addr32[0] & m->addr32[0]) ==
2397                     (b->addr32[0] & m->addr32[0]))
2398                         match++;
2399                 break;
2400 #endif /* INET */
2401 #ifdef INET6
2402         case AF_INET6:
2403                 if (((a->addr32[0] & m->addr32[0]) ==
2404                      (b->addr32[0] & m->addr32[0])) &&
2405                     ((a->addr32[1] & m->addr32[1]) ==
2406                      (b->addr32[1] & m->addr32[1])) &&
2407                     ((a->addr32[2] & m->addr32[2]) ==
2408                      (b->addr32[2] & m->addr32[2])) &&
2409                     ((a->addr32[3] & m->addr32[3]) ==
2410                      (b->addr32[3] & m->addr32[3])))
2411                         match++;
2412                 break;
2413 #endif /* INET6 */
2414         }
2415         if (match) {
2416                 if (n)
2417                         return (0);
2418                 else
2419                         return (1);
2420         } else {
2421                 if (n)
2422                         return (1);
2423                 else
2424                         return (0);
2425         }
2426 }
2427
2428 /*
2429  * Return 1 if b <= a <= e, otherwise return 0.
2430  */
2431 int
2432 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2433     struct pf_addr *a, sa_family_t af)
2434 {
2435         switch (af) {
2436 #ifdef INET
2437         case AF_INET:
2438                 if ((a->addr32[0] < b->addr32[0]) ||
2439                     (a->addr32[0] > e->addr32[0]))
2440                         return (0);
2441                 break;
2442 #endif /* INET */
2443 #ifdef INET6
2444         case AF_INET6: {
2445                 int     i;
2446
2447                 /* check a >= b */
2448                 for (i = 0; i < 4; ++i)
2449                         if (a->addr32[i] > b->addr32[i])
2450                                 break;
2451                         else if (a->addr32[i] < b->addr32[i])
2452                                 return (0);
2453                 /* check a <= e */
2454                 for (i = 0; i < 4; ++i)
2455                         if (a->addr32[i] < e->addr32[i])
2456                                 break;
2457                         else if (a->addr32[i] > e->addr32[i])
2458                                 return (0);
2459                 break;
2460         }
2461 #endif /* INET6 */
2462         }
2463         return (1);
2464 }
2465
2466 static int
2467 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2468 {
2469         switch (op) {
2470         case PF_OP_IRG:
2471                 return ((p > a1) && (p < a2));
2472         case PF_OP_XRG:
2473                 return ((p < a1) || (p > a2));
2474         case PF_OP_RRG:
2475                 return ((p >= a1) && (p <= a2));
2476         case PF_OP_EQ:
2477                 return (p == a1);
2478         case PF_OP_NE:
2479                 return (p != a1);
2480         case PF_OP_LT:
2481                 return (p < a1);
2482         case PF_OP_LE:
2483                 return (p <= a1);
2484         case PF_OP_GT:
2485                 return (p > a1);
2486         case PF_OP_GE:
2487                 return (p >= a1);
2488         }
2489         return (0); /* never reached */
2490 }
2491
2492 int
2493 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2494 {
2495         NTOHS(a1);
2496         NTOHS(a2);
2497         NTOHS(p);
2498         return (pf_match(op, a1, a2, p));
2499 }
2500
2501 static int
2502 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2503 {
2504         if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2505                 return (0);
2506         return (pf_match(op, a1, a2, u));
2507 }
2508
2509 static int
2510 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2511 {
2512         if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2513                 return (0);
2514         return (pf_match(op, a1, a2, g));
2515 }
2516
2517 int
2518 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2519 {
2520         if (*tag == -1)
2521                 *tag = mtag;
2522
2523         return ((!r->match_tag_not && r->match_tag == *tag) ||
2524             (r->match_tag_not && r->match_tag != *tag));
2525 }
2526
2527 int
2528 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2529 {
2530
2531         KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2532
2533         if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2534                 return (ENOMEM);
2535
2536         pd->pf_mtag->tag = tag;
2537
2538         return (0);
2539 }
2540
2541 #define PF_ANCHOR_STACKSIZE     32
2542 struct pf_anchor_stackframe {
2543         struct pf_ruleset       *rs;
2544         struct pf_rule          *r;     /* XXX: + match bit */
2545         struct pf_anchor        *child;
2546 };
2547
2548 /*
2549  * XXX: We rely on malloc(9) returning pointer aligned addresses.
2550  */
2551 #define PF_ANCHORSTACK_MATCH    0x00000001
2552 #define PF_ANCHORSTACK_MASK     (PF_ANCHORSTACK_MATCH)
2553
2554 #define PF_ANCHOR_MATCH(f)      ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2555 #define PF_ANCHOR_RULE(f)       (struct pf_rule *)                      \
2556                                 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2557 #define PF_ANCHOR_SET_MATCH(f)  do { (f)->r = (void *)                  \
2558                                 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
2559 } while (0)
2560
2561 void
2562 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2563     struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2564     int *match)
2565 {
2566         struct pf_anchor_stackframe     *f;
2567
2568         PF_RULES_RASSERT();
2569
2570         if (match)
2571                 *match = 0;
2572         if (*depth >= PF_ANCHOR_STACKSIZE) {
2573                 printf("%s: anchor stack overflow on %s\n",
2574                     __func__, (*r)->anchor->name);
2575                 *r = TAILQ_NEXT(*r, entries);
2576                 return;
2577         } else if (*depth == 0 && a != NULL)
2578                 *a = *r;
2579         f = stack + (*depth)++;
2580         f->rs = *rs;
2581         f->r = *r;
2582         if ((*r)->anchor_wildcard) {
2583                 struct pf_anchor_node *parent = &(*r)->anchor->children;
2584
2585                 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2586                         *r = NULL;
2587                         return;
2588                 }
2589                 *rs = &f->child->ruleset;
2590         } else {
2591                 f->child = NULL;
2592                 *rs = &(*r)->anchor->ruleset;
2593         }
2594         *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2595 }
2596
2597 int
2598 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2599     struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2600     int *match)
2601 {
2602         struct pf_anchor_stackframe     *f;
2603         struct pf_rule *fr;
2604         int quick = 0;
2605
2606         PF_RULES_RASSERT();
2607
2608         do {
2609                 if (*depth <= 0)
2610                         break;
2611                 f = stack + *depth - 1;
2612                 fr = PF_ANCHOR_RULE(f);
2613                 if (f->child != NULL) {
2614                         struct pf_anchor_node *parent;
2615
2616                         /*
2617                          * This block traverses through
2618                          * a wildcard anchor.
2619                          */
2620                         parent = &fr->anchor->children;
2621                         if (match != NULL && *match) {
2622                                 /*
2623                                  * If any of "*" matched, then
2624                                  * "foo/ *" matched, mark frame
2625                                  * appropriately.
2626                                  */
2627                                 PF_ANCHOR_SET_MATCH(f);
2628                                 *match = 0;
2629                         }
2630                         f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2631                         if (f->child != NULL) {
2632                                 *rs = &f->child->ruleset;
2633                                 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2634                                 if (*r == NULL)
2635                                         continue;
2636                                 else
2637                                         break;
2638                         }
2639                 }
2640                 (*depth)--;
2641                 if (*depth == 0 && a != NULL)
2642                         *a = NULL;
2643                 *rs = f->rs;
2644                 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2645                         quick = fr->quick;
2646                 *r = TAILQ_NEXT(fr, entries);
2647         } while (*r == NULL);
2648
2649         return (quick);
2650 }
2651
2652 #ifdef INET6
2653 void
2654 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2655     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2656 {
2657         switch (af) {
2658 #ifdef INET
2659         case AF_INET:
2660                 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2661                 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2662                 break;
2663 #endif /* INET */
2664         case AF_INET6:
2665                 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2666                 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2667                 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2668                 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2669                 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2670                 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2671                 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2672                 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2673                 break;
2674         }
2675 }
2676
2677 void
2678 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2679 {
2680         switch (af) {
2681 #ifdef INET
2682         case AF_INET:
2683                 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2684                 break;
2685 #endif /* INET */
2686         case AF_INET6:
2687                 if (addr->addr32[3] == 0xffffffff) {
2688                         addr->addr32[3] = 0;
2689                         if (addr->addr32[2] == 0xffffffff) {
2690                                 addr->addr32[2] = 0;
2691                                 if (addr->addr32[1] == 0xffffffff) {
2692                                         addr->addr32[1] = 0;
2693                                         addr->addr32[0] =
2694                                             htonl(ntohl(addr->addr32[0]) + 1);
2695                                 } else
2696                                         addr->addr32[1] =
2697                                             htonl(ntohl(addr->addr32[1]) + 1);
2698                         } else
2699                                 addr->addr32[2] =
2700                                     htonl(ntohl(addr->addr32[2]) + 1);
2701                 } else
2702                         addr->addr32[3] =
2703                             htonl(ntohl(addr->addr32[3]) + 1);
2704                 break;
2705         }
2706 }
2707 #endif /* INET6 */
2708
2709 int
2710 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2711 {
2712         struct pf_addr          *saddr, *daddr;
2713         u_int16_t                sport, dport;
2714         struct inpcbinfo        *pi;
2715         struct inpcb            *inp;
2716
2717         pd->lookup.uid = UID_MAX;
2718         pd->lookup.gid = GID_MAX;
2719
2720         switch (pd->proto) {
2721         case IPPROTO_TCP:
2722                 if (pd->hdr.tcp == NULL)
2723                         return (-1);
2724                 sport = pd->hdr.tcp->th_sport;
2725                 dport = pd->hdr.tcp->th_dport;
2726                 pi = &V_tcbinfo;
2727                 break;
2728         case IPPROTO_UDP:
2729                 if (pd->hdr.udp == NULL)
2730                         return (-1);
2731                 sport = pd->hdr.udp->uh_sport;
2732                 dport = pd->hdr.udp->uh_dport;
2733                 pi = &V_udbinfo;
2734                 break;
2735         default:
2736                 return (-1);
2737         }
2738         if (direction == PF_IN) {
2739                 saddr = pd->src;
2740                 daddr = pd->dst;
2741         } else {
2742                 u_int16_t       p;
2743
2744                 p = sport;
2745                 sport = dport;
2746                 dport = p;
2747                 saddr = pd->dst;
2748                 daddr = pd->src;
2749         }
2750         switch (pd->af) {
2751 #ifdef INET
2752         case AF_INET:
2753                 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2754                     dport, INPLOOKUP_RLOCKPCB, NULL, m);
2755                 if (inp == NULL) {
2756                         inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2757                            daddr->v4, dport, INPLOOKUP_WILDCARD |
2758                            INPLOOKUP_RLOCKPCB, NULL, m);
2759                         if (inp == NULL)
2760                                 return (-1);
2761                 }
2762                 break;
2763 #endif /* INET */
2764 #ifdef INET6
2765         case AF_INET6:
2766                 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2767                     dport, INPLOOKUP_RLOCKPCB, NULL, m);
2768                 if (inp == NULL) {
2769                         inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2770                             &daddr->v6, dport, INPLOOKUP_WILDCARD |
2771                             INPLOOKUP_RLOCKPCB, NULL, m);
2772                         if (inp == NULL)
2773                                 return (-1);
2774                 }
2775                 break;
2776 #endif /* INET6 */
2777
2778         default:
2779                 return (-1);
2780         }
2781         INP_RLOCK_ASSERT(inp);
2782         pd->lookup.uid = inp->inp_cred->cr_uid;
2783         pd->lookup.gid = inp->inp_cred->cr_groups[0];
2784         INP_RUNLOCK(inp);
2785
2786         return (1);
2787 }
2788
2789 static u_int8_t
2790 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2791 {
2792         int              hlen;
2793         u_int8_t         hdr[60];
2794         u_int8_t        *opt, optlen;
2795         u_int8_t         wscale = 0;
2796
2797         hlen = th_off << 2;             /* hlen <= sizeof(hdr) */
2798         if (hlen <= sizeof(struct tcphdr))
2799                 return (0);
2800         if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2801                 return (0);
2802         opt = hdr + sizeof(struct tcphdr);
2803         hlen -= sizeof(struct tcphdr);
2804         while (hlen >= 3) {
2805                 switch (*opt) {
2806                 case TCPOPT_EOL:
2807                 case TCPOPT_NOP:
2808                         ++opt;
2809                         --hlen;
2810                         break;
2811                 case TCPOPT_WINDOW:
2812                         wscale = opt[2];
2813                         if (wscale > TCP_MAX_WINSHIFT)
2814                                 wscale = TCP_MAX_WINSHIFT;
2815                         wscale |= PF_WSCALE_FLAG;
2816                         /* FALLTHROUGH */
2817                 default:
2818                         optlen = opt[1];
2819                         if (optlen < 2)
2820                                 optlen = 2;
2821                         hlen -= optlen;
2822                         opt += optlen;
2823                         break;
2824                 }
2825         }
2826         return (wscale);
2827 }
2828
2829 static u_int16_t
2830 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2831 {
2832         int              hlen;
2833         u_int8_t         hdr[60];
2834         u_int8_t        *opt, optlen;
2835         u_int16_t        mss = V_tcp_mssdflt;
2836
2837         hlen = th_off << 2;     /* hlen <= sizeof(hdr) */
2838         if (hlen <= sizeof(struct tcphdr))
2839                 return (0);
2840         if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2841                 return (0);
2842         opt = hdr + sizeof(struct tcphdr);
2843         hlen -= sizeof(struct tcphdr);
2844         while (hlen >= TCPOLEN_MAXSEG) {
2845                 switch (*opt) {
2846                 case TCPOPT_EOL:
2847                 case TCPOPT_NOP:
2848                         ++opt;
2849                         --hlen;
2850                         break;
2851                 case TCPOPT_MAXSEG:
2852                         bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2853                         NTOHS(mss);
2854                         /* FALLTHROUGH */
2855                 default:
2856                         optlen = opt[1];
2857                         if (optlen < 2)
2858                                 optlen = 2;
2859                         hlen -= optlen;
2860                         opt += optlen;
2861                         break;
2862                 }
2863         }
2864         return (mss);
2865 }
2866
2867 static u_int16_t
2868 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2869 {
2870 #ifdef INET
2871         struct sockaddr_in      *dst;
2872         struct route             ro;
2873 #endif /* INET */
2874 #ifdef INET6
2875         struct sockaddr_in6     *dst6;
2876         struct route_in6         ro6;
2877 #endif /* INET6 */
2878         struct rtentry          *rt = NULL;
2879         int                      hlen = 0;
2880         u_int16_t                mss = V_tcp_mssdflt;
2881
2882         switch (af) {
2883 #ifdef INET
2884         case AF_INET:
2885                 hlen = sizeof(struct ip);
2886                 bzero(&ro, sizeof(ro));
2887                 dst = (struct sockaddr_in *)&ro.ro_dst;
2888                 dst->sin_family = AF_INET;
2889                 dst->sin_len = sizeof(*dst);
2890                 dst->sin_addr = addr->v4;
2891                 in_rtalloc_ign(&ro, 0, rtableid);
2892                 rt = ro.ro_rt;
2893                 break;
2894 #endif /* INET */
2895 #ifdef INET6
2896         case AF_INET6:
2897                 hlen = sizeof(struct ip6_hdr);
2898                 bzero(&ro6, sizeof(ro6));
2899                 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2900                 dst6->sin6_family = AF_INET6;
2901                 dst6->sin6_len = sizeof(*dst6);
2902                 dst6->sin6_addr = addr->v6;
2903                 in6_rtalloc_ign(&ro6, 0, rtableid);
2904                 rt = ro6.ro_rt;
2905                 break;
2906 #endif /* INET6 */
2907         }
2908
2909         if (rt && rt->rt_ifp) {
2910                 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2911                 mss = max(V_tcp_mssdflt, mss);
2912                 RTFREE(rt);
2913         }
2914         mss = min(mss, offer);
2915         mss = max(mss, 64);             /* sanity - at least max opt space */
2916         return (mss);
2917 }
2918
2919 static void
2920 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
2921 {
2922         struct pf_rule *r = s->rule.ptr;
2923         struct pf_src_node *sn = NULL;
2924
2925         s->rt_kif = NULL;
2926         if (!r->rt || r->rt == PF_FASTROUTE)
2927                 return;
2928         switch (s->key[PF_SK_WIRE]->af) {
2929 #ifdef INET
2930         case AF_INET:
2931                 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL, &sn);
2932                 s->rt_kif = r->rpool.cur->kif;
2933                 break;
2934 #endif /* INET */
2935 #ifdef INET6
2936         case AF_INET6:
2937                 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL, &sn);
2938                 s->rt_kif = r->rpool.cur->kif;
2939                 break;
2940 #endif /* INET6 */
2941         }
2942 }
2943
2944 static u_int32_t
2945 pf_tcp_iss(struct pf_pdesc *pd)
2946 {
2947         MD5_CTX ctx;
2948         u_int32_t digest[4];
2949
2950         if (V_pf_tcp_secret_init == 0) {
2951                 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
2952                 MD5Init(&V_pf_tcp_secret_ctx);
2953                 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
2954                     sizeof(V_pf_tcp_secret));
2955                 V_pf_tcp_secret_init = 1;
2956         }
2957
2958         ctx = V_pf_tcp_secret_ctx;
2959
2960         MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
2961         MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
2962         if (pd->af == AF_INET6) {
2963                 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
2964                 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
2965         } else {
2966                 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
2967                 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
2968         }
2969         MD5Final((u_char *)digest, &ctx);
2970         V_pf_tcp_iss_off += 4096;
2971 #define ISN_RANDOM_INCREMENT (4096 - 1)
2972         return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
2973             V_pf_tcp_iss_off);
2974 #undef  ISN_RANDOM_INCREMENT
2975 }
2976
2977 static int
2978 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
2979     struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
2980     struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
2981 {
2982         struct pf_rule          *nr = NULL;
2983         struct pf_addr          * const saddr = pd->src;
2984         struct pf_addr          * const daddr = pd->dst;
2985         sa_family_t              af = pd->af;
2986         struct pf_rule          *r, *a = NULL;
2987         struct pf_ruleset       *ruleset = NULL;
2988         struct pf_src_node      *nsn = NULL;
2989         struct tcphdr           *th = pd->hdr.tcp;
2990         struct pf_state_key     *sk = NULL, *nk = NULL;
2991         u_short                  reason;
2992         int                      rewrite = 0, hdrlen = 0;
2993         int                      tag = -1, rtableid = -1;
2994         int                      asd = 0;
2995         int                      match = 0;
2996         int                      state_icmp = 0;
2997         u_int16_t                sport = 0, dport = 0;
2998         u_int16_t                bproto_sum = 0, bip_sum = 0;
2999         u_int8_t                 icmptype = 0, icmpcode = 0;
3000         struct pf_anchor_stackframe     anchor_stack[PF_ANCHOR_STACKSIZE];
3001
3002         PF_RULES_RASSERT();
3003
3004         if (inp != NULL) {
3005                 INP_LOCK_ASSERT(inp);
3006                 pd->lookup.uid = inp->inp_cred->cr_uid;
3007                 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3008                 pd->lookup.done = 1;
3009         }
3010
3011         switch (pd->proto) {
3012         case IPPROTO_TCP:
3013                 sport = th->th_sport;
3014                 dport = th->th_dport;
3015                 hdrlen = sizeof(*th);
3016                 break;
3017         case IPPROTO_UDP:
3018                 sport = pd->hdr.udp->uh_sport;
3019                 dport = pd->hdr.udp->uh_dport;
3020                 hdrlen = sizeof(*pd->hdr.udp);
3021                 break;
3022 #ifdef INET
3023         case IPPROTO_ICMP:
3024                 if (pd->af != AF_INET)
3025                         break;
3026                 sport = dport = pd->hdr.icmp->icmp_id;
3027                 hdrlen = sizeof(*pd->hdr.icmp);
3028                 icmptype = pd->hdr.icmp->icmp_type;
3029                 icmpcode = pd->hdr.icmp->icmp_code;
3030
3031                 if (icmptype == ICMP_UNREACH ||
3032                     icmptype == ICMP_SOURCEQUENCH ||
3033                     icmptype == ICMP_REDIRECT ||
3034                     icmptype == ICMP_TIMXCEED ||
3035                     icmptype == ICMP_PARAMPROB)
3036                         state_icmp++;
3037                 break;
3038 #endif /* INET */
3039 #ifdef INET6
3040         case IPPROTO_ICMPV6:
3041                 if (af != AF_INET6)
3042                         break;
3043                 sport = dport = pd->hdr.icmp6->icmp6_id;
3044                 hdrlen = sizeof(*pd->hdr.icmp6);
3045                 icmptype = pd->hdr.icmp6->icmp6_type;
3046                 icmpcode = pd->hdr.icmp6->icmp6_code;
3047
3048                 if (icmptype == ICMP6_DST_UNREACH ||
3049                     icmptype == ICMP6_PACKET_TOO_BIG ||
3050                     icmptype == ICMP6_TIME_EXCEEDED ||
3051                     icmptype == ICMP6_PARAM_PROB)
3052                         state_icmp++;
3053                 break;
3054 #endif /* INET6 */
3055         default:
3056                 sport = dport = hdrlen = 0;
3057                 break;
3058         }
3059
3060         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3061
3062         /* check packet for BINAT/NAT/RDR */
3063         if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3064             &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3065                 KASSERT(sk != NULL, ("%s: null sk", __func__));
3066                 KASSERT(nk != NULL, ("%s: null nk", __func__));
3067
3068                 if (pd->ip_sum)
3069                         bip_sum = *pd->ip_sum;
3070
3071                 switch (pd->proto) {
3072                 case IPPROTO_TCP:
3073                         bproto_sum = th->th_sum;
3074                         pd->proto_sum = &th->th_sum;
3075
3076                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3077                             nk->port[pd->sidx] != sport) {
3078                                 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3079                                     &th->th_sum, &nk->addr[pd->sidx],
3080                                     nk->port[pd->sidx], 0, af);
3081                                 pd->sport = &th->th_sport;
3082                                 sport = th->th_sport;
3083                         }
3084
3085                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3086                             nk->port[pd->didx] != dport) {
3087                                 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3088                                     &th->th_sum, &nk->addr[pd->didx],
3089                                     nk->port[pd->didx], 0, af);
3090                                 dport = th->th_dport;
3091                                 pd->dport = &th->th_dport;
3092                         }
3093                         rewrite++;
3094                         break;
3095                 case IPPROTO_UDP:
3096                         bproto_sum = pd->hdr.udp->uh_sum;
3097                         pd->proto_sum = &pd->hdr.udp->uh_sum;
3098
3099                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3100                             nk->port[pd->sidx] != sport) {
3101                                 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3102                                     pd->ip_sum, &pd->hdr.udp->uh_sum,
3103                                     &nk->addr[pd->sidx],
3104                                     nk->port[pd->sidx], 1, af);
3105                                 sport = pd->hdr.udp->uh_sport;
3106                                 pd->sport = &pd->hdr.udp->uh_sport;
3107                         }
3108
3109                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3110                             nk->port[pd->didx] != dport) {
3111                                 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3112                                     pd->ip_sum, &pd->hdr.udp->uh_sum,
3113                                     &nk->addr[pd->didx],
3114                                     nk->port[pd->didx], 1, af);
3115                                 dport = pd->hdr.udp->uh_dport;
3116                                 pd->dport = &pd->hdr.udp->uh_dport;
3117                         }
3118                         rewrite++;
3119                         break;
3120 #ifdef INET
3121                 case IPPROTO_ICMP:
3122                         nk->port[0] = nk->port[1];
3123                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3124                                 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3125                                     nk->addr[pd->sidx].v4.s_addr, 0);
3126
3127                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3128                                 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3129                                     nk->addr[pd->didx].v4.s_addr, 0);
3130
3131                         if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3132                                 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3133                                     pd->hdr.icmp->icmp_cksum, sport,
3134                                     nk->port[1], 0);
3135                                 pd->hdr.icmp->icmp_id = nk->port[1];
3136                                 pd->sport = &pd->hdr.icmp->icmp_id;
3137                         }
3138                         m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3139                         break;
3140 #endif /* INET */
3141 #ifdef INET6
3142                 case IPPROTO_ICMPV6:
3143                         nk->port[0] = nk->port[1];
3144                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3145                                 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3146                                     &nk->addr[pd->sidx], 0);
3147
3148                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3149                                 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3150                                     &nk->addr[pd->didx], 0);
3151                         rewrite++;
3152                         break;
3153 #endif /* INET */
3154                 default:
3155                         switch (af) {
3156 #ifdef INET
3157                         case AF_INET:
3158                                 if (PF_ANEQ(saddr,
3159                                     &nk->addr[pd->sidx], AF_INET))
3160                                         pf_change_a(&saddr->v4.s_addr,
3161                                             pd->ip_sum,
3162                                             nk->addr[pd->sidx].v4.s_addr, 0);
3163
3164                                 if (PF_ANEQ(daddr,
3165                                     &nk->addr[pd->didx], AF_INET))
3166                                         pf_change_a(&daddr->v4.s_addr,
3167                                             pd->ip_sum,
3168                                             nk->addr[pd->didx].v4.s_addr, 0);
3169                                 break;
3170 #endif /* INET */
3171 #ifdef INET6
3172                         case AF_INET6:
3173                                 if (PF_ANEQ(saddr,
3174                                     &nk->addr[pd->sidx], AF_INET6))
3175                                         PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3176
3177                                 if (PF_ANEQ(daddr,
3178                                     &nk->addr[pd->didx], AF_INET6))
3179                                         PF_ACPY(saddr, &nk->addr[pd->didx], af);
3180                                 break;
3181 #endif /* INET */
3182                         }
3183                         break;
3184                 }
3185                 if (nr->natpass)
3186                         r = NULL;
3187                 pd->nat_rule = nr;
3188         }
3189
3190         while (r != NULL) {
3191                 r->evaluations++;
3192                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3193                         r = r->skip[PF_SKIP_IFP].ptr;
3194                 else if (r->direction && r->direction != direction)
3195                         r = r->skip[PF_SKIP_DIR].ptr;
3196                 else if (r->af && r->af != af)
3197                         r = r->skip[PF_SKIP_AF].ptr;
3198                 else if (r->proto && r->proto != pd->proto)
3199                         r = r->skip[PF_SKIP_PROTO].ptr;
3200                 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3201                     r->src.neg, kif, M_GETFIB(m)))
3202                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3203                 /* tcp/udp only. port_op always 0 in other cases */
3204                 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3205                     r->src.port[0], r->src.port[1], sport))
3206                         r = r->skip[PF_SKIP_SRC_PORT].ptr;
3207                 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3208                     r->dst.neg, NULL, M_GETFIB(m)))
3209                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
3210                 /* tcp/udp only. port_op always 0 in other cases */
3211                 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3212                     r->dst.port[0], r->dst.port[1], dport))
3213                         r = r->skip[PF_SKIP_DST_PORT].ptr;
3214                 /* icmp only. type always 0 in other cases */
3215                 else if (r->type && r->type != icmptype + 1)
3216                         r = TAILQ_NEXT(r, entries);
3217                 /* icmp only. type always 0 in other cases */
3218                 else if (r->code && r->code != icmpcode + 1)
3219                         r = TAILQ_NEXT(r, entries);
3220                 else if (r->tos && !(r->tos == pd->tos))
3221                         r = TAILQ_NEXT(r, entries);
3222                 else if (r->rule_flag & PFRULE_FRAGMENT)
3223                         r = TAILQ_NEXT(r, entries);
3224                 else if (pd->proto == IPPROTO_TCP &&
3225                     (r->flagset & th->th_flags) != r->flags)
3226                         r = TAILQ_NEXT(r, entries);
3227                 /* tcp/udp only. uid.op always 0 in other cases */
3228                 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3229                     pf_socket_lookup(direction, pd, m), 1)) &&
3230                     !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3231                     pd->lookup.uid))
3232                         r = TAILQ_NEXT(r, entries);
3233                 /* tcp/udp only. gid.op always 0 in other cases */
3234                 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3235                     pf_socket_lookup(direction, pd, m), 1)) &&
3236                     !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3237                     pd->lookup.gid))
3238                         r = TAILQ_NEXT(r, entries);
3239                 else if (r->prob &&
3240                     r->prob <= arc4random())
3241                         r = TAILQ_NEXT(r, entries);
3242                 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3243                     pd->pf_mtag ? pd->pf_mtag->tag : 0))
3244                         r = TAILQ_NEXT(r, entries);
3245                 else if (r->os_fingerprint != PF_OSFP_ANY &&
3246                     (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3247                     pf_osfp_fingerprint(pd, m, off, th),
3248                     r->os_fingerprint)))
3249                         r = TAILQ_NEXT(r, entries);
3250                 else {
3251                         if (r->tag)
3252                                 tag = r->tag;
3253                         if (r->rtableid >= 0)
3254                                 rtableid = r->rtableid;
3255                         if (r->anchor == NULL) {
3256                                 match = 1;
3257                                 *rm = r;
3258                                 *am = a;
3259                                 *rsm = ruleset;
3260                                 if ((*rm)->quick)
3261                                         break;
3262                                 r = TAILQ_NEXT(r, entries);
3263                         } else
3264                                 pf_step_into_anchor(anchor_stack, &asd,
3265                                     &ruleset, PF_RULESET_FILTER, &r, &a,
3266                                     &match);
3267                 }
3268                 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3269                     &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3270                         break;
3271         }
3272         r = *rm;
3273         a = *am;
3274         ruleset = *rsm;
3275
3276         REASON_SET(&reason, PFRES_MATCH);
3277
3278         if (r->log || (nr != NULL && nr->log)) {
3279                 if (rewrite)
3280                         m_copyback(m, off, hdrlen, pd->hdr.any);
3281                 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3282                     ruleset, pd, 1);
3283         }
3284
3285         if ((r->action == PF_DROP) &&
3286             ((r->rule_flag & PFRULE_RETURNRST) ||
3287             (r->rule_flag & PFRULE_RETURNICMP) ||
3288             (r->rule_flag & PFRULE_RETURN))) {
3289                 /* undo NAT changes, if they have taken place */
3290                 if (nr != NULL) {
3291                         PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3292                         PF_ACPY(daddr, &sk->addr[pd->didx], af);
3293                         if (pd->sport)
3294                                 *pd->sport = sk->port[pd->sidx];
3295                         if (pd->dport)
3296                                 *pd->dport = sk->port[pd->didx];
3297                         if (pd->proto_sum)
3298                                 *pd->proto_sum = bproto_sum;
3299                         if (pd->ip_sum)
3300                                 *pd->ip_sum = bip_sum;
3301                         m_copyback(m, off, hdrlen, pd->hdr.any);
3302                 }
3303                 if (pd->proto == IPPROTO_TCP &&
3304                     ((r->rule_flag & PFRULE_RETURNRST) ||
3305                     (r->rule_flag & PFRULE_RETURN)) &&
3306                     !(th->th_flags & TH_RST)) {
3307                         u_int32_t        ack = ntohl(th->th_seq) + pd->p_len;
3308                         int              len = 0;
3309 #ifdef INET
3310                         struct ip       *h4;
3311 #endif
3312 #ifdef INET6
3313                         struct ip6_hdr  *h6;
3314 #endif
3315
3316                         switch (af) {
3317 #ifdef INET
3318                         case AF_INET:
3319                                 h4 = mtod(m, struct ip *);
3320                                 len = ntohs(h4->ip_len) - off;
3321                                 break;
3322 #endif
3323 #ifdef INET6
3324                         case AF_INET6:
3325                                 h6 = mtod(m, struct ip6_hdr *);
3326                                 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3327                                 break;
3328 #endif
3329                         }
3330
3331                         if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3332                                 REASON_SET(&reason, PFRES_PROTCKSUM);
3333                         else {
3334                                 if (th->th_flags & TH_SYN)
3335                                         ack++;
3336                                 if (th->th_flags & TH_FIN)
3337                                         ack++;
3338                                 pf_send_tcp(m, r, af, pd->dst,
3339                                     pd->src, th->th_dport, th->th_sport,
3340                                     ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3341                                     r->return_ttl, 1, 0, kif->pfik_ifp);
3342                         }
3343                 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3344                     r->return_icmp)
3345                         pf_send_icmp(m, r->return_icmp >> 8,
3346                             r->return_icmp & 255, af, r);
3347                 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3348                     r->return_icmp6)
3349                         pf_send_icmp(m, r->return_icmp6 >> 8,
3350                             r->return_icmp6 & 255, af, r);
3351         }
3352
3353         if (r->action == PF_DROP)
3354                 goto cleanup;
3355
3356         if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3357                 REASON_SET(&reason, PFRES_MEMORY);
3358                 goto cleanup;
3359         }
3360         if (rtableid >= 0)
3361                 M_SETFIB(m, rtableid);
3362
3363         if (!state_icmp && (r->keep_state || nr != NULL ||
3364             (pd->flags & PFDESC_TCP_NORM))) {
3365                 int action;
3366                 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3367                     sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3368                     hdrlen);
3369                 if (action != PF_PASS)
3370                         return (action);
3371         } else {
3372                 if (sk != NULL)
3373                         uma_zfree(V_pf_state_key_z, sk);
3374                 if (nk != NULL)
3375                         uma_zfree(V_pf_state_key_z, nk);
3376         }
3377
3378         /* copy back packet headers if we performed NAT operations */
3379         if (rewrite)
3380                 m_copyback(m, off, hdrlen, pd->hdr.any);
3381
3382         if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3383             direction == PF_OUT &&
3384             pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3385                 /*
3386                  * We want the state created, but we dont
3387                  * want to send this in case a partner
3388                  * firewall has to know about it to allow
3389                  * replies through it.
3390                  */
3391                 return (PF_DEFER);
3392
3393         return (PF_PASS);
3394
3395 cleanup:
3396         if (sk != NULL)
3397                 uma_zfree(V_pf_state_key_z, sk);
3398         if (nk != NULL)
3399                 uma_zfree(V_pf_state_key_z, nk);
3400         return (PF_DROP);
3401 }
3402
3403 static int
3404 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3405     struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3406     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3407     u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3408     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3409 {
3410         struct pf_state         *s = NULL;
3411         struct pf_src_node      *sn = NULL;
3412         struct tcphdr           *th = pd->hdr.tcp;
3413         u_int16_t                mss = V_tcp_mssdflt;
3414         u_short                  reason;
3415
3416         /* check maximums */
3417         if (r->max_states && (r->states_cur >= r->max_states)) {
3418                 V_pf_status.lcounters[LCNT_STATES]++;
3419                 REASON_SET(&reason, PFRES_MAXSTATES);
3420                 return (PF_DROP);
3421         }
3422         /* src node for filter rule */
3423         if ((r->rule_flag & PFRULE_SRCTRACK ||
3424             r->rpool.opts & PF_POOL_STICKYADDR) &&
3425             pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3426                 REASON_SET(&reason, PFRES_SRCLIMIT);
3427                 goto csfailed;
3428         }
3429         /* src node for translation rule */
3430         if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3431             pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3432                 REASON_SET(&reason, PFRES_SRCLIMIT);
3433                 goto csfailed;
3434         }
3435         s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3436         if (s == NULL) {
3437                 REASON_SET(&reason, PFRES_MEMORY);
3438                 goto csfailed;
3439         }
3440         s->rule.ptr = r;
3441         s->nat_rule.ptr = nr;
3442         s->anchor.ptr = a;
3443         STATE_INC_COUNTERS(s);
3444         if (r->allow_opts)
3445                 s->state_flags |= PFSTATE_ALLOWOPTS;
3446         if (r->rule_flag & PFRULE_STATESLOPPY)
3447                 s->state_flags |= PFSTATE_SLOPPY;
3448         s->log = r->log & PF_LOG_ALL;
3449         s->sync_state = PFSYNC_S_NONE;
3450         if (nr != NULL)
3451                 s->log |= nr->log & PF_LOG_ALL;
3452         switch (pd->proto) {
3453         case IPPROTO_TCP:
3454                 s->src.seqlo = ntohl(th->th_seq);
3455                 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3456                 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3457                     r->keep_state == PF_STATE_MODULATE) {
3458                         /* Generate sequence number modulator */
3459                         if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3460                             0)
3461                                 s->src.seqdiff = 1;
3462                         pf_change_a(&th->th_seq, &th->th_sum,
3463                             htonl(s->src.seqlo + s->src.seqdiff), 0);
3464                         *rewrite = 1;
3465                 } else
3466                         s->src.seqdiff = 0;
3467                 if (th->th_flags & TH_SYN) {
3468                         s->src.seqhi++;
3469                         s->src.wscale = pf_get_wscale(m, off,
3470                             th->th_off, pd->af);
3471                 }
3472                 s->src.max_win = MAX(ntohs(th->th_win), 1);
3473                 if (s->src.wscale & PF_WSCALE_MASK) {
3474                         /* Remove scale factor from initial window */
3475                         int win = s->src.max_win;
3476                         win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3477                         s->src.max_win = (win - 1) >>
3478                             (s->src.wscale & PF_WSCALE_MASK);
3479                 }
3480                 if (th->th_flags & TH_FIN)
3481                         s->src.seqhi++;
3482                 s->dst.seqhi = 1;
3483                 s->dst.max_win = 1;
3484                 s->src.state = TCPS_SYN_SENT;
3485                 s->dst.state = TCPS_CLOSED;
3486                 s->timeout = PFTM_TCP_FIRST_PACKET;
3487                 break;
3488         case IPPROTO_UDP:
3489                 s->src.state = PFUDPS_SINGLE;
3490                 s->dst.state = PFUDPS_NO_TRAFFIC;
3491                 s->timeout = PFTM_UDP_FIRST_PACKET;
3492                 break;
3493         case IPPROTO_ICMP:
3494 #ifdef INET6
3495         case IPPROTO_ICMPV6:
3496 #endif
3497                 s->timeout = PFTM_ICMP_FIRST_PACKET;
3498                 break;
3499         default:
3500                 s->src.state = PFOTHERS_SINGLE;
3501                 s->dst.state = PFOTHERS_NO_TRAFFIC;
3502                 s->timeout = PFTM_OTHER_FIRST_PACKET;
3503         }
3504
3505         s->creation = time_uptime;
3506         s->expire = time_uptime;
3507
3508         if (sn != NULL) {
3509                 s->src_node = sn;
3510                 s->src_node->states++;
3511         }
3512         if (nsn != NULL) {
3513                 /* XXX We only modify one side for now. */
3514                 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3515                 s->nat_src_node = nsn;
3516                 s->nat_src_node->states++;
3517         }
3518         if (pd->proto == IPPROTO_TCP) {
3519                 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3520                     off, pd, th, &s->src, &s->dst)) {
3521                         REASON_SET(&reason, PFRES_MEMORY);
3522                         pf_src_tree_remove_state(s);
3523                         STATE_DEC_COUNTERS(s);
3524                         uma_zfree(V_pf_state_z, s);
3525                         return (PF_DROP);
3526                 }
3527                 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3528                     pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3529                     &s->src, &s->dst, rewrite)) {
3530                         /* This really shouldn't happen!!! */
3531                         DPFPRINTF(PF_DEBUG_URGENT,
3532                             ("pf_normalize_tcp_stateful failed on first pkt"));
3533                         pf_normalize_tcp_cleanup(s);
3534                         pf_src_tree_remove_state(s);
3535                         STATE_DEC_COUNTERS(s);
3536                         uma_zfree(V_pf_state_z, s);
3537                         return (PF_DROP);
3538                 }
3539         }
3540         s->direction = pd->dir;
3541
3542         /*
3543          * sk/nk could already been setup by pf_get_translation().
3544          */
3545         if (nr == NULL) {
3546                 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3547                     __func__, nr, sk, nk));
3548                 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3549                 if (sk == NULL)
3550                         goto csfailed;
3551                 nk = sk;
3552         } else
3553                 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3554                     __func__, nr, sk, nk));
3555
3556         /* Swap sk/nk for PF_OUT. */
3557         if (pf_state_insert(BOUND_IFACE(r, kif),
3558             (pd->dir == PF_IN) ? sk : nk,
3559             (pd->dir == PF_IN) ? nk : sk, s)) {
3560                 if (pd->proto == IPPROTO_TCP)
3561                         pf_normalize_tcp_cleanup(s);
3562                 REASON_SET(&reason, PFRES_STATEINS);
3563                 pf_src_tree_remove_state(s);
3564                 STATE_DEC_COUNTERS(s);
3565                 uma_zfree(V_pf_state_z, s);
3566                 return (PF_DROP);
3567         } else
3568                 *sm = s;
3569
3570         pf_set_rt_ifp(s, pd->src);      /* needs s->state_key set */
3571         if (tag > 0)
3572                 s->tag = tag;
3573         if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3574             TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3575                 s->src.state = PF_TCPS_PROXY_SRC;
3576                 /* undo NAT changes, if they have taken place */
3577                 if (nr != NULL) {
3578                         struct pf_state_key *skt = s->key[PF_SK_WIRE];
3579                         if (pd->dir == PF_OUT)
3580                                 skt = s->key[PF_SK_STACK];
3581                         PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3582                         PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3583                         if (pd->sport)
3584                                 *pd->sport = skt->port[pd->sidx];
3585                         if (pd->dport)
3586                                 *pd->dport = skt->port[pd->didx];
3587                         if (pd->proto_sum)
3588                                 *pd->proto_sum = bproto_sum;
3589                         if (pd->ip_sum)
3590                                 *pd->ip_sum = bip_sum;
3591                         m_copyback(m, off, hdrlen, pd->hdr.any);
3592                 }
3593                 s->src.seqhi = htonl(arc4random());
3594                 /* Find mss option */
3595                 int rtid = M_GETFIB(m);
3596                 mss = pf_get_mss(m, off, th->th_off, pd->af);
3597                 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3598                 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3599                 s->src.mss = mss;
3600                 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3601                     th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3602                     TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3603                 REASON_SET(&reason, PFRES_SYNPROXY);
3604                 return (PF_SYNPROXY_DROP);
3605         }
3606
3607         return (PF_PASS);
3608
3609 csfailed:
3610         if (sk != NULL)
3611                 uma_zfree(V_pf_state_key_z, sk);
3612         if (nk != NULL)
3613                 uma_zfree(V_pf_state_key_z, nk);
3614
3615         if (sn != NULL && sn->states == 0 && sn->expire == 0)
3616                 pf_remove_src_node(sn);
3617
3618         if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0)
3619                 pf_remove_src_node(nsn);
3620
3621         return (PF_DROP);
3622 }
3623
3624 static int
3625 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3626     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3627     struct pf_ruleset **rsm)
3628 {
3629         struct pf_rule          *r, *a = NULL;
3630         struct pf_ruleset       *ruleset = NULL;
3631         sa_family_t              af = pd->af;
3632         u_short                  reason;
3633         int                      tag = -1;
3634         int                      asd = 0;
3635         int                      match = 0;
3636         struct pf_anchor_stackframe     anchor_stack[PF_ANCHOR_STACKSIZE];
3637
3638         PF_RULES_RASSERT();
3639
3640         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3641         while (r != NULL) {
3642                 r->evaluations++;
3643                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3644                         r = r->skip[PF_SKIP_IFP].ptr;
3645                 else if (r->direction && r->direction != direction)
3646                         r = r->skip[PF_SKIP_DIR].ptr;
3647                 else if (r->af && r->af != af)
3648                         r = r->skip[PF_SKIP_AF].ptr;
3649                 else if (r->proto && r->proto != pd->proto)
3650                         r = r->skip[PF_SKIP_PROTO].ptr;
3651                 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3652                     r->src.neg, kif, M_GETFIB(m)))
3653                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3654                 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3655                     r->dst.neg, NULL, M_GETFIB(m)))
3656                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
3657                 else if (r->tos && !(r->tos == pd->tos))
3658                         r = TAILQ_NEXT(r, entries);
3659                 else if (r->os_fingerprint != PF_OSFP_ANY)
3660                         r = TAILQ_NEXT(r, entries);
3661                 else if (pd->proto == IPPROTO_UDP &&
3662                     (r->src.port_op || r->dst.port_op))
3663                         r = TAILQ_NEXT(r, entries);
3664                 else if (pd->proto == IPPROTO_TCP &&
3665                     (r->src.port_op || r->dst.port_op || r->flagset))
3666                         r = TAILQ_NEXT(r, entries);
3667                 else if ((pd->proto == IPPROTO_ICMP ||
3668                     pd->proto == IPPROTO_ICMPV6) &&
3669                     (r->type || r->code))
3670                         r = TAILQ_NEXT(r, entries);
3671                 else if (r->prob && r->prob <=
3672                     (arc4random() % (UINT_MAX - 1) + 1))
3673                         r = TAILQ_NEXT(r, entries);
3674                 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3675                     pd->pf_mtag ? pd->pf_mtag->tag : 0))
3676                         r = TAILQ_NEXT(r, entries);
3677                 else {
3678                         if (r->anchor == NULL) {
3679                                 match = 1;
3680                                 *rm = r;
3681                                 *am = a;
3682                                 *rsm = ruleset;
3683                                 if ((*rm)->quick)
3684                                         break;
3685                                 r = TAILQ_NEXT(r, entries);
3686                         } else
3687                                 pf_step_into_anchor(anchor_stack, &asd,
3688                                     &ruleset, PF_RULESET_FILTER, &r, &a,
3689                                     &match);
3690                 }
3691                 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3692                     &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3693                         break;
3694         }
3695         r = *rm;
3696         a = *am;
3697         ruleset = *rsm;
3698
3699         REASON_SET(&reason, PFRES_MATCH);
3700
3701         if (r->log)
3702                 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3703                     1);
3704
3705         if (r->action != PF_PASS)
3706                 return (PF_DROP);
3707
3708         if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3709                 REASON_SET(&reason, PFRES_MEMORY);
3710                 return (PF_DROP);
3711         }
3712
3713         return (PF_PASS);
3714 }
3715
3716 static int
3717 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3718         struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3719         struct pf_pdesc *pd, u_short *reason, int *copyback)
3720 {
3721         struct tcphdr           *th = pd->hdr.tcp;
3722         u_int16_t                win = ntohs(th->th_win);
3723         u_int32_t                ack, end, seq, orig_seq;
3724         u_int8_t                 sws, dws;
3725         int                      ackskew;
3726
3727         if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3728                 sws = src->wscale & PF_WSCALE_MASK;
3729                 dws = dst->wscale & PF_WSCALE_MASK;
3730         } else
3731                 sws = dws = 0;
3732
3733         /*
3734          * Sequence tracking algorithm from Guido van Rooij's paper:
3735          *   http://www.madison-gurkha.com/publications/tcp_filtering/
3736          *      tcp_filtering.ps
3737          */
3738
3739         orig_seq = seq = ntohl(th->th_seq);
3740         if (src->seqlo == 0) {
3741                 /* First packet from this end. Set its state */
3742
3743                 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3744                     src->scrub == NULL) {
3745                         if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3746                                 REASON_SET(reason, PFRES_MEMORY);
3747                                 return (PF_DROP);
3748                         }
3749                 }
3750
3751                 /* Deferred generation of sequence number modulator */
3752                 if (dst->seqdiff && !src->seqdiff) {
3753                         /* use random iss for the TCP server */
3754                         while ((src->seqdiff = arc4random() - seq) == 0)
3755                                 ;
3756                         ack = ntohl(th->th_ack) - dst->seqdiff;
3757                         pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3758                             src->seqdiff), 0);
3759                         pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3760                         *copyback = 1;
3761                 } else {
3762                         ack = ntohl(th->th_ack);
3763                 }
3764
3765                 end = seq + pd->p_len;
3766                 if (th->th_flags & TH_SYN) {
3767                         end++;
3768                         if (dst->wscale & PF_WSCALE_FLAG) {
3769                                 src->wscale = pf_get_wscale(m, off, th->th_off,
3770                                     pd->af);
3771                                 if (src->wscale & PF_WSCALE_FLAG) {
3772                                         /* Remove scale factor from initial
3773                                          * window */
3774                                         sws = src->wscale & PF_WSCALE_MASK;
3775                                         win = ((u_int32_t)win + (1 << sws) - 1)
3776                                             >> sws;
3777                                         dws = dst->wscale & PF_WSCALE_MASK;
3778                                 } else {
3779                                         /* fixup other window */
3780                                         dst->max_win <<= dst->wscale &
3781                                             PF_WSCALE_MASK;
3782                                         /* in case of a retrans SYN|ACK */
3783                                         dst->wscale = 0;
3784                                 }
3785                         }
3786                 }
3787                 if (th->th_flags & TH_FIN)
3788                         end++;
3789
3790                 src->seqlo = seq;
3791                 if (src->state < TCPS_SYN_SENT)
3792                         src->state = TCPS_SYN_SENT;
3793
3794                 /*
3795                  * May need to slide the window (seqhi may have been set by
3796                  * the crappy stack check or if we picked up the connection
3797                  * after establishment)
3798                  */
3799                 if (src->seqhi == 1 ||
3800                     SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3801                         src->seqhi = end + MAX(1, dst->max_win << dws);
3802                 if (win > src->max_win)
3803                         src->max_win = win;
3804
3805         } else {
3806                 ack = ntohl(th->th_ack) - dst->seqdiff;
3807                 if (src->seqdiff) {
3808                         /* Modulate sequence numbers */
3809                         pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3810                             src->seqdiff), 0);
3811                         pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3812                         *copyback = 1;
3813                 }
3814                 end = seq + pd->p_len;
3815                 if (th->th_flags & TH_SYN)
3816                         end++;
3817                 if (th->th_flags & TH_FIN)
3818                         end++;
3819         }
3820
3821         if ((th->th_flags & TH_ACK) == 0) {
3822                 /* Let it pass through the ack skew check */
3823                 ack = dst->seqlo;
3824         } else if ((ack == 0 &&
3825             (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3826             /* broken tcp stacks do not set ack */
3827             (dst->state < TCPS_SYN_SENT)) {
3828                 /*
3829                  * Many stacks (ours included) will set the ACK number in an
3830                  * FIN|ACK if the SYN times out -- no sequence to ACK.
3831                  */
3832                 ack = dst->seqlo;
3833         }
3834
3835         if (seq == end) {
3836                 /* Ease sequencing restrictions on no data packets */
3837                 seq = src->seqlo;
3838                 end = seq;
3839         }
3840
3841         ackskew = dst->seqlo - ack;
3842
3843
3844         /*
3845          * Need to demodulate the sequence numbers in any TCP SACK options
3846          * (Selective ACK). We could optionally validate the SACK values
3847          * against the current ACK window, either forwards or backwards, but
3848          * I'm not confident that SACK has been implemented properly
3849          * everywhere. It wouldn't surprise me if several stacks accidently
3850          * SACK too far backwards of previously ACKed data. There really aren't
3851          * any security implications of bad SACKing unless the target stack
3852          * doesn't validate the option length correctly. Someone trying to
3853          * spoof into a TCP connection won't bother blindly sending SACK
3854          * options anyway.
3855          */
3856         if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3857                 if (pf_modulate_sack(m, off, pd, th, dst))
3858                         *copyback = 1;
3859         }
3860
3861
3862 #define MAXACKWINDOW (0xffff + 1500)    /* 1500 is an arbitrary fudge factor */
3863         if (SEQ_GEQ(src->seqhi, end) &&
3864             /* Last octet inside other's window space */
3865             SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3866             /* Retrans: not more than one window back */
3867             (ackskew >= -MAXACKWINDOW) &&
3868             /* Acking not more than one reassembled fragment backwards */
3869             (ackskew <= (MAXACKWINDOW << sws)) &&
3870             /* Acking not more than one window forward */
3871             ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3872             (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3873             (pd->flags & PFDESC_IP_REAS) == 0)) {
3874             /* Require an exact/+1 sequence match on resets when possible */
3875
3876                 if (dst->scrub || src->scrub) {
3877                         if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3878                             *state, src, dst, copyback))
3879                                 return (PF_DROP);
3880                 }
3881
3882                 /* update max window */
3883                 if (src->max_win < win)
3884                         src->max_win = win;
3885                 /* synchronize sequencing */
3886                 if (SEQ_GT(end, src->seqlo))
3887                         src->seqlo = end;
3888                 /* slide the window of what the other end can send */
3889                 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3890                         dst->seqhi = ack + MAX((win << sws), 1);
3891
3892
3893                 /* update states */
3894                 if (th->th_flags & TH_SYN)
3895                         if (src->state < TCPS_SYN_SENT)
3896                                 src->state = TCPS_SYN_SENT;
3897                 if (th->th_flags & TH_FIN)
3898                         if (src->state < TCPS_CLOSING)
3899                                 src->state = TCPS_CLOSING;
3900                 if (th->th_flags & TH_ACK) {
3901                         if (dst->state == TCPS_SYN_SENT) {
3902                                 dst->state = TCPS_ESTABLISHED;
3903                                 if (src->state == TCPS_ESTABLISHED &&
3904                                     (*state)->src_node != NULL &&
3905                                     pf_src_connlimit(state)) {
3906                                         REASON_SET(reason, PFRES_SRCLIMIT);
3907                                         return (PF_DROP);
3908                                 }
3909                         } else if (dst->state == TCPS_CLOSING)
3910                                 dst->state = TCPS_FIN_WAIT_2;
3911                 }
3912                 if (th->th_flags & TH_RST)
3913                         src->state = dst->state = TCPS_TIME_WAIT;
3914
3915                 /* update expire time */
3916                 (*state)->expire = time_uptime;
3917                 if (src->state >= TCPS_FIN_WAIT_2 &&
3918                     dst->state >= TCPS_FIN_WAIT_2)
3919                         (*state)->timeout = PFTM_TCP_CLOSED;
3920                 else if (src->state >= TCPS_CLOSING &&
3921                     dst->state >= TCPS_CLOSING)
3922                         (*state)->timeout = PFTM_TCP_FIN_WAIT;
3923                 else if (src->state < TCPS_ESTABLISHED ||
3924                     dst->state < TCPS_ESTABLISHED)
3925                         (*state)->timeout = PFTM_TCP_OPENING;
3926                 else if (src->state >= TCPS_CLOSING ||
3927                     dst->state >= TCPS_CLOSING)
3928                         (*state)->timeout = PFTM_TCP_CLOSING;
3929                 else
3930                         (*state)->timeout = PFTM_TCP_ESTABLISHED;
3931
3932                 /* Fall through to PASS packet */
3933
3934         } else if ((dst->state < TCPS_SYN_SENT ||
3935                 dst->state >= TCPS_FIN_WAIT_2 ||
3936                 src->state >= TCPS_FIN_WAIT_2) &&
3937             SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
3938             /* Within a window forward of the originating packet */
3939             SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
3940             /* Within a window backward of the originating packet */
3941
3942                 /*
3943                  * This currently handles three situations:
3944                  *  1) Stupid stacks will shotgun SYNs before their peer
3945                  *     replies.
3946                  *  2) When PF catches an already established stream (the
3947                  *     firewall rebooted, the state table was flushed, routes
3948                  *     changed...)
3949                  *  3) Packets get funky immediately after the connection
3950                  *     closes (this should catch Solaris spurious ACK|FINs
3951                  *     that web servers like to spew after a close)
3952                  *
3953                  * This must be a little more careful than the above code
3954                  * since packet floods will also be caught here. We don't
3955                  * update the TTL here to mitigate the damage of a packet
3956                  * flood and so the same code can handle awkward establishment
3957                  * and a loosened connection close.
3958                  * In the establishment case, a correct peer response will
3959                  * validate the connection, go through the normal state code
3960                  * and keep updating the state TTL.
3961                  */
3962
3963                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
3964                         printf("pf: loose state match: ");
3965                         pf_print_state(*state);
3966                         pf_print_flags(th->th_flags);
3967                         printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
3968                             "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
3969                             pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
3970                             (unsigned long long)(*state)->packets[1],
3971                             pd->dir == PF_IN ? "in" : "out",
3972                             pd->dir == (*state)->direction ? "fwd" : "rev");
3973                 }
3974
3975                 if (dst->scrub || src->scrub) {
3976                         if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3977                             *state, src, dst, copyback))
3978                                 return (PF_DROP);
3979                 }
3980
3981                 /* update max window */
3982                 if (src->max_win < win)
3983                         src->max_win = win;
3984                 /* synchronize sequencing */
3985                 if (SEQ_GT(end, src->seqlo))
3986                         src->seqlo = end;
3987                 /* slide the window of what the other end can send */
3988                 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3989                         dst->seqhi = ack + MAX((win << sws), 1);
3990
3991                 /*
3992                  * Cannot set dst->seqhi here since this could be a shotgunned
3993                  * SYN and not an already established connection.
3994                  */
3995
3996                 if (th->th_flags & TH_FIN)
3997                         if (src->state < TCPS_CLOSING)
3998                                 src->state = TCPS_CLOSING;
3999                 if (th->th_flags & TH_RST)
4000                         src->state = dst->state = TCPS_TIME_WAIT;
4001
4002                 /* Fall through to PASS packet */
4003
4004         } else {
4005                 if ((*state)->dst.state == TCPS_SYN_SENT &&
4006                     (*state)->src.state == TCPS_SYN_SENT) {
4007                         /* Send RST for state mismatches during handshake */
4008                         if (!(th->th_flags & TH_RST))
4009                                 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4010                                     pd->dst, pd->src, th->th_dport,
4011                                     th->th_sport, ntohl(th->th_ack), 0,
4012                                     TH_RST, 0, 0,
4013                                     (*state)->rule.ptr->return_ttl, 1, 0,
4014                                     kif->pfik_ifp);
4015                         src->seqlo = 0;
4016                         src->seqhi = 1;
4017                         src->max_win = 1;
4018                 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4019                         printf("pf: BAD state: ");
4020                         pf_print_state(*state);
4021                         pf_print_flags(th->th_flags);
4022                         printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4023                             "pkts=%llu:%llu dir=%s,%s\n",
4024                             seq, orig_seq, ack, pd->p_len, ackskew,
4025                             (unsigned long long)(*state)->packets[0],
4026                             (unsigned long long)(*state)->packets[1],
4027                             pd->dir == PF_IN ? "in" : "out",
4028                             pd->dir == (*state)->direction ? "fwd" : "rev");
4029                         printf("pf: State failure on: %c %c %c %c | %c %c\n",
4030                             SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4031                             SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4032                             ' ': '2',
4033                             (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4034                             (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4035                             SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4036                             SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4037                 }
4038                 REASON_SET(reason, PFRES_BADSTATE);
4039                 return (PF_DROP);
4040         }
4041
4042         return (PF_PASS);
4043 }
4044
4045 static int
4046 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4047         struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4048 {
4049         struct tcphdr           *th = pd->hdr.tcp;
4050
4051         if (th->th_flags & TH_SYN)
4052                 if (src->state < TCPS_SYN_SENT)
4053                         src->state = TCPS_SYN_SENT;
4054         if (th->th_flags & TH_FIN)
4055                 if (src->state < TCPS_CLOSING)
4056                         src->state = TCPS_CLOSING;
4057         if (th->th_flags & TH_ACK) {
4058                 if (dst->state == TCPS_SYN_SENT) {
4059                         dst->state = TCPS_ESTABLISHED;
4060                         if (src->state == TCPS_ESTABLISHED &&
4061                             (*state)->src_node != NULL &&
4062                             pf_src_connlimit(state)) {
4063                                 REASON_SET(reason, PFRES_SRCLIMIT);
4064                                 return (PF_DROP);
4065                         }
4066                 } else if (dst->state == TCPS_CLOSING) {
4067                         dst->state = TCPS_FIN_WAIT_2;
4068                 } else if (src->state == TCPS_SYN_SENT &&
4069                     dst->state < TCPS_SYN_SENT) {
4070                         /*
4071                          * Handle a special sloppy case where we only see one
4072                          * half of the connection. If there is a ACK after
4073                          * the initial SYN without ever seeing a packet from
4074                          * the destination, set the connection to established.
4075                          */
4076                         dst->state = src->state = TCPS_ESTABLISHED;
4077                         if ((*state)->src_node != NULL &&
4078                             pf_src_connlimit(state)) {
4079                                 REASON_SET(reason, PFRES_SRCLIMIT);
4080                                 return (PF_DROP);
4081                         }
4082                 } else if (src->state == TCPS_CLOSING &&
4083                     dst->state == TCPS_ESTABLISHED &&
4084                     dst->seqlo == 0) {
4085                         /*
4086                          * Handle the closing of half connections where we
4087                          * don't see the full bidirectional FIN/ACK+ACK
4088                          * handshake.
4089                          */
4090                         dst->state = TCPS_CLOSING;
4091                 }
4092         }
4093         if (th->th_flags & TH_RST)
4094                 src->state = dst->state = TCPS_TIME_WAIT;
4095
4096         /* update expire time */
4097         (*state)->expire = time_uptime;
4098         if (src->state >= TCPS_FIN_WAIT_2 &&
4099             dst->state >= TCPS_FIN_WAIT_2)
4100                 (*state)->timeout = PFTM_TCP_CLOSED;
4101         else if (src->state >= TCPS_CLOSING &&
4102             dst->state >= TCPS_CLOSING)
4103                 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4104         else if (src->state < TCPS_ESTABLISHED ||
4105             dst->state < TCPS_ESTABLISHED)
4106                 (*state)->timeout = PFTM_TCP_OPENING;
4107         else if (src->state >= TCPS_CLOSING ||
4108             dst->state >= TCPS_CLOSING)
4109                 (*state)->timeout = PFTM_TCP_CLOSING;
4110         else
4111                 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4112
4113         return (PF_PASS);
4114 }
4115
4116 static int
4117 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4118     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4119     u_short *reason)
4120 {
4121         struct pf_state_key_cmp  key;
4122         struct tcphdr           *th = pd->hdr.tcp;
4123         int                      copyback = 0;
4124         struct pf_state_peer    *src, *dst;
4125         struct pf_state_key     *sk;
4126
4127         bzero(&key, sizeof(key));
4128         key.af = pd->af;
4129         key.proto = IPPROTO_TCP;
4130         if (direction == PF_IN) {       /* wire side, straight */
4131                 PF_ACPY(&key.addr[0], pd->src, key.af);
4132                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4133                 key.port[0] = th->th_sport;
4134                 key.port[1] = th->th_dport;
4135         } else {                        /* stack side, reverse */
4136                 PF_ACPY(&key.addr[1], pd->src, key.af);
4137                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4138                 key.port[1] = th->th_sport;
4139                 key.port[0] = th->th_dport;
4140         }
4141
4142         STATE_LOOKUP(kif, &key, direction, *state, pd);
4143
4144         if (direction == (*state)->direction) {
4145                 src = &(*state)->src;
4146                 dst = &(*state)->dst;
4147         } else {
4148                 src = &(*state)->dst;
4149                 dst = &(*state)->src;
4150         }
4151
4152         sk = (*state)->key[pd->didx];
4153
4154         if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4155                 if (direction != (*state)->direction) {
4156                         REASON_SET(reason, PFRES_SYNPROXY);
4157                         return (PF_SYNPROXY_DROP);
4158                 }
4159                 if (th->th_flags & TH_SYN) {
4160                         if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4161                                 REASON_SET(reason, PFRES_SYNPROXY);
4162                                 return (PF_DROP);
4163                         }
4164                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4165                             pd->src, th->th_dport, th->th_sport,
4166                             (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4167                             TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4168                         REASON_SET(reason, PFRES_SYNPROXY);
4169                         return (PF_SYNPROXY_DROP);
4170                 } else if (!(th->th_flags & TH_ACK) ||
4171                     (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4172                     (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4173                         REASON_SET(reason, PFRES_SYNPROXY);
4174                         return (PF_DROP);
4175                 } else if ((*state)->src_node != NULL &&
4176                     pf_src_connlimit(state)) {
4177                         REASON_SET(reason, PFRES_SRCLIMIT);
4178                         return (PF_DROP);
4179                 } else
4180                         (*state)->src.state = PF_TCPS_PROXY_DST;
4181         }
4182         if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4183                 if (direction == (*state)->direction) {
4184                         if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4185                             (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4186                             (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4187                                 REASON_SET(reason, PFRES_SYNPROXY);
4188                                 return (PF_DROP);
4189                         }
4190                         (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4191                         if ((*state)->dst.seqhi == 1)
4192                                 (*state)->dst.seqhi = htonl(arc4random());
4193                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4194                             &sk->addr[pd->sidx], &sk->addr[pd->didx],
4195                             sk->port[pd->sidx], sk->port[pd->didx],
4196                             (*state)->dst.seqhi, 0, TH_SYN, 0,
4197                             (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4198                         REASON_SET(reason, PFRES_SYNPROXY);
4199                         return (PF_SYNPROXY_DROP);
4200                 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4201                     (TH_SYN|TH_ACK)) ||
4202                     (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4203                         REASON_SET(reason, PFRES_SYNPROXY);
4204                         return (PF_DROP);
4205                 } else {
4206                         (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4207                         (*state)->dst.seqlo = ntohl(th->th_seq);
4208                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4209                             pd->src, th->th_dport, th->th_sport,
4210                             ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4211                             TH_ACK, (*state)->src.max_win, 0, 0, 0,
4212                             (*state)->tag, NULL);
4213                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4214                             &sk->addr[pd->sidx], &sk->addr[pd->didx],
4215                             sk->port[pd->sidx], sk->port[pd->didx],
4216                             (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4217                             TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4218                         (*state)->src.seqdiff = (*state)->dst.seqhi -
4219                             (*state)->src.seqlo;
4220                         (*state)->dst.seqdiff = (*state)->src.seqhi -
4221                             (*state)->dst.seqlo;
4222                         (*state)->src.seqhi = (*state)->src.seqlo +
4223                             (*state)->dst.max_win;
4224                         (*state)->dst.seqhi = (*state)->dst.seqlo +
4225                             (*state)->src.max_win;
4226                         (*state)->src.wscale = (*state)->dst.wscale = 0;
4227                         (*state)->src.state = (*state)->dst.state =
4228                             TCPS_ESTABLISHED;
4229                         REASON_SET(reason, PFRES_SYNPROXY);
4230                         return (PF_SYNPROXY_DROP);
4231                 }
4232         }
4233
4234         if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4235             dst->state >= TCPS_FIN_WAIT_2 &&
4236             src->state >= TCPS_FIN_WAIT_2) {
4237                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4238                         printf("pf: state reuse ");
4239                         pf_print_state(*state);
4240                         pf_print_flags(th->th_flags);
4241                         printf("\n");
4242                 }
4243                 /* XXX make sure it's the same direction ?? */
4244                 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4245                 pf_unlink_state(*state, PF_ENTER_LOCKED);
4246                 *state = NULL;
4247                 return (PF_DROP);
4248         }
4249
4250         if ((*state)->state_flags & PFSTATE_SLOPPY) {
4251                 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4252                         return (PF_DROP);
4253         } else {
4254                 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4255                     &copyback) == PF_DROP)
4256                         return (PF_DROP);
4257         }
4258
4259         /* translate source/destination address, if necessary */
4260         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4261                 struct pf_state_key *nk = (*state)->key[pd->didx];
4262
4263                 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4264                     nk->port[pd->sidx] != th->th_sport)
4265                         pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4266                             &th->th_sum, &nk->addr[pd->sidx],
4267                             nk->port[pd->sidx], 0, pd->af);
4268
4269                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4270                     nk->port[pd->didx] != th->th_dport)
4271                         pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4272                             &th->th_sum, &nk->addr[pd->didx],
4273                             nk->port[pd->didx], 0, pd->af);
4274                 copyback = 1;
4275         }
4276
4277         /* Copyback sequence modulation or stateful scrub changes if needed */
4278         if (copyback)
4279                 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4280
4281         return (PF_PASS);
4282 }
4283
4284 static int
4285 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4286     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4287 {
4288         struct pf_state_peer    *src, *dst;
4289         struct pf_state_key_cmp  key;
4290         struct udphdr           *uh = pd->hdr.udp;
4291
4292         bzero(&key, sizeof(key));
4293         key.af = pd->af;
4294         key.proto = IPPROTO_UDP;
4295         if (direction == PF_IN) {       /* wire side, straight */
4296                 PF_ACPY(&key.addr[0], pd->src, key.af);
4297                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4298                 key.port[0] = uh->uh_sport;
4299                 key.port[1] = uh->uh_dport;
4300         } else {                        /* stack side, reverse */
4301                 PF_ACPY(&key.addr[1], pd->src, key.af);
4302                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4303                 key.port[1] = uh->uh_sport;
4304                 key.port[0] = uh->uh_dport;
4305         }
4306
4307         STATE_LOOKUP(kif, &key, direction, *state, pd);
4308
4309         if (direction == (*state)->direction) {
4310                 src = &(*state)->src;
4311                 dst = &(*state)->dst;
4312         } else {
4313                 src = &(*state)->dst;
4314                 dst = &(*state)->src;
4315         }
4316
4317         /* update states */
4318         if (src->state < PFUDPS_SINGLE)
4319                 src->state = PFUDPS_SINGLE;
4320         if (dst->state == PFUDPS_SINGLE)
4321                 dst->state = PFUDPS_MULTIPLE;
4322
4323         /* update expire time */
4324         (*state)->expire = time_uptime;
4325         if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4326                 (*state)->timeout = PFTM_UDP_MULTIPLE;
4327         else
4328                 (*state)->timeout = PFTM_UDP_SINGLE;
4329
4330         /* translate source/destination address, if necessary */
4331         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4332                 struct pf_state_key *nk = (*state)->key[pd->didx];
4333
4334                 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4335                     nk->port[pd->sidx] != uh->uh_sport)
4336                         pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4337                             &uh->uh_sum, &nk->addr[pd->sidx],
4338                             nk->port[pd->sidx], 1, pd->af);
4339
4340                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4341                     nk->port[pd->didx] != uh->uh_dport)
4342                         pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4343                             &uh->uh_sum, &nk->addr[pd->didx],
4344                             nk->port[pd->didx], 1, pd->af);
4345                 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4346         }
4347
4348         return (PF_PASS);
4349 }
4350
4351 static int
4352 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4353     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4354 {
4355         struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
4356         u_int16_t        icmpid = 0, *icmpsum;
4357         u_int8_t         icmptype;
4358         int              state_icmp = 0;
4359         struct pf_state_key_cmp key;
4360
4361         bzero(&key, sizeof(key));
4362         switch (pd->proto) {
4363 #ifdef INET
4364         case IPPROTO_ICMP:
4365                 icmptype = pd->hdr.icmp->icmp_type;
4366                 icmpid = pd->hdr.icmp->icmp_id;
4367                 icmpsum = &pd->hdr.icmp->icmp_cksum;
4368
4369                 if (icmptype == ICMP_UNREACH ||
4370                     icmptype == ICMP_SOURCEQUENCH ||
4371                     icmptype == ICMP_REDIRECT ||
4372                     icmptype == ICMP_TIMXCEED ||
4373                     icmptype == ICMP_PARAMPROB)
4374                         state_icmp++;
4375                 break;
4376 #endif /* INET */
4377 #ifdef INET6
4378         case IPPROTO_ICMPV6:
4379                 icmptype = pd->hdr.icmp6->icmp6_type;
4380                 icmpid = pd->hdr.icmp6->icmp6_id;
4381                 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4382
4383                 if (icmptype == ICMP6_DST_UNREACH ||
4384                     icmptype == ICMP6_PACKET_TOO_BIG ||
4385                     icmptype == ICMP6_TIME_EXCEEDED ||
4386                     icmptype == ICMP6_PARAM_PROB)
4387                         state_icmp++;
4388                 break;
4389 #endif /* INET6 */
4390         }
4391
4392         if (!state_icmp) {
4393
4394                 /*
4395                  * ICMP query/reply message not related to a TCP/UDP packet.
4396                  * Search for an ICMP state.
4397                  */
4398                 key.af = pd->af;
4399                 key.proto = pd->proto;
4400                 key.port[0] = key.port[1] = icmpid;
4401                 if (direction == PF_IN) {       /* wire side, straight */
4402                         PF_ACPY(&key.addr[0], pd->src, key.af);
4403                         PF_ACPY(&key.addr[1], pd->dst, key.af);
4404                 } else {                        /* stack side, reverse */
4405                         PF_ACPY(&key.addr[1], pd->src, key.af);
4406                         PF_ACPY(&key.addr[0], pd->dst, key.af);
4407                 }
4408
4409                 STATE_LOOKUP(kif, &key, direction, *state, pd);
4410
4411                 (*state)->expire = time_uptime;
4412                 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4413
4414                 /* translate source/destination address, if necessary */
4415                 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4416                         struct pf_state_key *nk = (*state)->key[pd->didx];
4417
4418                         switch (pd->af) {
4419 #ifdef INET
4420                         case AF_INET:
4421                                 if (PF_ANEQ(pd->src,
4422                                     &nk->addr[pd->sidx], AF_INET))
4423                                         pf_change_a(&saddr->v4.s_addr,
4424                                             pd->ip_sum,
4425                                             nk->addr[pd->sidx].v4.s_addr, 0);
4426
4427                                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4428                                     AF_INET))
4429                                         pf_change_a(&daddr->v4.s_addr,
4430                                             pd->ip_sum,
4431                                             nk->addr[pd->didx].v4.s_addr, 0);
4432
4433                                 if (nk->port[0] !=
4434                                     pd->hdr.icmp->icmp_id) {
4435                                         pd->hdr.icmp->icmp_cksum =
4436                                             pf_cksum_fixup(
4437                                             pd->hdr.icmp->icmp_cksum, icmpid,
4438                                             nk->port[pd->sidx], 0);
4439                                         pd->hdr.icmp->icmp_id =
4440                                             nk->port[pd->sidx];
4441                                 }
4442
4443                                 m_copyback(m, off, ICMP_MINLEN,
4444                                     (caddr_t )pd->hdr.icmp);
4445                                 break;
4446 #endif /* INET */
4447 #ifdef INET6
4448                         case AF_INET6:
4449                                 if (PF_ANEQ(pd->src,
4450                                     &nk->addr[pd->sidx], AF_INET6))
4451                                         pf_change_a6(saddr,
4452                                             &pd->hdr.icmp6->icmp6_cksum,
4453                                             &nk->addr[pd->sidx], 0);
4454
4455                                 if (PF_ANEQ(pd->dst,
4456                                     &nk->addr[pd->didx], AF_INET6))
4457                                         pf_change_a6(daddr,
4458                                             &pd->hdr.icmp6->icmp6_cksum,
4459                                             &nk->addr[pd->didx], 0);
4460
4461                                 m_copyback(m, off, sizeof(struct icmp6_hdr),
4462                                     (caddr_t )pd->hdr.icmp6);
4463                                 break;
4464 #endif /* INET6 */
4465                         }
4466                 }
4467                 return (PF_PASS);
4468
4469         } else {
4470                 /*
4471                  * ICMP error message in response to a TCP/UDP packet.
4472                  * Extract the inner TCP/UDP header and search for that state.
4473                  */
4474
4475                 struct pf_pdesc pd2;
4476                 bzero(&pd2, sizeof pd2);
4477 #ifdef INET
4478                 struct ip       h2;
4479 #endif /* INET */
4480 #ifdef INET6
4481                 struct ip6_hdr  h2_6;
4482                 int             terminal = 0;
4483 #endif /* INET6 */
4484                 int             ipoff2 = 0;
4485                 int             off2 = 0;
4486
4487                 pd2.af = pd->af;
4488                 /* Payload packet is from the opposite direction. */
4489                 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4490                 pd2.didx = (direction == PF_IN) ? 0 : 1;
4491                 switch (pd->af) {
4492 #ifdef INET
4493                 case AF_INET:
4494                         /* offset of h2 in mbuf chain */
4495                         ipoff2 = off + ICMP_MINLEN;
4496
4497                         if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4498                             NULL, reason, pd2.af)) {
4499                                 DPFPRINTF(PF_DEBUG_MISC,
4500                                     ("pf: ICMP error message too short "
4501                                     "(ip)\n"));
4502                                 return (PF_DROP);
4503                         }
4504                         /*
4505                          * ICMP error messages don't refer to non-first
4506                          * fragments
4507                          */
4508                         if (h2.ip_off & htons(IP_OFFMASK)) {
4509                                 REASON_SET(reason, PFRES_FRAG);
4510                                 return (PF_DROP);
4511                         }
4512
4513                         /* offset of protocol header that follows h2 */
4514                         off2 = ipoff2 + (h2.ip_hl << 2);
4515
4516                         pd2.proto = h2.ip_p;
4517                         pd2.src = (struct pf_addr *)&h2.ip_src;
4518                         pd2.dst = (struct pf_addr *)&h2.ip_dst;
4519                         pd2.ip_sum = &h2.ip_sum;
4520                         break;
4521 #endif /* INET */
4522 #ifdef INET6
4523                 case AF_INET6:
4524                         ipoff2 = off + sizeof(struct icmp6_hdr);
4525
4526                         if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4527                             NULL, reason, pd2.af)) {
4528                                 DPFPRINTF(PF_DEBUG_MISC,
4529                                     ("pf: ICMP error message too short "
4530                                     "(ip6)\n"));
4531                                 return (PF_DROP);
4532                         }
4533                         pd2.proto = h2_6.ip6_nxt;
4534                         pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4535                         pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4536                         pd2.ip_sum = NULL;
4537                         off2 = ipoff2 + sizeof(h2_6);
4538                         do {
4539                                 switch (pd2.proto) {
4540                                 case IPPROTO_FRAGMENT:
4541                                         /*
4542                                          * ICMPv6 error messages for
4543                                          * non-first fragments
4544                                          */
4545                                         REASON_SET(reason, PFRES_FRAG);
4546                                         return (PF_DROP);
4547                                 case IPPROTO_AH:
4548                                 case IPPROTO_HOPOPTS:
4549                                 case IPPROTO_ROUTING:
4550                                 case IPPROTO_DSTOPTS: {
4551                                         /* get next header and header length */
4552                                         struct ip6_ext opt6;
4553
4554                                         if (!pf_pull_hdr(m, off2, &opt6,
4555                                             sizeof(opt6), NULL, reason,
4556                                             pd2.af)) {
4557                                                 DPFPRINTF(PF_DEBUG_MISC,
4558                                                     ("pf: ICMPv6 short opt\n"));
4559                                                 return (PF_DROP);
4560                                         }
4561                                         if (pd2.proto == IPPROTO_AH)
4562                                                 off2 += (opt6.ip6e_len + 2) * 4;
4563                                         else
4564                                                 off2 += (opt6.ip6e_len + 1) * 8;
4565                                         pd2.proto = opt6.ip6e_nxt;
4566                                         /* goto the next header */
4567                                         break;
4568                                 }
4569                                 default:
4570                                         terminal++;
4571                                         break;
4572                                 }
4573                         } while (!terminal);
4574                         break;
4575 #endif /* INET6 */
4576                 }
4577
4578                 switch (pd2.proto) {
4579                 case IPPROTO_TCP: {
4580                         struct tcphdr            th;
4581                         u_int32_t                seq;
4582                         struct pf_state_peer    *src, *dst;
4583                         u_int8_t                 dws;
4584                         int                      copyback = 0;
4585
4586                         /*
4587                          * Only the first 8 bytes of the TCP header can be
4588                          * expected. Don't access any TCP header fields after
4589                          * th_seq, an ackskew test is not possible.
4590                          */
4591                         if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4592                             pd2.af)) {
4593                                 DPFPRINTF(PF_DEBUG_MISC,
4594                                     ("pf: ICMP error message too short "
4595                                     "(tcp)\n"));
4596                                 return (PF_DROP);
4597                         }
4598
4599                         key.af = pd2.af;
4600                         key.proto = IPPROTO_TCP;
4601                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4602                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4603                         key.port[pd2.sidx] = th.th_sport;
4604                         key.port[pd2.didx] = th.th_dport;
4605
4606                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4607
4608                         if (direction == (*state)->direction) {
4609                                 src = &(*state)->dst;
4610                                 dst = &(*state)->src;
4611                         } else {
4612                                 src = &(*state)->src;
4613                                 dst = &(*state)->dst;
4614                         }
4615
4616                         if (src->wscale && dst->wscale)
4617                                 dws = dst->wscale & PF_WSCALE_MASK;
4618                         else
4619                                 dws = 0;
4620
4621                         /* Demodulate sequence number */
4622                         seq = ntohl(th.th_seq) - src->seqdiff;
4623                         if (src->seqdiff) {
4624                                 pf_change_a(&th.th_seq, icmpsum,
4625                                     htonl(seq), 0);
4626                                 copyback = 1;
4627                         }
4628
4629                         if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4630                             (!SEQ_GEQ(src->seqhi, seq) ||
4631                             !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4632                                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4633                                         printf("pf: BAD ICMP %d:%d ",
4634                                             icmptype, pd->hdr.icmp->icmp_code);
4635                                         pf_print_host(pd->src, 0, pd->af);
4636                                         printf(" -> ");
4637                                         pf_print_host(pd->dst, 0, pd->af);
4638                                         printf(" state: ");
4639                                         pf_print_state(*state);
4640                                         printf(" seq=%u\n", seq);
4641                                 }
4642                                 REASON_SET(reason, PFRES_BADSTATE);
4643                                 return (PF_DROP);
4644                         } else {
4645                                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4646                                         printf("pf: OK ICMP %d:%d ",
4647                                             icmptype, pd->hdr.icmp->icmp_code);
4648                                         pf_print_host(pd->src, 0, pd->af);
4649                                         printf(" -> ");
4650                                         pf_print_host(pd->dst, 0, pd->af);
4651                                         printf(" state: ");
4652                                         pf_print_state(*state);
4653                                         printf(" seq=%u\n", seq);
4654                                 }
4655                         }
4656
4657                         /* translate source/destination address, if necessary */
4658                         if ((*state)->key[PF_SK_WIRE] !=
4659                             (*state)->key[PF_SK_STACK]) {
4660                                 struct pf_state_key *nk =
4661                                     (*state)->key[pd->didx];
4662
4663                                 if (PF_ANEQ(pd2.src,
4664                                     &nk->addr[pd2.sidx], pd2.af) ||
4665                                     nk->port[pd2.sidx] != th.th_sport)
4666                                         pf_change_icmp(pd2.src, &th.th_sport,
4667                                             daddr, &nk->addr[pd2.sidx],
4668                                             nk->port[pd2.sidx], NULL,
4669                                             pd2.ip_sum, icmpsum,
4670                                             pd->ip_sum, 0, pd2.af);
4671
4672                                 if (PF_ANEQ(pd2.dst,
4673                                     &nk->addr[pd2.didx], pd2.af) ||
4674                                     nk->port[pd2.didx] != th.th_dport)
4675                                         pf_change_icmp(pd2.dst, &th.th_dport,
4676                                             NULL, /* XXX Inbound NAT? */
4677                                             &nk->addr[pd2.didx],
4678                                             nk->port[pd2.didx], NULL,
4679                                             pd2.ip_sum, icmpsum,
4680                                             pd->ip_sum, 0, pd2.af);
4681                                 copyback = 1;
4682                         }
4683
4684                         if (copyback) {
4685                                 switch (pd2.af) {
4686 #ifdef INET
4687                                 case AF_INET:
4688                                         m_copyback(m, off, ICMP_MINLEN,
4689                                             (caddr_t )pd->hdr.icmp);
4690                                         m_copyback(m, ipoff2, sizeof(h2),
4691                                             (caddr_t )&h2);
4692                                         break;
4693 #endif /* INET */
4694 #ifdef INET6
4695                                 case AF_INET6:
4696                                         m_copyback(m, off,
4697                                             sizeof(struct icmp6_hdr),
4698                                             (caddr_t )pd->hdr.icmp6);
4699                                         m_copyback(m, ipoff2, sizeof(h2_6),
4700                                             (caddr_t )&h2_6);
4701                                         break;
4702 #endif /* INET6 */
4703                                 }
4704                                 m_copyback(m, off2, 8, (caddr_t)&th);
4705                         }
4706
4707                         return (PF_PASS);
4708                         break;
4709                 }
4710                 case IPPROTO_UDP: {
4711                         struct udphdr           uh;
4712
4713                         if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4714                             NULL, reason, pd2.af)) {
4715                                 DPFPRINTF(PF_DEBUG_MISC,
4716                                     ("pf: ICMP error message too short "
4717                                     "(udp)\n"));
4718                                 return (PF_DROP);
4719                         }
4720
4721                         key.af = pd2.af;
4722                         key.proto = IPPROTO_UDP;
4723                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4724                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4725                         key.port[pd2.sidx] = uh.uh_sport;
4726                         key.port[pd2.didx] = uh.uh_dport;
4727
4728                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4729
4730                         /* translate source/destination address, if necessary */
4731                         if ((*state)->key[PF_SK_WIRE] !=
4732                             (*state)->key[PF_SK_STACK]) {
4733                                 struct pf_state_key *nk =
4734                                     (*state)->key[pd->didx];
4735
4736                                 if (PF_ANEQ(pd2.src,
4737                                     &nk->addr[pd2.sidx], pd2.af) ||
4738                                     nk->port[pd2.sidx] != uh.uh_sport)
4739                                         pf_change_icmp(pd2.src, &uh.uh_sport,
4740                                             daddr, &nk->addr[pd2.sidx],
4741                                             nk->port[pd2.sidx], &uh.uh_sum,
4742                                             pd2.ip_sum, icmpsum,
4743                                             pd->ip_sum, 1, pd2.af);
4744
4745                                 if (PF_ANEQ(pd2.dst,
4746                                     &nk->addr[pd2.didx], pd2.af) ||
4747                                     nk->port[pd2.didx] != uh.uh_dport)
4748                                         pf_change_icmp(pd2.dst, &uh.uh_dport,
4749                                             NULL, /* XXX Inbound NAT? */
4750                                             &nk->addr[pd2.didx],
4751                                             nk->port[pd2.didx], &uh.uh_sum,
4752                                             pd2.ip_sum, icmpsum,
4753                                             pd->ip_sum, 1, pd2.af);
4754
4755                                 switch (pd2.af) {
4756 #ifdef INET
4757                                 case AF_INET:
4758                                         m_copyback(m, off, ICMP_MINLEN,
4759                                             (caddr_t )pd->hdr.icmp);
4760                                         m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4761                                         break;
4762 #endif /* INET */
4763 #ifdef INET6
4764                                 case AF_INET6:
4765                                         m_copyback(m, off,
4766                                             sizeof(struct icmp6_hdr),
4767                                             (caddr_t )pd->hdr.icmp6);
4768                                         m_copyback(m, ipoff2, sizeof(h2_6),
4769                                             (caddr_t )&h2_6);
4770                                         break;
4771 #endif /* INET6 */
4772                                 }
4773                                 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4774                         }
4775                         return (PF_PASS);
4776                         break;
4777                 }
4778 #ifdef INET
4779                 case IPPROTO_ICMP: {
4780                         struct icmp             iih;
4781
4782                         if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4783                             NULL, reason, pd2.af)) {
4784                                 DPFPRINTF(PF_DEBUG_MISC,
4785                                     ("pf: ICMP error message too short i"
4786                                     "(icmp)\n"));
4787                                 return (PF_DROP);
4788                         }
4789
4790                         key.af = pd2.af;
4791                         key.proto = IPPROTO_ICMP;
4792                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4793                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4794                         key.port[0] = key.port[1] = iih.icmp_id;
4795
4796                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4797
4798                         /* translate source/destination address, if necessary */
4799                         if ((*state)->key[PF_SK_WIRE] !=
4800                             (*state)->key[PF_SK_STACK]) {
4801                                 struct pf_state_key *nk =
4802                                     (*state)->key[pd->didx];
4803
4804                                 if (PF_ANEQ(pd2.src,
4805                                     &nk->addr[pd2.sidx], pd2.af) ||
4806                                     nk->port[pd2.sidx] != iih.icmp_id)
4807                                         pf_change_icmp(pd2.src, &iih.icmp_id,
4808                                             daddr, &nk->addr[pd2.sidx],
4809                                             nk->port[pd2.sidx], NULL,
4810                                             pd2.ip_sum, icmpsum,
4811                                             pd->ip_sum, 0, AF_INET);
4812
4813                                 if (PF_ANEQ(pd2.dst,
4814                                     &nk->addr[pd2.didx], pd2.af) ||
4815                                     nk->port[pd2.didx] != iih.icmp_id)
4816                                         pf_change_icmp(pd2.dst, &iih.icmp_id,
4817                                             NULL, /* XXX Inbound NAT? */
4818                                             &nk->addr[pd2.didx],
4819                                             nk->port[pd2.didx], NULL,
4820                                             pd2.ip_sum, icmpsum,
4821                                             pd->ip_sum, 0, AF_INET);
4822
4823                                 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4824                                 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4825                                 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4826                         }
4827                         return (PF_PASS);
4828                         break;
4829                 }
4830 #endif /* INET */
4831 #ifdef INET6
4832                 case IPPROTO_ICMPV6: {
4833                         struct icmp6_hdr        iih;
4834
4835                         if (!pf_pull_hdr(m, off2, &iih,
4836                             sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4837                                 DPFPRINTF(PF_DEBUG_MISC,
4838                                     ("pf: ICMP error message too short "
4839                                     "(icmp6)\n"));
4840                                 return (PF_DROP);
4841                         }
4842
4843                         key.af = pd2.af;
4844                         key.proto = IPPROTO_ICMPV6;
4845                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4846                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4847                         key.port[0] = key.port[1] = iih.icmp6_id;
4848
4849                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4850
4851                         /* translate source/destination address, if necessary */
4852                         if ((*state)->key[PF_SK_WIRE] !=
4853                             (*state)->key[PF_SK_STACK]) {
4854                                 struct pf_state_key *nk =
4855                                     (*state)->key[pd->didx];
4856
4857                                 if (PF_ANEQ(pd2.src,
4858                                     &nk->addr[pd2.sidx], pd2.af) ||
4859                                     nk->port[pd2.sidx] != iih.icmp6_id)
4860                                         pf_change_icmp(pd2.src, &iih.icmp6_id,
4861                                             daddr, &nk->addr[pd2.sidx],
4862                                             nk->port[pd2.sidx], NULL,
4863                                             pd2.ip_sum, icmpsum,
4864                                             pd->ip_sum, 0, AF_INET6);
4865
4866                                 if (PF_ANEQ(pd2.dst,
4867                                     &nk->addr[pd2.didx], pd2.af) ||
4868                                     nk->port[pd2.didx] != iih.icmp6_id)
4869                                         pf_change_icmp(pd2.dst, &iih.icmp6_id,
4870                                             NULL, /* XXX Inbound NAT? */
4871                                             &nk->addr[pd2.didx],
4872                                             nk->port[pd2.didx], NULL,
4873                                             pd2.ip_sum, icmpsum,
4874                                             pd->ip_sum, 0, AF_INET6);
4875
4876                                 m_copyback(m, off, sizeof(struct icmp6_hdr),
4877                                     (caddr_t)pd->hdr.icmp6);
4878                                 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4879                                 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4880                                     (caddr_t)&iih);
4881                         }
4882                         return (PF_PASS);
4883                         break;
4884                 }
4885 #endif /* INET6 */
4886                 default: {
4887                         key.af = pd2.af;
4888                         key.proto = pd2.proto;
4889                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4890                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4891                         key.port[0] = key.port[1] = 0;
4892
4893                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4894
4895                         /* translate source/destination address, if necessary */
4896                         if ((*state)->key[PF_SK_WIRE] !=
4897                             (*state)->key[PF_SK_STACK]) {
4898                                 struct pf_state_key *nk =
4899                                     (*state)->key[pd->didx];
4900
4901                                 if (PF_ANEQ(pd2.src,
4902                                     &nk->addr[pd2.sidx], pd2.af))
4903                                         pf_change_icmp(pd2.src, NULL, daddr,
4904                                             &nk->addr[pd2.sidx], 0, NULL,
4905                                             pd2.ip_sum, icmpsum,
4906                                             pd->ip_sum, 0, pd2.af);
4907
4908                                 if (PF_ANEQ(pd2.dst,
4909                                     &nk->addr[pd2.didx], pd2.af))
4910                                         pf_change_icmp(pd2.src, NULL,
4911                                             NULL, /* XXX Inbound NAT? */
4912                                             &nk->addr[pd2.didx], 0, NULL,
4913                                             pd2.ip_sum, icmpsum,
4914                                             pd->ip_sum, 0, pd2.af);
4915
4916                                 switch (pd2.af) {
4917 #ifdef INET
4918                                 case AF_INET:
4919                                         m_copyback(m, off, ICMP_MINLEN,
4920                                             (caddr_t)pd->hdr.icmp);
4921                                         m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4922                                         break;
4923 #endif /* INET */
4924 #ifdef INET6
4925                                 case AF_INET6:
4926                                         m_copyback(m, off,
4927                                             sizeof(struct icmp6_hdr),
4928                                             (caddr_t )pd->hdr.icmp6);
4929                                         m_copyback(m, ipoff2, sizeof(h2_6),
4930                                             (caddr_t )&h2_6);
4931                                         break;
4932 #endif /* INET6 */
4933                                 }
4934                         }
4935                         return (PF_PASS);
4936                         break;
4937                 }
4938                 }
4939         }
4940 }
4941
4942 static int
4943 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
4944     struct mbuf *m, struct pf_pdesc *pd)
4945 {
4946         struct pf_state_peer    *src, *dst;
4947         struct pf_state_key_cmp  key;
4948
4949         bzero(&key, sizeof(key));
4950         key.af = pd->af;
4951         key.proto = pd->proto;
4952         if (direction == PF_IN) {
4953                 PF_ACPY(&key.addr[0], pd->src, key.af);
4954                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4955                 key.port[0] = key.port[1] = 0;
4956         } else {
4957                 PF_ACPY(&key.addr[1], pd->src, key.af);
4958                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4959                 key.port[1] = key.port[0] = 0;
4960         }
4961
4962         STATE_LOOKUP(kif, &key, direction, *state, pd);
4963
4964         if (direction == (*state)->direction) {
4965                 src = &(*state)->src;
4966                 dst = &(*state)->dst;
4967         } else {
4968                 src = &(*state)->dst;
4969                 dst = &(*state)->src;
4970         }
4971
4972         /* update states */
4973         if (src->state < PFOTHERS_SINGLE)
4974                 src->state = PFOTHERS_SINGLE;
4975         if (dst->state == PFOTHERS_SINGLE)
4976                 dst->state = PFOTHERS_MULTIPLE;
4977
4978         /* update expire time */
4979         (*state)->expire = time_uptime;
4980         if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
4981                 (*state)->timeout = PFTM_OTHER_MULTIPLE;
4982         else
4983                 (*state)->timeout = PFTM_OTHER_SINGLE;
4984
4985         /* translate source/destination address, if necessary */
4986         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4987                 struct pf_state_key *nk = (*state)->key[pd->didx];
4988
4989                 KASSERT(nk, ("%s: nk is null", __func__));
4990                 KASSERT(pd, ("%s: pd is null", __func__));
4991                 KASSERT(pd->src, ("%s: pd->src is null", __func__));
4992                 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
4993                 switch (pd->af) {
4994 #ifdef INET
4995                 case AF_INET:
4996                         if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
4997                                 pf_change_a(&pd->src->v4.s_addr,
4998                                     pd->ip_sum,
4999                                     nk->addr[pd->sidx].v4.s_addr,
5000                                     0);
5001
5002
5003                         if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5004                                 pf_change_a(&pd->dst->v4.s_addr,
5005                                     pd->ip_sum,
5006                                     nk->addr[pd->didx].v4.s_addr,
5007                                     0);
5008
5009                                 break;
5010 #endif /* INET */
5011 #ifdef INET6
5012                 case AF_INET6:
5013                         if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5014                                 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5015
5016                         if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5017                                 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5018 #endif /* INET6 */
5019                 }
5020         }
5021         return (PF_PASS);
5022 }
5023
5024 /*
5025  * ipoff and off are measured from the start of the mbuf chain.
5026  * h must be at "ipoff" on the mbuf chain.
5027  */
5028 void *
5029 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5030     u_short *actionp, u_short *reasonp, sa_family_t af)
5031 {
5032         switch (af) {
5033 #ifdef INET
5034         case AF_INET: {
5035                 struct ip       *h = mtod(m, struct ip *);
5036                 u_int16_t        fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5037
5038                 if (fragoff) {
5039                         if (fragoff >= len)
5040                                 ACTION_SET(actionp, PF_PASS);
5041                         else {
5042                                 ACTION_SET(actionp, PF_DROP);
5043                                 REASON_SET(reasonp, PFRES_FRAG);
5044                         }
5045                         return (NULL);
5046                 }
5047                 if (m->m_pkthdr.len < off + len ||
5048                     ntohs(h->ip_len) < off + len) {
5049                         ACTION_SET(actionp, PF_DROP);
5050                         REASON_SET(reasonp, PFRES_SHORT);
5051                         return (NULL);
5052                 }
5053                 break;
5054         }
5055 #endif /* INET */
5056 #ifdef INET6
5057         case AF_INET6: {
5058                 struct ip6_hdr  *h = mtod(m, struct ip6_hdr *);
5059
5060                 if (m->m_pkthdr.len < off + len ||
5061                     (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5062                     (unsigned)(off + len)) {
5063                         ACTION_SET(actionp, PF_DROP);
5064                         REASON_SET(reasonp, PFRES_SHORT);
5065                         return (NULL);
5066                 }
5067                 break;
5068         }
5069 #endif /* INET6 */
5070         }
5071         m_copydata(m, off, len, p);
5072         return (p);
5073 }
5074
5075 int
5076 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5077     int rtableid)
5078 {
5079 #ifdef RADIX_MPATH
5080         struct radix_node_head  *rnh;
5081 #endif
5082         struct sockaddr_in      *dst;
5083         int                      ret = 1;
5084         int                      check_mpath;
5085 #ifdef INET6
5086         struct sockaddr_in6     *dst6;
5087         struct route_in6         ro;
5088 #else
5089         struct route             ro;
5090 #endif
5091         struct radix_node       *rn;
5092         struct rtentry          *rt;
5093         struct ifnet            *ifp;
5094
5095         check_mpath = 0;
5096 #ifdef RADIX_MPATH
5097         /* XXX: stick to table 0 for now */
5098         rnh = rt_tables_get_rnh(0, af);
5099         if (rnh != NULL && rn_mpath_capable(rnh))
5100                 check_mpath = 1;
5101 #endif
5102         bzero(&ro, sizeof(ro));
5103         switch (af) {
5104         case AF_INET:
5105                 dst = satosin(&ro.ro_dst);
5106                 dst->sin_family = AF_INET;
5107                 dst->sin_len = sizeof(*dst);
5108                 dst->sin_addr = addr->v4;
5109                 break;
5110 #ifdef INET6
5111         case AF_INET6:
5112                 /*
5113                  * Skip check for addresses with embedded interface scope,
5114                  * as they would always match anyway.
5115                  */
5116                 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5117                         goto out;
5118                 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5119                 dst6->sin6_family = AF_INET6;
5120                 dst6->sin6_len = sizeof(*dst6);
5121                 dst6->sin6_addr = addr->v6;
5122                 break;
5123 #endif /* INET6 */
5124         default:
5125                 return (0);
5126         }
5127
5128         /* Skip checks for ipsec interfaces */
5129         if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5130                 goto out;
5131
5132         switch (af) {
5133 #ifdef INET6
5134         case AF_INET6:
5135                 in6_rtalloc_ign(&ro, 0, rtableid);
5136                 break;
5137 #endif
5138 #ifdef INET
5139         case AF_INET:
5140                 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5141                 break;
5142 #endif
5143         default:
5144                 rtalloc_ign((struct route *)&ro, 0);    /* No/default FIB. */
5145                 break;
5146         }
5147
5148         if (ro.ro_rt != NULL) {
5149                 /* No interface given, this is a no-route check */
5150                 if (kif == NULL)
5151                         goto out;
5152
5153                 if (kif->pfik_ifp == NULL) {
5154                         ret = 0;
5155                         goto out;
5156                 }
5157
5158                 /* Perform uRPF check if passed input interface */
5159                 ret = 0;
5160                 rn = (struct radix_node *)ro.ro_rt;
5161                 do {
5162                         rt = (struct rtentry *)rn;
5163                         ifp = rt->rt_ifp;
5164
5165                         if (kif->pfik_ifp == ifp)
5166                                 ret = 1;
5167 #ifdef RADIX_MPATH
5168                         rn = rn_mpath_next(rn);
5169 #endif
5170                 } while (check_mpath == 1 && rn != NULL && ret == 0);
5171         } else
5172                 ret = 0;
5173 out:
5174         if (ro.ro_rt != NULL)
5175                 RTFREE(ro.ro_rt);
5176         return (ret);
5177 }
5178
5179 #ifdef INET
5180 static void
5181 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5182     struct pf_state *s, struct pf_pdesc *pd)
5183 {
5184         struct mbuf             *m0, *m1;
5185         struct sockaddr_in      dst;
5186         struct ip               *ip;
5187         struct ifnet            *ifp = NULL;
5188         struct pf_addr           naddr;
5189         struct pf_src_node      *sn = NULL;
5190         int                      error = 0;
5191         uint16_t                 ip_len, ip_off;
5192
5193         KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5194         KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5195             __func__));
5196
5197         if ((pd->pf_mtag == NULL &&
5198             ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5199             pd->pf_mtag->routed++ > 3) {
5200                 m0 = *m;
5201                 *m = NULL;
5202                 goto bad_locked;
5203         }
5204
5205         if (r->rt == PF_DUPTO) {
5206                 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5207                         if (s)
5208                                 PF_STATE_UNLOCK(s);
5209                         return;
5210                 }
5211         } else {
5212                 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5213                         if (s)
5214                                 PF_STATE_UNLOCK(s);
5215                         return;
5216                 }
5217                 m0 = *m;
5218         }
5219
5220         ip = mtod(m0, struct ip *);
5221
5222         bzero(&dst, sizeof(dst));
5223         dst.sin_family = AF_INET;
5224         dst.sin_len = sizeof(dst);
5225         dst.sin_addr = ip->ip_dst;
5226
5227         if (r->rt == PF_FASTROUTE) {
5228                 struct rtentry *rt;
5229
5230                 if (s)
5231                         PF_STATE_UNLOCK(s);
5232                 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5233                 if (rt == NULL) {
5234                         RTFREE_LOCKED(rt);
5235                         KMOD_IPSTAT_INC(ips_noroute);
5236                         error = EHOSTUNREACH;
5237                         goto bad;
5238                 }
5239
5240                 ifp = rt->rt_ifp;
5241                 rt->rt_rmx.rmx_pksent++;
5242
5243                 if (rt->rt_flags & RTF_GATEWAY)
5244                         bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5245                 RTFREE_LOCKED(rt);
5246         } else {
5247                 if (TAILQ_EMPTY(&r->rpool.list)) {
5248                         DPFPRINTF(PF_DEBUG_URGENT,
5249                             ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5250                         goto bad_locked;
5251                 }
5252                 if (s == NULL) {
5253                         pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5254                             &naddr, NULL, &sn);
5255                         if (!PF_AZERO(&naddr, AF_INET))
5256                                 dst.sin_addr.s_addr = naddr.v4.s_addr;
5257                         ifp = r->rpool.cur->kif ?
5258                             r->rpool.cur->kif->pfik_ifp : NULL;
5259                 } else {
5260                         if (!PF_AZERO(&s->rt_addr, AF_INET))
5261                                 dst.sin_addr.s_addr =
5262                                     s->rt_addr.v4.s_addr;
5263                         ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5264                         PF_STATE_UNLOCK(s);
5265                 }
5266         }
5267         if (ifp == NULL)
5268                 goto bad;
5269
5270         if (oifp != ifp) {
5271                 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5272                         goto bad;
5273                 else if (m0 == NULL)
5274                         goto done;
5275                 if (m0->m_len < sizeof(struct ip)) {
5276                         DPFPRINTF(PF_DEBUG_URGENT,
5277                             ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5278                         goto bad;
5279                 }
5280                 ip = mtod(m0, struct ip *);
5281         }
5282
5283         if (ifp->if_flags & IFF_LOOPBACK)
5284                 m0->m_flags |= M_SKIP_FIREWALL;
5285
5286         ip_len = ntohs(ip->ip_len);
5287         ip_off = ntohs(ip->ip_off);
5288
5289         /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5290         m0->m_pkthdr.csum_flags |= CSUM_IP;
5291         if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5292                 in_delayed_cksum(m0);
5293                 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5294         }
5295 #ifdef SCTP
5296         if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5297                 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5298                 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5299         }
5300 #endif
5301
5302         /*
5303          * If small enough for interface, or the interface will take
5304          * care of the fragmentation for us, we can just send directly.
5305          */
5306         if (ip_len <= ifp->if_mtu ||
5307             (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5308             ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5309                 ip->ip_sum = 0;
5310                 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5311                         ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5312                         m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5313                 }
5314                 m_clrprotoflags(m0);    /* Avoid confusing lower layers. */
5315                 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5316                 goto done;
5317         }
5318
5319         /* Balk when DF bit is set or the interface didn't support TSO. */
5320         if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5321                 error = EMSGSIZE;
5322                 KMOD_IPSTAT_INC(ips_cantfrag);
5323                 if (r->rt != PF_DUPTO) {
5324                         icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5325                             ifp->if_mtu);
5326                         goto done;
5327                 } else
5328                         goto bad;
5329         }
5330
5331         error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5332         if (error)
5333                 goto bad;
5334
5335         for (; m0; m0 = m1) {
5336                 m1 = m0->m_nextpkt;
5337                 m0->m_nextpkt = NULL;
5338                 if (error == 0) {
5339                         m_clrprotoflags(m0);
5340                         error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5341                 } else
5342                         m_freem(m0);
5343         }
5344
5345         if (error == 0)
5346                 KMOD_IPSTAT_INC(ips_fragmented);
5347
5348 done:
5349         if (r->rt != PF_DUPTO)
5350                 *m = NULL;
5351         return;
5352
5353 bad_locked:
5354         if (s)
5355                 PF_STATE_UNLOCK(s);
5356 bad:
5357         m_freem(m0);
5358         goto done;
5359 }
5360 #endif /* INET */
5361
5362 #ifdef INET6
5363 static void
5364 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5365     struct pf_state *s, struct pf_pdesc *pd)
5366 {
5367         struct mbuf             *m0;
5368         struct sockaddr_in6     dst;
5369         struct ip6_hdr          *ip6;
5370         struct ifnet            *ifp = NULL;
5371         struct pf_addr           naddr;
5372         struct pf_src_node      *sn = NULL;
5373
5374         KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5375         KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5376             __func__));
5377
5378         if ((pd->pf_mtag == NULL &&
5379             ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5380             pd->pf_mtag->routed++ > 3) {
5381                 m0 = *m;
5382                 *m = NULL;
5383                 goto bad_locked;
5384         }
5385
5386         if (r->rt == PF_DUPTO) {
5387                 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5388                         if (s)
5389                                 PF_STATE_UNLOCK(s);
5390                         return;
5391                 }
5392         } else {
5393                 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5394                         if (s)
5395                                 PF_STATE_UNLOCK(s);
5396                         return;
5397                 }
5398                 m0 = *m;
5399         }
5400
5401         ip6 = mtod(m0, struct ip6_hdr *);
5402
5403         bzero(&dst, sizeof(dst));
5404         dst.sin6_family = AF_INET6;
5405         dst.sin6_len = sizeof(dst);
5406         dst.sin6_addr = ip6->ip6_dst;
5407
5408         /* Cheat. XXX why only in the v6 case??? */
5409         if (r->rt == PF_FASTROUTE) {
5410                 if (s)
5411                         PF_STATE_UNLOCK(s);
5412                 m0->m_flags |= M_SKIP_FIREWALL;
5413                 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5414                 return;
5415         }
5416
5417         if (TAILQ_EMPTY(&r->rpool.list)) {
5418                 DPFPRINTF(PF_DEBUG_URGENT,
5419                     ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5420                 goto bad_locked;
5421         }
5422         if (s == NULL) {
5423                 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5424                     &naddr, NULL, &sn);
5425                 if (!PF_AZERO(&naddr, AF_INET6))
5426                         PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5427                             &naddr, AF_INET6);
5428                 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5429         } else {
5430                 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5431                         PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5432                             &s->rt_addr, AF_INET6);
5433                 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5434         }
5435
5436         if (s)
5437                 PF_STATE_UNLOCK(s);
5438
5439         if (ifp == NULL)
5440                 goto bad;
5441
5442         if (oifp != ifp) {
5443                 if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5444                         goto bad;
5445                 else if (m0 == NULL)
5446                         goto done;
5447                 if (m0->m_len < sizeof(struct ip6_hdr)) {
5448                         DPFPRINTF(PF_DEBUG_URGENT,
5449                             ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5450                             __func__));
5451                         goto bad;
5452                 }
5453                 ip6 = mtod(m0, struct ip6_hdr *);
5454         }
5455
5456         if (ifp->if_flags & IFF_LOOPBACK)
5457                 m0->m_flags |= M_SKIP_FIREWALL;
5458
5459         /*
5460          * If the packet is too large for the outgoing interface,
5461          * send back an icmp6 error.
5462          */
5463         if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5464                 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5465         if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5466                 nd6_output(ifp, ifp, m0, &dst, NULL);
5467         else {
5468                 in6_ifstat_inc(ifp, ifs6_in_toobig);
5469                 if (r->rt != PF_DUPTO)
5470                         icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5471                 else
5472                         goto bad;
5473         }
5474
5475 done:
5476         if (r->rt != PF_DUPTO)
5477                 *m = NULL;
5478         return;
5479
5480 bad_locked:
5481         if (s)
5482                 PF_STATE_UNLOCK(s);
5483 bad:
5484         m_freem(m0);
5485         goto done;
5486 }
5487 #endif /* INET6 */
5488
5489 /*
5490  * FreeBSD supports cksum offloads for the following drivers.
5491  *  em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5492  *   ti(4), txp(4), xl(4)
5493  *
5494  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5495  *  network driver performed cksum including pseudo header, need to verify
5496  *   csum_data
5497  * CSUM_DATA_VALID :
5498  *  network driver performed cksum, needs to additional pseudo header
5499  *  cksum computation with partial csum_data(i.e. lack of H/W support for
5500  *  pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5501  *
5502  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5503  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5504  * TCP/UDP layer.
5505  * Also, set csum_data to 0xffff to force cksum validation.
5506  */
5507 static int
5508 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5509 {
5510         u_int16_t sum = 0;
5511         int hw_assist = 0;
5512         struct ip *ip;
5513
5514         if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5515                 return (1);
5516         if (m->m_pkthdr.len < off + len)
5517                 return (1);
5518
5519         switch (p) {
5520         case IPPROTO_TCP:
5521                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5522                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5523                                 sum = m->m_pkthdr.csum_data;
5524                         } else {
5525                                 ip = mtod(m, struct ip *);
5526                                 sum = in_pseudo(ip->ip_src.s_addr,
5527                                 ip->ip_dst.s_addr, htonl((u_short)len +
5528                                 m->m_pkthdr.csum_data + IPPROTO_TCP));
5529                         }
5530                         sum ^= 0xffff;
5531                         ++hw_assist;
5532                 }
5533                 break;
5534         case IPPROTO_UDP:
5535                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5536                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5537                                 sum = m->m_pkthdr.csum_data;
5538                         } else {
5539                                 ip = mtod(m, struct ip *);
5540                                 sum = in_pseudo(ip->ip_src.s_addr,
5541                                 ip->ip_dst.s_addr, htonl((u_short)len +
5542                                 m->m_pkthdr.csum_data + IPPROTO_UDP));
5543                         }
5544                         sum ^= 0xffff;
5545                         ++hw_assist;
5546                 }
5547                 break;
5548         case IPPROTO_ICMP:
5549 #ifdef INET6
5550         case IPPROTO_ICMPV6:
5551 #endif /* INET6 */
5552                 break;
5553         default:
5554                 return (1);
5555         }
5556
5557         if (!hw_assist) {
5558                 switch (af) {
5559                 case AF_INET:
5560                         if (p == IPPROTO_ICMP) {
5561                                 if (m->m_len < off)
5562                                         return (1);
5563                                 m->m_data += off;
5564                                 m->m_len -= off;
5565                                 sum = in_cksum(m, len);
5566                                 m->m_data -= off;
5567                                 m->m_len += off;
5568                         } else {
5569                                 if (m->m_len < sizeof(struct ip))
5570                                         return (1);
5571                                 sum = in4_cksum(m, p, off, len);
5572                         }
5573                         break;
5574 #ifdef INET6
5575                 case AF_INET6:
5576                         if (m->m_len < sizeof(struct ip6_hdr))
5577                                 return (1);
5578                         sum = in6_cksum(m, p, off, len);
5579                         break;
5580 #endif /* INET6 */
5581                 default:
5582                         return (1);
5583                 }
5584         }
5585         if (sum) {
5586                 switch (p) {
5587                 case IPPROTO_TCP:
5588                     {
5589                         KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5590                         break;
5591                     }
5592                 case IPPROTO_UDP:
5593                     {
5594                         KMOD_UDPSTAT_INC(udps_badsum);
5595                         break;
5596                     }
5597 #ifdef INET
5598                 case IPPROTO_ICMP:
5599                     {
5600                         KMOD_ICMPSTAT_INC(icps_checksum);
5601                         break;
5602                     }
5603 #endif
5604 #ifdef INET6
5605                 case IPPROTO_ICMPV6:
5606                     {
5607                         KMOD_ICMP6STAT_INC(icp6s_checksum);
5608                         break;
5609                     }
5610 #endif /* INET6 */
5611                 }
5612                 return (1);
5613         } else {
5614                 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5615                         m->m_pkthdr.csum_flags |=
5616                             (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5617                         m->m_pkthdr.csum_data = 0xffff;
5618                 }
5619         }
5620         return (0);
5621 }
5622
5623
5624 #ifdef INET
5625 int
5626 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5627 {
5628         struct pfi_kif          *kif;
5629         u_short                  action, reason = 0, log = 0;
5630         struct mbuf             *m = *m0;
5631         struct ip               *h = NULL;
5632         struct m_tag            *ipfwtag;
5633         struct pf_rule          *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5634         struct pf_state         *s = NULL;
5635         struct pf_ruleset       *ruleset = NULL;
5636         struct pf_pdesc          pd;
5637         int                      off, dirndx, pqid = 0;
5638
5639         M_ASSERTPKTHDR(m);
5640
5641         if (!V_pf_status.running)
5642                 return (PF_PASS);
5643
5644         memset(&pd, 0, sizeof(pd));
5645
5646         kif = (struct pfi_kif *)ifp->if_pf_kif;
5647
5648         if (kif == NULL) {
5649                 DPFPRINTF(PF_DEBUG_URGENT,
5650                     ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5651                 return (PF_DROP);
5652         }
5653         if (kif->pfik_flags & PFI_IFLAG_SKIP)
5654                 return (PF_PASS);
5655
5656         if (m->m_flags & M_SKIP_FIREWALL)
5657                 return (PF_PASS);
5658
5659         pd.pf_mtag = pf_find_mtag(m);
5660
5661         PF_RULES_RLOCK();
5662
5663         if (ip_divert_ptr != NULL &&
5664             ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5665                 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5666                 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5667                         if (pd.pf_mtag == NULL &&
5668                             ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5669                                 action = PF_DROP;
5670                                 goto done;
5671                         }
5672                         pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5673                         m_tag_delete(m, ipfwtag);
5674                 }
5675                 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5676                         m->m_flags |= M_FASTFWD_OURS;
5677                         pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5678                 }
5679         } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5680                 /* We do IP header normalization and packet reassembly here */
5681                 action = PF_DROP;
5682                 goto done;
5683         }
5684         m = *m0;        /* pf_normalize messes with m0 */
5685         h = mtod(m, struct ip *);
5686
5687         off = h->ip_hl << 2;
5688         if (off < (int)sizeof(struct ip)) {
5689                 action = PF_DROP;
5690                 REASON_SET(&reason, PFRES_SHORT);
5691                 log = 1;
5692                 goto done;
5693         }
5694
5695         pd.src = (struct pf_addr *)&h->ip_src;
5696         pd.dst = (struct pf_addr *)&h->ip_dst;
5697         pd.sport = pd.dport = NULL;
5698         pd.ip_sum = &h->ip_sum;
5699         pd.proto_sum = NULL;
5700         pd.proto = h->ip_p;
5701         pd.dir = dir;
5702         pd.sidx = (dir == PF_IN) ? 0 : 1;
5703         pd.didx = (dir == PF_IN) ? 1 : 0;
5704         pd.af = AF_INET;
5705         pd.tos = h->ip_tos;
5706         pd.tot_len = ntohs(h->ip_len);
5707
5708         /* handle fragments that didn't get reassembled by normalization */
5709         if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5710                 action = pf_test_fragment(&r, dir, kif, m, h,
5711                     &pd, &a, &ruleset);
5712                 goto done;
5713         }
5714
5715         switch (h->ip_p) {
5716
5717         case IPPROTO_TCP: {
5718                 struct tcphdr   th;
5719
5720                 pd.hdr.tcp = &th;
5721                 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5722                     &action, &reason, AF_INET)) {
5723                         log = action != PF_PASS;
5724                         goto done;
5725                 }
5726                 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5727                 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5728                         pqid = 1;
5729                 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5730                 if (action == PF_DROP)
5731                         goto done;
5732                 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5733                     &reason);
5734                 if (action == PF_PASS) {
5735                         if (pfsync_update_state_ptr != NULL)
5736                                 pfsync_update_state_ptr(s);
5737                         r = s->rule.ptr;
5738                         a = s->anchor.ptr;
5739                         log = s->log;
5740                 } else if (s == NULL)
5741                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5742                             &a, &ruleset, inp);
5743                 break;
5744         }
5745
5746         case IPPROTO_UDP: {
5747                 struct udphdr   uh;
5748
5749                 pd.hdr.udp = &uh;
5750                 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5751                     &action, &reason, AF_INET)) {
5752                         log = action != PF_PASS;
5753                         goto done;
5754                 }
5755                 if (uh.uh_dport == 0 ||
5756                     ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5757                     ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5758                         action = PF_DROP;
5759                         REASON_SET(&reason, PFRES_SHORT);
5760                         goto done;
5761                 }
5762                 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5763                 if (action == PF_PASS) {
5764                         if (pfsync_update_state_ptr != NULL)
5765                                 pfsync_update_state_ptr(s);
5766                         r = s->rule.ptr;
5767                         a = s->anchor.ptr;
5768                         log = s->log;
5769                 } else if (s == NULL)
5770                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5771                             &a, &ruleset, inp);
5772                 break;
5773         }
5774
5775         case IPPROTO_ICMP: {
5776                 struct icmp     ih;
5777
5778                 pd.hdr.icmp = &ih;
5779                 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5780                     &action, &reason, AF_INET)) {
5781                         log = action != PF_PASS;
5782                         goto done;
5783                 }
5784                 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5785                     &reason);
5786                 if (action == PF_PASS) {
5787                         if (pfsync_update_state_ptr != NULL)
5788                                 pfsync_update_state_ptr(s);
5789                         r = s->rule.ptr;
5790                         a = s->anchor.ptr;
5791                         log = s->log;
5792                 } else if (s == NULL)
5793                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5794                             &a, &ruleset, inp);
5795                 break;
5796         }
5797
5798 #ifdef INET6
5799         case IPPROTO_ICMPV6: {
5800                 action = PF_DROP;
5801                 DPFPRINTF(PF_DEBUG_MISC,
5802                     ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5803                 goto done;
5804         }
5805 #endif
5806
5807         default:
5808                 action = pf_test_state_other(&s, dir, kif, m, &pd);
5809                 if (action == PF_PASS) {
5810                         if (pfsync_update_state_ptr != NULL)
5811                                 pfsync_update_state_ptr(s);
5812                         r = s->rule.ptr;
5813                         a = s->anchor.ptr;
5814                         log = s->log;
5815                 } else if (s == NULL)
5816                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5817                             &a, &ruleset, inp);
5818                 break;
5819         }
5820
5821 done:
5822         PF_RULES_RUNLOCK();
5823         if (action == PF_PASS && h->ip_hl > 5 &&
5824             !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5825                 action = PF_DROP;
5826                 REASON_SET(&reason, PFRES_IPOPTIONS);
5827                 log = 1;
5828                 DPFPRINTF(PF_DEBUG_MISC,
5829                     ("pf: dropping packet with ip options\n"));
5830         }
5831
5832         if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5833                 action = PF_DROP;
5834                 REASON_SET(&reason, PFRES_MEMORY);
5835         }
5836         if (r->rtableid >= 0)
5837                 M_SETFIB(m, r->rtableid);
5838
5839 #ifdef ALTQ
5840         if (action == PF_PASS && r->qid) {
5841                 if (pd.pf_mtag == NULL &&
5842                     ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5843                         action = PF_DROP;
5844                         REASON_SET(&reason, PFRES_MEMORY);
5845                 }
5846                 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5847                         pd.pf_mtag->qid = r->pqid;
5848                 else
5849                         pd.pf_mtag->qid = r->qid;
5850                 /* add hints for ecn */
5851                 pd.pf_mtag->hdr = h;
5852
5853         }
5854 #endif /* ALTQ */
5855
5856         /*
5857          * connections redirected to loopback should not match sockets
5858          * bound specifically to loopback due to security implications,
5859          * see tcp_input() and in_pcblookup_listen().
5860          */
5861         if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5862             pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5863             (s->nat_rule.ptr->action == PF_RDR ||
5864             s->nat_rule.ptr->action == PF_BINAT) &&
5865             (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5866                 m->m_flags |= M_SKIP_FIREWALL;
5867
5868         if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5869             !PACKET_LOOPED(&pd)) {
5870
5871                 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5872                     sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5873                 if (ipfwtag != NULL) {
5874                         ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5875                             ntohs(r->divert.port);
5876                         ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5877
5878                         if (s)
5879                                 PF_STATE_UNLOCK(s);
5880
5881                         m_tag_prepend(m, ipfwtag);
5882                         if (m->m_flags & M_FASTFWD_OURS) {
5883                                 if (pd.pf_mtag == NULL &&
5884                                     ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5885                                         action = PF_DROP;
5886                                         REASON_SET(&reason, PFRES_MEMORY);
5887                                         log = 1;
5888                                         DPFPRINTF(PF_DEBUG_MISC,
5889                                             ("pf: failed to allocate tag\n"));
5890                                 }
5891                                 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5892                                 m->m_flags &= ~M_FASTFWD_OURS;
5893                         }
5894                         ip_divert_ptr(*m0, dir ==  PF_IN ? DIR_IN : DIR_OUT);
5895                         *m0 = NULL;
5896
5897                         return (action);
5898                 } else {
5899                         /* XXX: ipfw has the same behaviour! */
5900                         action = PF_DROP;
5901                         REASON_SET(&reason, PFRES_MEMORY);
5902                         log = 1;
5903                         DPFPRINTF(PF_DEBUG_MISC,
5904                             ("pf: failed to allocate divert tag\n"));
5905                 }
5906         }
5907
5908         if (log) {
5909                 struct pf_rule *lr;
5910
5911                 if (s != NULL && s->nat_rule.ptr != NULL &&
5912                     s->nat_rule.ptr->log & PF_LOG_ALL)
5913                         lr = s->nat_rule.ptr;
5914                 else
5915                         lr = r;
5916                 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5917                     (s == NULL));
5918         }
5919
5920         kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5921         kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5922
5923         if (action == PF_PASS || r->action == PF_DROP) {
5924                 dirndx = (dir == PF_OUT);
5925                 r->packets[dirndx]++;
5926                 r->bytes[dirndx] += pd.tot_len;
5927                 if (a != NULL) {
5928                         a->packets[dirndx]++;
5929                         a->bytes[dirndx] += pd.tot_len;
5930                 }
5931                 if (s != NULL) {
5932                         if (s->nat_rule.ptr != NULL) {
5933                                 s->nat_rule.ptr->packets[dirndx]++;
5934                                 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
5935                         }
5936                         if (s->src_node != NULL) {
5937                                 s->src_node->packets[dirndx]++;
5938                                 s->src_node->bytes[dirndx] += pd.tot_len;
5939                         }
5940                         if (s->nat_src_node != NULL) {
5941                                 s->nat_src_node->packets[dirndx]++;
5942                                 s->nat_src_node->bytes[dirndx] += pd.tot_len;
5943                         }
5944                         dirndx = (dir == s->direction) ? 0 : 1;
5945                         s->packets[dirndx]++;
5946                         s->bytes[dirndx] += pd.tot_len;
5947                 }
5948                 tr = r;
5949                 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
5950                 if (nr != NULL && r == &V_pf_default_rule)
5951                         tr = nr;
5952                 if (tr->src.addr.type == PF_ADDR_TABLE)
5953                         pfr_update_stats(tr->src.addr.p.tbl,
5954                             (s == NULL) ? pd.src :
5955                             &s->key[(s->direction == PF_IN)]->
5956                                 addr[(s->direction == PF_OUT)],
5957                             pd.af, pd.tot_len, dir == PF_OUT,
5958                             r->action == PF_PASS, tr->src.neg);
5959                 if (tr->dst.addr.type == PF_ADDR_TABLE)
5960                         pfr_update_stats(tr->dst.addr.p.tbl,
5961                             (s == NULL) ? pd.dst :
5962                             &s->key[(s->direction == PF_IN)]->
5963                                 addr[(s->direction == PF_IN)],
5964                             pd.af, pd.tot_len, dir == PF_OUT,
5965                             r->action == PF_PASS, tr->dst.neg);
5966         }
5967
5968         switch (action) {
5969         case PF_SYNPROXY_DROP:
5970                 m_freem(*m0);
5971         case PF_DEFER:
5972                 *m0 = NULL;
5973                 action = PF_PASS;
5974                 break;
5975         default:
5976                 /* pf_route() returns unlocked. */
5977                 if (r->rt) {
5978                         pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
5979                         return (action);
5980                 }
5981                 break;
5982         }
5983         if (s)
5984                 PF_STATE_UNLOCK(s);
5985
5986         return (action);
5987 }
5988 #endif /* INET */
5989
5990 #ifdef INET6
5991 int
5992 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5993 {
5994         struct pfi_kif          *kif;
5995         u_short                  action, reason = 0, log = 0;
5996         struct mbuf             *m = *m0, *n = NULL;
5997         struct ip6_hdr          *h = NULL;
5998         struct pf_rule          *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5999         struct pf_state         *s = NULL;
6000         struct pf_ruleset       *ruleset = NULL;
6001         struct pf_pdesc          pd;
6002         int                      off, terminal = 0, dirndx, rh_cnt = 0;
6003
6004         M_ASSERTPKTHDR(m);
6005
6006         if (!V_pf_status.running)
6007                 return (PF_PASS);
6008
6009         memset(&pd, 0, sizeof(pd));
6010         pd.pf_mtag = pf_find_mtag(m);
6011
6012         if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6013                 return (PF_PASS);
6014
6015         kif = (struct pfi_kif *)ifp->if_pf_kif;
6016         if (kif == NULL) {
6017                 DPFPRINTF(PF_DEBUG_URGENT,
6018                     ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6019                 return (PF_DROP);
6020         }
6021         if (kif->pfik_flags & PFI_IFLAG_SKIP)
6022                 return (PF_PASS);
6023
6024         PF_RULES_RLOCK();
6025
6026         /* We do IP header normalization and packet reassembly here */
6027         if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6028                 action = PF_DROP;
6029                 goto done;
6030         }
6031         m = *m0;        /* pf_normalize messes with m0 */
6032         h = mtod(m, struct ip6_hdr *);
6033
6034 #if 1
6035         /*
6036          * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6037          * will do something bad, so drop the packet for now.
6038          */
6039         if (htons(h->ip6_plen) == 0) {
6040                 action = PF_DROP;
6041                 REASON_SET(&reason, PFRES_NORM);        /*XXX*/
6042                 goto done;
6043         }
6044 #endif
6045
6046         pd.src = (struct pf_addr *)&h->ip6_src;
6047         pd.dst = (struct pf_addr *)&h->ip6_dst;
6048         pd.sport = pd.dport = NULL;
6049         pd.ip_sum = NULL;
6050         pd.proto_sum = NULL;
6051         pd.dir = dir;
6052         pd.sidx = (dir == PF_IN) ? 0 : 1;
6053         pd.didx = (dir == PF_IN) ? 1 : 0;
6054         pd.af = AF_INET6;
6055         pd.tos = 0;
6056         pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6057
6058         off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6059         pd.proto = h->ip6_nxt;
6060         do {
6061                 switch (pd.proto) {
6062                 case IPPROTO_FRAGMENT:
6063                         action = pf_test_fragment(&r, dir, kif, m, h,
6064                             &pd, &a, &ruleset);
6065                         if (action == PF_DROP)
6066                                 REASON_SET(&reason, PFRES_FRAG);
6067                         goto done;
6068                 case IPPROTO_ROUTING: {
6069                         struct ip6_rthdr rthdr;
6070
6071                         if (rh_cnt++) {
6072                                 DPFPRINTF(PF_DEBUG_MISC,
6073                                     ("pf: IPv6 more than one rthdr\n"));
6074                                 action = PF_DROP;
6075                                 REASON_SET(&reason, PFRES_IPOPTIONS);
6076                                 log = 1;
6077                                 goto done;
6078                         }
6079                         if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6080                             &reason, pd.af)) {
6081                                 DPFPRINTF(PF_DEBUG_MISC,
6082                                     ("pf: IPv6 short rthdr\n"));
6083                                 action = PF_DROP;
6084                                 REASON_SET(&reason, PFRES_SHORT);
6085                                 log = 1;
6086                                 goto done;
6087                         }
6088                         if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6089                                 DPFPRINTF(PF_DEBUG_MISC,
6090                                     ("pf: IPv6 rthdr0\n"));
6091                                 action = PF_DROP;
6092                                 REASON_SET(&reason, PFRES_IPOPTIONS);
6093                                 log = 1;
6094                                 goto done;
6095                         }
6096                         /* FALLTHROUGH */
6097                 }
6098                 case IPPROTO_AH:
6099                 case IPPROTO_HOPOPTS:
6100                 case IPPROTO_DSTOPTS: {
6101                         /* get next header and header length */
6102                         struct ip6_ext  opt6;
6103
6104                         if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6105                             NULL, &reason, pd.af)) {
6106                                 DPFPRINTF(PF_DEBUG_MISC,
6107                                     ("pf: IPv6 short opt\n"));
6108                                 action = PF_DROP;
6109                                 log = 1;
6110                                 goto done;
6111                         }
6112                         if (pd.proto == IPPROTO_AH)
6113                                 off += (opt6.ip6e_len + 2) * 4;
6114                         else
6115                                 off += (opt6.ip6e_len + 1) * 8;
6116                         pd.proto = opt6.ip6e_nxt;
6117                         /* goto the next header */
6118                         break;
6119                 }
6120                 default:
6121                         terminal++;
6122                         break;
6123                 }
6124         } while (!terminal);
6125
6126         /* if there's no routing header, use unmodified mbuf for checksumming */
6127         if (!n)
6128                 n = m;
6129
6130         switch (pd.proto) {
6131
6132         case IPPROTO_TCP: {
6133                 struct tcphdr   th;
6134
6135                 pd.hdr.tcp = &th;
6136                 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6137                     &action, &reason, AF_INET6)) {
6138                         log = action != PF_PASS;
6139                         goto done;
6140                 }
6141                 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6142                 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6143                 if (action == PF_DROP)
6144                         goto done;
6145                 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6146                     &reason);
6147                 if (action == PF_PASS) {
6148                         if (pfsync_update_state_ptr != NULL)
6149                                 pfsync_update_state_ptr(s);
6150                         r = s->rule.ptr;
6151                         a = s->anchor.ptr;
6152                         log = s->log;
6153                 } else if (s == NULL)
6154                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6155                             &a, &ruleset, inp);
6156                 break;
6157         }
6158
6159         case IPPROTO_UDP: {
6160                 struct udphdr   uh;
6161
6162                 pd.hdr.udp = &uh;
6163                 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6164                     &action, &reason, AF_INET6)) {
6165                         log = action != PF_PASS;
6166                         goto done;
6167                 }
6168                 if (uh.uh_dport == 0 ||
6169                     ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6170                     ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6171                         action = PF_DROP;
6172                         REASON_SET(&reason, PFRES_SHORT);
6173                         goto done;
6174                 }
6175                 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6176                 if (action == PF_PASS) {
6177                         if (pfsync_update_state_ptr != NULL)
6178                                 pfsync_update_state_ptr(s);
6179                         r = s->rule.ptr;
6180                         a = s->anchor.ptr;
6181                         log = s->log;
6182                 } else if (s == NULL)
6183                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6184                             &a, &ruleset, inp);
6185                 break;
6186         }
6187
6188         case IPPROTO_ICMP: {
6189                 action = PF_DROP;
6190                 DPFPRINTF(PF_DEBUG_MISC,
6191                     ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6192                 goto done;
6193         }
6194
6195         case IPPROTO_ICMPV6: {
6196                 struct icmp6_hdr        ih;
6197
6198                 pd.hdr.icmp6 = &ih;
6199                 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6200                     &action, &reason, AF_INET6)) {
6201                         log = action != PF_PASS;
6202                         goto done;
6203                 }
6204                 action = pf_test_state_icmp(&s, dir, kif,
6205                     m, off, h, &pd, &reason);
6206                 if (action == PF_PASS) {
6207                         if (pfsync_update_state_ptr != NULL)
6208                                 pfsync_update_state_ptr(s);
6209                         r = s->rule.ptr;
6210                         a = s->anchor.ptr;
6211                         log = s->log;
6212                 } else if (s == NULL)
6213                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6214                             &a, &ruleset, inp);
6215                 break;
6216         }
6217
6218         default:
6219                 action = pf_test_state_other(&s, dir, kif, m, &pd);
6220                 if (action == PF_PASS) {
6221                         if (pfsync_update_state_ptr != NULL)
6222                                 pfsync_update_state_ptr(s);
6223                         r = s->rule.ptr;
6224                         a = s->anchor.ptr;
6225                         log = s->log;
6226                 } else if (s == NULL)
6227                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6228                             &a, &ruleset, inp);
6229                 break;
6230         }
6231
6232 done:
6233         PF_RULES_RUNLOCK();
6234         if (n != m) {
6235                 m_freem(n);
6236                 n = NULL;
6237         }
6238
6239         /* handle dangerous IPv6 extension headers. */
6240         if (action == PF_PASS && rh_cnt &&
6241             !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6242                 action = PF_DROP;
6243                 REASON_SET(&reason, PFRES_IPOPTIONS);
6244                 log = 1;
6245                 DPFPRINTF(PF_DEBUG_MISC,
6246                     ("pf: dropping packet with dangerous v6 headers\n"));
6247         }
6248
6249         if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6250                 action = PF_DROP;
6251                 REASON_SET(&reason, PFRES_MEMORY);
6252         }
6253         if (r->rtableid >= 0)
6254                 M_SETFIB(m, r->rtableid);
6255
6256 #ifdef ALTQ
6257         if (action == PF_PASS && r->qid) {
6258                 if (pd.pf_mtag == NULL &&
6259                     ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6260                         action = PF_DROP;
6261                         REASON_SET(&reason, PFRES_MEMORY);
6262                 }
6263                 if (pd.tos & IPTOS_LOWDELAY)
6264                         pd.pf_mtag->qid = r->pqid;
6265                 else
6266                         pd.pf_mtag->qid = r->qid;
6267                 /* add hints for ecn */
6268                 pd.pf_mtag->hdr = h;
6269         }
6270 #endif /* ALTQ */
6271
6272         if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6273             pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6274             (s->nat_rule.ptr->action == PF_RDR ||
6275             s->nat_rule.ptr->action == PF_BINAT) &&
6276             IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6277                 m->m_flags |= M_SKIP_FIREWALL;
6278
6279         /* XXX: Anybody working on it?! */
6280         if (r->divert.port)
6281                 printf("pf: divert(9) is not supported for IPv6\n");
6282
6283         if (log) {
6284                 struct pf_rule *lr;
6285
6286                 if (s != NULL && s->nat_rule.ptr != NULL &&
6287                     s->nat_rule.ptr->log & PF_LOG_ALL)
6288                         lr = s->nat_rule.ptr;
6289                 else
6290                         lr = r;
6291                 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6292                     &pd, (s == NULL));
6293         }
6294
6295         kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6296         kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6297
6298         if (action == PF_PASS || r->action == PF_DROP) {
6299                 dirndx = (dir == PF_OUT);
6300                 r->packets[dirndx]++;
6301                 r->bytes[dirndx] += pd.tot_len;
6302                 if (a != NULL) {
6303                         a->packets[dirndx]++;
6304                         a->bytes[dirndx] += pd.tot_len;
6305                 }
6306                 if (s != NULL) {
6307                         if (s->nat_rule.ptr != NULL) {
6308                                 s->nat_rule.ptr->packets[dirndx]++;
6309                                 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6310                         }
6311                         if (s->src_node != NULL) {
6312                                 s->src_node->packets[dirndx]++;
6313                                 s->src_node->bytes[dirndx] += pd.tot_len;
6314                         }
6315                         if (s->nat_src_node != NULL) {
6316                                 s->nat_src_node->packets[dirndx]++;
6317                                 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6318                         }
6319                         dirndx = (dir == s->direction) ? 0 : 1;
6320                         s->packets[dirndx]++;
6321                         s->bytes[dirndx] += pd.tot_len;
6322                 }
6323                 tr = r;
6324                 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6325                 if (nr != NULL && r == &V_pf_default_rule)
6326                         tr = nr;
6327                 if (tr->src.addr.type == PF_ADDR_TABLE)
6328                         pfr_update_stats(tr->src.addr.p.tbl,
6329                             (s == NULL) ? pd.src :
6330                             &s->key[(s->direction == PF_IN)]->addr[0],
6331                             pd.af, pd.tot_len, dir == PF_OUT,
6332                             r->action == PF_PASS, tr->src.neg);
6333                 if (tr->dst.addr.type == PF_ADDR_TABLE)
6334                         pfr_update_stats(tr->dst.addr.p.tbl,
6335                             (s == NULL) ? pd.dst :
6336                             &s->key[(s->direction == PF_IN)]->addr[1],
6337                             pd.af, pd.tot_len, dir == PF_OUT,
6338                             r->action == PF_PASS, tr->dst.neg);
6339         }
6340
6341         switch (action) {
6342         case PF_SYNPROXY_DROP:
6343                 m_freem(*m0);
6344         case PF_DEFER:
6345                 *m0 = NULL;
6346                 action = PF_PASS;
6347                 break;
6348         default:
6349                 /* pf_route6() returns unlocked. */
6350                 if (r->rt) {
6351                         pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6352                         return (action);
6353                 }
6354                 break;
6355         }
6356
6357         if (s)
6358                 PF_STATE_UNLOCK(s);
6359
6360         return (action);
6361 }
6362 #endif /* INET6 */