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