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