]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netpfil/pf/pf.c
MFC r343295:
[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 (V_pfsync_insert_state_ptr != NULL)
1263                 V_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                         timeout = (u_int64_t)timeout * (end - states) /
1562                             (end - start);
1563                         return (state->expire + timeout);
1564                 }
1565                 else
1566                         return (time_uptime);
1567         }
1568         return (state->expire + timeout);
1569 }
1570
1571 void
1572 pf_purge_expired_src_nodes()
1573 {
1574         struct pf_src_node_list  freelist;
1575         struct pf_srchash       *sh;
1576         struct pf_src_node      *cur, *next;
1577         int i;
1578
1579         LIST_INIT(&freelist);
1580         for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1581             PF_HASHROW_LOCK(sh);
1582             LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1583                 if (cur->states == 0 && cur->expire <= time_uptime) {
1584                         pf_unlink_src_node(cur);
1585                         LIST_INSERT_HEAD(&freelist, cur, entry);
1586                 } else if (cur->rule.ptr != NULL)
1587                         cur->rule.ptr->rule_flag |= PFRULE_REFS;
1588             PF_HASHROW_UNLOCK(sh);
1589         }
1590
1591         pf_free_src_nodes(&freelist);
1592
1593         V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1594 }
1595
1596 static void
1597 pf_src_tree_remove_state(struct pf_state *s)
1598 {
1599         struct pf_src_node *sn;
1600         struct pf_srchash *sh;
1601         uint32_t timeout;
1602
1603         timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1604             s->rule.ptr->timeout[PFTM_SRC_NODE] :
1605             V_pf_default_rule.timeout[PFTM_SRC_NODE];
1606
1607         if (s->src_node != NULL) {
1608                 sn = s->src_node;
1609                 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1610                 PF_HASHROW_LOCK(sh);
1611                 if (s->src.tcp_est)
1612                         --sn->conn;
1613                 if (--sn->states == 0)
1614                         sn->expire = time_uptime + timeout;
1615                 PF_HASHROW_UNLOCK(sh);
1616         }
1617         if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1618                 sn = s->nat_src_node;
1619                 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1620                 PF_HASHROW_LOCK(sh);
1621                 if (--sn->states == 0)
1622                         sn->expire = time_uptime + timeout;
1623                 PF_HASHROW_UNLOCK(sh);
1624         }
1625         s->src_node = s->nat_src_node = NULL;
1626 }
1627
1628 /*
1629  * Unlink and potentilly free a state. Function may be
1630  * called with ID hash row locked, but always returns
1631  * unlocked, since it needs to go through key hash locking.
1632  */
1633 int
1634 pf_unlink_state(struct pf_state *s, u_int flags)
1635 {
1636         struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1637
1638         if ((flags & PF_ENTER_LOCKED) == 0)
1639                 PF_HASHROW_LOCK(ih);
1640         else
1641                 PF_HASHROW_ASSERT(ih);
1642
1643         if (s->timeout == PFTM_UNLINKED) {
1644                 /*
1645                  * State is being processed
1646                  * by pf_unlink_state() in
1647                  * an other thread.
1648                  */
1649                 PF_HASHROW_UNLOCK(ih);
1650                 return (0);     /* XXXGL: undefined actually */
1651         }
1652
1653         if (s->src.state == PF_TCPS_PROXY_DST) {
1654                 /* XXX wire key the right one? */
1655                 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1656                     &s->key[PF_SK_WIRE]->addr[1],
1657                     &s->key[PF_SK_WIRE]->addr[0],
1658                     s->key[PF_SK_WIRE]->port[1],
1659                     s->key[PF_SK_WIRE]->port[0],
1660                     s->src.seqhi, s->src.seqlo + 1,
1661                     TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1662         }
1663
1664         LIST_REMOVE(s, entry);
1665         pf_src_tree_remove_state(s);
1666
1667         if (V_pfsync_delete_state_ptr != NULL)
1668                 V_pfsync_delete_state_ptr(s);
1669
1670         STATE_DEC_COUNTERS(s);
1671
1672         s->timeout = PFTM_UNLINKED;
1673
1674         PF_HASHROW_UNLOCK(ih);
1675
1676         pf_detach_state(s);
1677         refcount_release(&s->refs);
1678
1679         return (pf_release_state(s));
1680 }
1681
1682 void
1683 pf_free_state(struct pf_state *cur)
1684 {
1685
1686         KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1687         KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1688             cur->timeout));
1689
1690         pf_normalize_tcp_cleanup(cur);
1691         uma_zfree(V_pf_state_z, cur);
1692         counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1693 }
1694
1695 /*
1696  * Called only from pf_purge_thread(), thus serialized.
1697  */
1698 static u_int
1699 pf_purge_expired_states(u_int i, int maxcheck)
1700 {
1701         struct pf_idhash *ih;
1702         struct pf_state *s;
1703
1704         V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1705
1706         /*
1707          * Go through hash and unlink states that expire now.
1708          */
1709         while (maxcheck > 0) {
1710
1711                 ih = &V_pf_idhash[i];
1712
1713                 /* only take the lock if we expect to do work */
1714                 if (!LIST_EMPTY(&ih->states)) {
1715 relock:
1716                         PF_HASHROW_LOCK(ih);
1717                         LIST_FOREACH(s, &ih->states, entry) {
1718                                 if (pf_state_expires(s) <= time_uptime) {
1719                                         V_pf_status.states -=
1720                                             pf_unlink_state(s, PF_ENTER_LOCKED);
1721                                         goto relock;
1722                                 }
1723                                 s->rule.ptr->rule_flag |= PFRULE_REFS;
1724                                 if (s->nat_rule.ptr != NULL)
1725                                         s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1726                                 if (s->anchor.ptr != NULL)
1727                                         s->anchor.ptr->rule_flag |= PFRULE_REFS;
1728                                 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1729                                 if (s->rt_kif)
1730                                         s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1731                         }
1732                         PF_HASHROW_UNLOCK(ih);
1733                 }
1734
1735                 /* Return when we hit end of hash. */
1736                 if (++i > pf_hashmask) {
1737                         V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1738                         return (0);
1739                 }
1740
1741                 maxcheck--;
1742         }
1743
1744         V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1745
1746         return (i);
1747 }
1748
1749 static void
1750 pf_purge_unlinked_rules()
1751 {
1752         struct pf_rulequeue tmpq;
1753         struct pf_rule *r, *r1;
1754
1755         /*
1756          * If we have overloading task pending, then we'd
1757          * better skip purging this time. There is a tiny
1758          * probability that overloading task references
1759          * an already unlinked rule.
1760          */
1761         PF_OVERLOADQ_LOCK();
1762         if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1763                 PF_OVERLOADQ_UNLOCK();
1764                 return;
1765         }
1766         PF_OVERLOADQ_UNLOCK();
1767
1768         /*
1769          * Do naive mark-and-sweep garbage collecting of old rules.
1770          * Reference flag is raised by pf_purge_expired_states()
1771          * and pf_purge_expired_src_nodes().
1772          *
1773          * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1774          * use a temporary queue.
1775          */
1776         TAILQ_INIT(&tmpq);
1777         PF_UNLNKDRULES_LOCK();
1778         TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1779                 if (!(r->rule_flag & PFRULE_REFS)) {
1780                         TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1781                         TAILQ_INSERT_TAIL(&tmpq, r, entries);
1782                 } else
1783                         r->rule_flag &= ~PFRULE_REFS;
1784         }
1785         PF_UNLNKDRULES_UNLOCK();
1786
1787         if (!TAILQ_EMPTY(&tmpq)) {
1788                 PF_RULES_WLOCK();
1789                 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1790                         TAILQ_REMOVE(&tmpq, r, entries);
1791                         pf_free_rule(r);
1792                 }
1793                 PF_RULES_WUNLOCK();
1794         }
1795 }
1796
1797 void
1798 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1799 {
1800         switch (af) {
1801 #ifdef INET
1802         case AF_INET: {
1803                 u_int32_t a = ntohl(addr->addr32[0]);
1804                 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1805                     (a>>8)&255, a&255);
1806                 if (p) {
1807                         p = ntohs(p);
1808                         printf(":%u", p);
1809                 }
1810                 break;
1811         }
1812 #endif /* INET */
1813 #ifdef INET6
1814         case AF_INET6: {
1815                 u_int16_t b;
1816                 u_int8_t i, curstart, curend, maxstart, maxend;
1817                 curstart = curend = maxstart = maxend = 255;
1818                 for (i = 0; i < 8; i++) {
1819                         if (!addr->addr16[i]) {
1820                                 if (curstart == 255)
1821                                         curstart = i;
1822                                 curend = i;
1823                         } else {
1824                                 if ((curend - curstart) >
1825                                     (maxend - maxstart)) {
1826                                         maxstart = curstart;
1827                                         maxend = curend;
1828                                 }
1829                                 curstart = curend = 255;
1830                         }
1831                 }
1832                 if ((curend - curstart) >
1833                     (maxend - maxstart)) {
1834                         maxstart = curstart;
1835                         maxend = curend;
1836                 }
1837                 for (i = 0; i < 8; i++) {
1838                         if (i >= maxstart && i <= maxend) {
1839                                 if (i == 0)
1840                                         printf(":");
1841                                 if (i == maxend)
1842                                         printf(":");
1843                         } else {
1844                                 b = ntohs(addr->addr16[i]);
1845                                 printf("%x", b);
1846                                 if (i < 7)
1847                                         printf(":");
1848                         }
1849                 }
1850                 if (p) {
1851                         p = ntohs(p);
1852                         printf("[%u]", p);
1853                 }
1854                 break;
1855         }
1856 #endif /* INET6 */
1857         }
1858 }
1859
1860 void
1861 pf_print_state(struct pf_state *s)
1862 {
1863         pf_print_state_parts(s, NULL, NULL);
1864 }
1865
1866 static void
1867 pf_print_state_parts(struct pf_state *s,
1868     struct pf_state_key *skwp, struct pf_state_key *sksp)
1869 {
1870         struct pf_state_key *skw, *sks;
1871         u_int8_t proto, dir;
1872
1873         /* Do our best to fill these, but they're skipped if NULL */
1874         skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1875         sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1876         proto = skw ? skw->proto : (sks ? sks->proto : 0);
1877         dir = s ? s->direction : 0;
1878
1879         switch (proto) {
1880         case IPPROTO_IPV4:
1881                 printf("IPv4");
1882                 break;
1883         case IPPROTO_IPV6:
1884                 printf("IPv6");
1885                 break;
1886         case IPPROTO_TCP:
1887                 printf("TCP");
1888                 break;
1889         case IPPROTO_UDP:
1890                 printf("UDP");
1891                 break;
1892         case IPPROTO_ICMP:
1893                 printf("ICMP");
1894                 break;
1895         case IPPROTO_ICMPV6:
1896                 printf("ICMPv6");
1897                 break;
1898         default:
1899                 printf("%u", proto);
1900                 break;
1901         }
1902         switch (dir) {
1903         case PF_IN:
1904                 printf(" in");
1905                 break;
1906         case PF_OUT:
1907                 printf(" out");
1908                 break;
1909         }
1910         if (skw) {
1911                 printf(" wire: ");
1912                 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1913                 printf(" ");
1914                 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1915         }
1916         if (sks) {
1917                 printf(" stack: ");
1918                 if (sks != skw) {
1919                         pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1920                         printf(" ");
1921                         pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1922                 } else
1923                         printf("-");
1924         }
1925         if (s) {
1926                 if (proto == IPPROTO_TCP) {
1927                         printf(" [lo=%u high=%u win=%u modulator=%u",
1928                             s->src.seqlo, s->src.seqhi,
1929                             s->src.max_win, s->src.seqdiff);
1930                         if (s->src.wscale && s->dst.wscale)
1931                                 printf(" wscale=%u",
1932                                     s->src.wscale & PF_WSCALE_MASK);
1933                         printf("]");
1934                         printf(" [lo=%u high=%u win=%u modulator=%u",
1935                             s->dst.seqlo, s->dst.seqhi,
1936                             s->dst.max_win, s->dst.seqdiff);
1937                         if (s->src.wscale && s->dst.wscale)
1938                                 printf(" wscale=%u",
1939                                 s->dst.wscale & PF_WSCALE_MASK);
1940                         printf("]");
1941                 }
1942                 printf(" %u:%u", s->src.state, s->dst.state);
1943         }
1944 }
1945
1946 void
1947 pf_print_flags(u_int8_t f)
1948 {
1949         if (f)
1950                 printf(" ");
1951         if (f & TH_FIN)
1952                 printf("F");
1953         if (f & TH_SYN)
1954                 printf("S");
1955         if (f & TH_RST)
1956                 printf("R");
1957         if (f & TH_PUSH)
1958                 printf("P");
1959         if (f & TH_ACK)
1960                 printf("A");
1961         if (f & TH_URG)
1962                 printf("U");
1963         if (f & TH_ECE)
1964                 printf("E");
1965         if (f & TH_CWR)
1966                 printf("W");
1967 }
1968
1969 #define PF_SET_SKIP_STEPS(i)                                    \
1970         do {                                                    \
1971                 while (head[i] != cur) {                        \
1972                         head[i]->skip[i].ptr = cur;             \
1973                         head[i] = TAILQ_NEXT(head[i], entries); \
1974                 }                                               \
1975         } while (0)
1976
1977 void
1978 pf_calc_skip_steps(struct pf_rulequeue *rules)
1979 {
1980         struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1981         int i;
1982
1983         cur = TAILQ_FIRST(rules);
1984         prev = cur;
1985         for (i = 0; i < PF_SKIP_COUNT; ++i)
1986                 head[i] = cur;
1987         while (cur != NULL) {
1988
1989                 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1990                         PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1991                 if (cur->direction != prev->direction)
1992                         PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1993                 if (cur->af != prev->af)
1994                         PF_SET_SKIP_STEPS(PF_SKIP_AF);
1995                 if (cur->proto != prev->proto)
1996                         PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1997                 if (cur->src.neg != prev->src.neg ||
1998                     pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1999                         PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2000                 if (cur->src.port[0] != prev->src.port[0] ||
2001                     cur->src.port[1] != prev->src.port[1] ||
2002                     cur->src.port_op != prev->src.port_op)
2003                         PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2004                 if (cur->dst.neg != prev->dst.neg ||
2005                     pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2006                         PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2007                 if (cur->dst.port[0] != prev->dst.port[0] ||
2008                     cur->dst.port[1] != prev->dst.port[1] ||
2009                     cur->dst.port_op != prev->dst.port_op)
2010                         PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2011
2012                 prev = cur;
2013                 cur = TAILQ_NEXT(cur, entries);
2014         }
2015         for (i = 0; i < PF_SKIP_COUNT; ++i)
2016                 PF_SET_SKIP_STEPS(i);
2017 }
2018
2019 static int
2020 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2021 {
2022         if (aw1->type != aw2->type)
2023                 return (1);
2024         switch (aw1->type) {
2025         case PF_ADDR_ADDRMASK:
2026         case PF_ADDR_RANGE:
2027                 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2028                         return (1);
2029                 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2030                         return (1);
2031                 return (0);
2032         case PF_ADDR_DYNIFTL:
2033                 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2034         case PF_ADDR_NOROUTE:
2035         case PF_ADDR_URPFFAILED:
2036                 return (0);
2037         case PF_ADDR_TABLE:
2038                 return (aw1->p.tbl != aw2->p.tbl);
2039         default:
2040                 printf("invalid address type: %d\n", aw1->type);
2041                 return (1);
2042         }
2043 }
2044
2045 /**
2046  * Checksum updates are a little complicated because the checksum in the TCP/UDP
2047  * header isn't always a full checksum. In some cases (i.e. output) it's a
2048  * pseudo-header checksum, which is a partial checksum over src/dst IP
2049  * addresses, protocol number and length.
2050  *
2051  * That means we have the following cases:
2052  *  * Input or forwarding: we don't have TSO, the checksum fields are full
2053  *      checksums, we need to update the checksum whenever we change anything.
2054  *  * Output (i.e. the checksum is a pseudo-header checksum):
2055  *      x The field being updated is src/dst address or affects the length of
2056  *      the packet. We need to update the pseudo-header checksum (note that this
2057  *      checksum is not ones' complement).
2058  *      x Some other field is being modified (e.g. src/dst port numbers): We
2059  *      don't have to update anything.
2060  **/
2061 u_int16_t
2062 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2063 {
2064         u_int32_t       l;
2065
2066         if (udp && !cksum)
2067                 return (0x0000);
2068         l = cksum + old - new;
2069         l = (l >> 16) + (l & 65535);
2070         l = l & 65535;
2071         if (udp && !l)
2072                 return (0xFFFF);
2073         return (l);
2074 }
2075
2076 u_int16_t
2077 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2078         u_int16_t new, u_int8_t udp)
2079 {
2080         if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2081                 return (cksum);
2082
2083         return (pf_cksum_fixup(cksum, old, new, udp));
2084 }
2085
2086 static void
2087 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2088         u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2089         sa_family_t af)
2090 {
2091         struct pf_addr  ao;
2092         u_int16_t       po = *p;
2093
2094         PF_ACPY(&ao, a, af);
2095         PF_ACPY(a, an, af);
2096
2097         if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2098                 *pc = ~*pc;
2099
2100         *p = pn;
2101
2102         switch (af) {
2103 #ifdef INET
2104         case AF_INET:
2105                 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2106                     ao.addr16[0], an->addr16[0], 0),
2107                     ao.addr16[1], an->addr16[1], 0);
2108                 *p = pn;
2109
2110                 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2111                     ao.addr16[0], an->addr16[0], u),
2112                     ao.addr16[1], an->addr16[1], u);
2113
2114                 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2115                 break;
2116 #endif /* INET */
2117 #ifdef INET6
2118         case AF_INET6:
2119                 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2120                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2121                     pf_cksum_fixup(pf_cksum_fixup(*pc,
2122                     ao.addr16[0], an->addr16[0], u),
2123                     ao.addr16[1], an->addr16[1], u),
2124                     ao.addr16[2], an->addr16[2], u),
2125                     ao.addr16[3], an->addr16[3], u),
2126                     ao.addr16[4], an->addr16[4], u),
2127                     ao.addr16[5], an->addr16[5], u),
2128                     ao.addr16[6], an->addr16[6], u),
2129                     ao.addr16[7], an->addr16[7], u);
2130
2131                 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2132                 break;
2133 #endif /* INET6 */
2134         }
2135
2136         if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | 
2137             CSUM_DELAY_DATA_IPV6)) {
2138                 *pc = ~*pc;
2139                 if (! *pc)
2140                         *pc = 0xffff;
2141         }
2142 }
2143
2144 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
2145 void
2146 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2147 {
2148         u_int32_t       ao;
2149
2150         memcpy(&ao, a, sizeof(ao));
2151         memcpy(a, &an, sizeof(u_int32_t));
2152         *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2153             ao % 65536, an % 65536, u);
2154 }
2155
2156 void
2157 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2158 {
2159         u_int32_t       ao;
2160
2161         memcpy(&ao, a, sizeof(ao));
2162         memcpy(a, &an, sizeof(u_int32_t));
2163
2164         *c = pf_proto_cksum_fixup(m,
2165             pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2166             ao % 65536, an % 65536, udp);
2167 }
2168
2169 #ifdef INET6
2170 static void
2171 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2172 {
2173         struct pf_addr  ao;
2174
2175         PF_ACPY(&ao, a, AF_INET6);
2176         PF_ACPY(a, an, AF_INET6);
2177
2178         *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2179             pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2180             pf_cksum_fixup(pf_cksum_fixup(*c,
2181             ao.addr16[0], an->addr16[0], u),
2182             ao.addr16[1], an->addr16[1], u),
2183             ao.addr16[2], an->addr16[2], u),
2184             ao.addr16[3], an->addr16[3], u),
2185             ao.addr16[4], an->addr16[4], u),
2186             ao.addr16[5], an->addr16[5], u),
2187             ao.addr16[6], an->addr16[6], u),
2188             ao.addr16[7], an->addr16[7], u);
2189 }
2190 #endif /* INET6 */
2191
2192 static void
2193 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2194     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2195     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2196 {
2197         struct pf_addr  oia, ooa;
2198
2199         PF_ACPY(&oia, ia, af);
2200         if (oa)
2201                 PF_ACPY(&ooa, oa, af);
2202
2203         /* Change inner protocol port, fix inner protocol checksum. */
2204         if (ip != NULL) {
2205                 u_int16_t       oip = *ip;
2206                 u_int32_t       opc;
2207
2208                 if (pc != NULL)
2209                         opc = *pc;
2210                 *ip = np;
2211                 if (pc != NULL)
2212                         *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2213                 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2214                 if (pc != NULL)
2215                         *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2216         }
2217         /* Change inner ip address, fix inner ip and icmp checksums. */
2218         PF_ACPY(ia, na, af);
2219         switch (af) {
2220 #ifdef INET
2221         case AF_INET: {
2222                 u_int32_t        oh2c = *h2c;
2223
2224                 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2225                     oia.addr16[0], ia->addr16[0], 0),
2226                     oia.addr16[1], ia->addr16[1], 0);
2227                 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2228                     oia.addr16[0], ia->addr16[0], 0),
2229                     oia.addr16[1], ia->addr16[1], 0);
2230                 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2231                 break;
2232         }
2233 #endif /* INET */
2234 #ifdef INET6
2235         case AF_INET6:
2236                 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2237                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2238                     pf_cksum_fixup(pf_cksum_fixup(*ic,
2239                     oia.addr16[0], ia->addr16[0], u),
2240                     oia.addr16[1], ia->addr16[1], u),
2241                     oia.addr16[2], ia->addr16[2], u),
2242                     oia.addr16[3], ia->addr16[3], u),
2243                     oia.addr16[4], ia->addr16[4], u),
2244                     oia.addr16[5], ia->addr16[5], u),
2245                     oia.addr16[6], ia->addr16[6], u),
2246                     oia.addr16[7], ia->addr16[7], u);
2247                 break;
2248 #endif /* INET6 */
2249         }
2250         /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2251         if (oa) {
2252                 PF_ACPY(oa, na, af);
2253                 switch (af) {
2254 #ifdef INET
2255                 case AF_INET:
2256                         *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2257                             ooa.addr16[0], oa->addr16[0], 0),
2258                             ooa.addr16[1], oa->addr16[1], 0);
2259                         break;
2260 #endif /* INET */
2261 #ifdef INET6
2262                 case AF_INET6:
2263                         *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2264                             pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2265                             pf_cksum_fixup(pf_cksum_fixup(*ic,
2266                             ooa.addr16[0], oa->addr16[0], u),
2267                             ooa.addr16[1], oa->addr16[1], u),
2268                             ooa.addr16[2], oa->addr16[2], u),
2269                             ooa.addr16[3], oa->addr16[3], u),
2270                             ooa.addr16[4], oa->addr16[4], u),
2271                             ooa.addr16[5], oa->addr16[5], u),
2272                             ooa.addr16[6], oa->addr16[6], u),
2273                             ooa.addr16[7], oa->addr16[7], u);
2274                         break;
2275 #endif /* INET6 */
2276                 }
2277         }
2278 }
2279
2280
2281 /*
2282  * Need to modulate the sequence numbers in the TCP SACK option
2283  * (credits to Krzysztof Pfaff for report and patch)
2284  */
2285 static int
2286 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2287     struct tcphdr *th, struct pf_state_peer *dst)
2288 {
2289         int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2290         u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2291         int copyback = 0, i, olen;
2292         struct sackblk sack;
2293
2294 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2295         if (hlen < TCPOLEN_SACKLEN ||
2296             !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2297                 return 0;
2298
2299         while (hlen >= TCPOLEN_SACKLEN) {
2300                 olen = opt[1];
2301                 switch (*opt) {
2302                 case TCPOPT_EOL:        /* FALLTHROUGH */
2303                 case TCPOPT_NOP:
2304                         opt++;
2305                         hlen--;
2306                         break;
2307                 case TCPOPT_SACK:
2308                         if (olen > hlen)
2309                                 olen = hlen;
2310                         if (olen >= TCPOLEN_SACKLEN) {
2311                                 for (i = 2; i + TCPOLEN_SACK <= olen;
2312                                     i += TCPOLEN_SACK) {
2313                                         memcpy(&sack, &opt[i], sizeof(sack));
2314                                         pf_change_proto_a(m, &sack.start, &th->th_sum,
2315                                             htonl(ntohl(sack.start) - dst->seqdiff), 0);
2316                                         pf_change_proto_a(m, &sack.end, &th->th_sum,
2317                                             htonl(ntohl(sack.end) - dst->seqdiff), 0);
2318                                         memcpy(&opt[i], &sack, sizeof(sack));
2319                                 }
2320                                 copyback = 1;
2321                         }
2322                         /* FALLTHROUGH */
2323                 default:
2324                         if (olen < 2)
2325                                 olen = 2;
2326                         hlen -= olen;
2327                         opt += olen;
2328                 }
2329         }
2330
2331         if (copyback)
2332                 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2333         return (copyback);
2334 }
2335
2336 static void
2337 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2338     const struct pf_addr *saddr, const struct pf_addr *daddr,
2339     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2340     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2341     u_int16_t rtag, struct ifnet *ifp)
2342 {
2343         struct pf_send_entry *pfse;
2344         struct mbuf     *m;
2345         int              len, tlen;
2346 #ifdef INET
2347         struct ip       *h = NULL;
2348 #endif /* INET */
2349 #ifdef INET6
2350         struct ip6_hdr  *h6 = NULL;
2351 #endif /* INET6 */
2352         struct tcphdr   *th;
2353         char            *opt;
2354         struct pf_mtag  *pf_mtag;
2355
2356         len = 0;
2357         th = NULL;
2358
2359         /* maximum segment size tcp option */
2360         tlen = sizeof(struct tcphdr);
2361         if (mss)
2362                 tlen += 4;
2363
2364         switch (af) {
2365 #ifdef INET
2366         case AF_INET:
2367                 len = sizeof(struct ip) + tlen;
2368                 break;
2369 #endif /* INET */
2370 #ifdef INET6
2371         case AF_INET6:
2372                 len = sizeof(struct ip6_hdr) + tlen;
2373                 break;
2374 #endif /* INET6 */
2375         default:
2376                 panic("%s: unsupported af %d", __func__, af);
2377         }
2378
2379         /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2380         pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2381         if (pfse == NULL)
2382                 return;
2383         m = m_gethdr(M_NOWAIT, MT_DATA);
2384         if (m == NULL) {
2385                 free(pfse, M_PFTEMP);
2386                 return;
2387         }
2388 #ifdef MAC
2389         mac_netinet_firewall_send(m);
2390 #endif
2391         if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2392                 free(pfse, M_PFTEMP);
2393                 m_freem(m);
2394                 return;
2395         }
2396         if (tag)
2397                 m->m_flags |= M_SKIP_FIREWALL;
2398         pf_mtag->tag = rtag;
2399
2400         if (r != NULL && r->rtableid >= 0)
2401                 M_SETFIB(m, r->rtableid);
2402
2403 #ifdef ALTQ
2404         if (r != NULL && r->qid) {
2405                 pf_mtag->qid = r->qid;
2406
2407                 /* add hints for ecn */
2408                 pf_mtag->hdr = mtod(m, struct ip *);
2409         }
2410 #endif /* ALTQ */
2411         m->m_data += max_linkhdr;
2412         m->m_pkthdr.len = m->m_len = len;
2413         m->m_pkthdr.rcvif = NULL;
2414         bzero(m->m_data, len);
2415         switch (af) {
2416 #ifdef INET
2417         case AF_INET:
2418                 h = mtod(m, struct ip *);
2419
2420                 /* IP header fields included in the TCP checksum */
2421                 h->ip_p = IPPROTO_TCP;
2422                 h->ip_len = htons(tlen);
2423                 h->ip_src.s_addr = saddr->v4.s_addr;
2424                 h->ip_dst.s_addr = daddr->v4.s_addr;
2425
2426                 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2427                 break;
2428 #endif /* INET */
2429 #ifdef INET6
2430         case AF_INET6:
2431                 h6 = mtod(m, struct ip6_hdr *);
2432
2433                 /* IP header fields included in the TCP checksum */
2434                 h6->ip6_nxt = IPPROTO_TCP;
2435                 h6->ip6_plen = htons(tlen);
2436                 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2437                 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2438
2439                 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2440                 break;
2441 #endif /* INET6 */
2442         }
2443
2444         /* TCP header */
2445         th->th_sport = sport;
2446         th->th_dport = dport;
2447         th->th_seq = htonl(seq);
2448         th->th_ack = htonl(ack);
2449         th->th_off = tlen >> 2;
2450         th->th_flags = flags;
2451         th->th_win = htons(win);
2452
2453         if (mss) {
2454                 opt = (char *)(th + 1);
2455                 opt[0] = TCPOPT_MAXSEG;
2456                 opt[1] = 4;
2457                 HTONS(mss);
2458                 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2459         }
2460
2461         switch (af) {
2462 #ifdef INET
2463         case AF_INET:
2464                 /* TCP checksum */
2465                 th->th_sum = in_cksum(m, len);
2466
2467                 /* Finish the IP header */
2468                 h->ip_v = 4;
2469                 h->ip_hl = sizeof(*h) >> 2;
2470                 h->ip_tos = IPTOS_LOWDELAY;
2471                 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2472                 h->ip_len = htons(len);
2473                 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2474                 h->ip_sum = 0;
2475
2476                 pfse->pfse_type = PFSE_IP;
2477                 break;
2478 #endif /* INET */
2479 #ifdef INET6
2480         case AF_INET6:
2481                 /* TCP checksum */
2482                 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2483                     sizeof(struct ip6_hdr), tlen);
2484
2485                 h6->ip6_vfc |= IPV6_VERSION;
2486                 h6->ip6_hlim = IPV6_DEFHLIM;
2487
2488                 pfse->pfse_type = PFSE_IP6;
2489                 break;
2490 #endif /* INET6 */
2491         }
2492         pfse->pfse_m = m;
2493         pf_send(pfse);
2494 }
2495
2496 static void
2497 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2498     struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2499     struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2500     u_short *reason)
2501 {
2502         struct pf_addr  * const saddr = pd->src;
2503         struct pf_addr  * const daddr = pd->dst;
2504         sa_family_t      af = pd->af;
2505
2506         /* undo NAT changes, if they have taken place */
2507         if (nr != NULL) {
2508                 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2509                 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2510                 if (pd->sport)
2511                         *pd->sport = sk->port[pd->sidx];
2512                 if (pd->dport)
2513                         *pd->dport = sk->port[pd->didx];
2514                 if (pd->proto_sum)
2515                         *pd->proto_sum = bproto_sum;
2516                 if (pd->ip_sum)
2517                         *pd->ip_sum = bip_sum;
2518                 m_copyback(m, off, hdrlen, pd->hdr.any);
2519         }
2520         if (pd->proto == IPPROTO_TCP &&
2521             ((r->rule_flag & PFRULE_RETURNRST) ||
2522             (r->rule_flag & PFRULE_RETURN)) &&
2523             !(th->th_flags & TH_RST)) {
2524                 u_int32_t        ack = ntohl(th->th_seq) + pd->p_len;
2525                 int              len = 0;
2526 #ifdef INET
2527                 struct ip       *h4;
2528 #endif
2529 #ifdef INET6
2530                 struct ip6_hdr  *h6;
2531 #endif
2532
2533                 switch (af) {
2534 #ifdef INET
2535                 case AF_INET:
2536                         h4 = mtod(m, struct ip *);
2537                         len = ntohs(h4->ip_len) - off;
2538                         break;
2539 #endif
2540 #ifdef INET6
2541                 case AF_INET6:
2542                         h6 = mtod(m, struct ip6_hdr *);
2543                         len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2544                         break;
2545 #endif
2546                 }
2547
2548                 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2549                         REASON_SET(reason, PFRES_PROTCKSUM);
2550                 else {
2551                         if (th->th_flags & TH_SYN)
2552                                 ack++;
2553                         if (th->th_flags & TH_FIN)
2554                                 ack++;
2555                         pf_send_tcp(m, r, af, pd->dst,
2556                                 pd->src, th->th_dport, th->th_sport,
2557                                 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2558                                 r->return_ttl, 1, 0, kif->pfik_ifp);
2559                 }
2560         } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2561                 r->return_icmp)
2562                 pf_send_icmp(m, r->return_icmp >> 8,
2563                         r->return_icmp & 255, af, r);
2564         else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2565                 r->return_icmp6)
2566                 pf_send_icmp(m, r->return_icmp6 >> 8,
2567                         r->return_icmp6 & 255, af, r);
2568 }
2569
2570
2571 static int
2572 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2573 {
2574         struct m_tag *mtag;
2575
2576         KASSERT(prio <= PF_PRIO_MAX,
2577             ("%s with invalid pcp", __func__));
2578
2579         mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2580         if (mtag == NULL) {
2581                 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2582                     sizeof(uint8_t), M_NOWAIT);
2583                 if (mtag == NULL)
2584                         return (ENOMEM);
2585                 m_tag_prepend(m, mtag);
2586         }
2587
2588         *(uint8_t *)(mtag + 1) = prio;
2589         return (0);
2590 }
2591
2592 static int
2593 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2594 {
2595         struct m_tag *mtag;
2596         u_int8_t mpcp;
2597
2598         mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2599         if (mtag == NULL)
2600                 return (0);
2601
2602         if (prio == PF_PRIO_ZERO)
2603                 prio = 0;
2604
2605         mpcp = *(uint8_t *)(mtag + 1);
2606
2607         return (mpcp == prio);
2608 }
2609
2610 static void
2611 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2612     struct pf_rule *r)
2613 {
2614         struct pf_send_entry *pfse;
2615         struct mbuf *m0;
2616         struct pf_mtag *pf_mtag;
2617
2618         /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2619         pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2620         if (pfse == NULL)
2621                 return;
2622
2623         if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2624                 free(pfse, M_PFTEMP);
2625                 return;
2626         }
2627
2628         if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2629                 free(pfse, M_PFTEMP);
2630                 return;
2631         }
2632         /* XXX: revisit */
2633         m0->m_flags |= M_SKIP_FIREWALL;
2634
2635         if (r->rtableid >= 0)
2636                 M_SETFIB(m0, r->rtableid);
2637
2638 #ifdef ALTQ
2639         if (r->qid) {
2640                 pf_mtag->qid = r->qid;
2641                 /* add hints for ecn */
2642                 pf_mtag->hdr = mtod(m0, struct ip *);
2643         }
2644 #endif /* ALTQ */
2645
2646         switch (af) {
2647 #ifdef INET
2648         case AF_INET:
2649                 pfse->pfse_type = PFSE_ICMP;
2650                 break;
2651 #endif /* INET */
2652 #ifdef INET6
2653         case AF_INET6:
2654                 pfse->pfse_type = PFSE_ICMP6;
2655                 break;
2656 #endif /* INET6 */
2657         }
2658         pfse->pfse_m = m0;
2659         pfse->icmpopts.type = type;
2660         pfse->icmpopts.code = code;
2661         pf_send(pfse);
2662 }
2663
2664 /*
2665  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2666  * If n is 0, they match if they are equal. If n is != 0, they match if they
2667  * are different.
2668  */
2669 int
2670 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2671     struct pf_addr *b, sa_family_t af)
2672 {
2673         int     match = 0;
2674
2675         switch (af) {
2676 #ifdef INET
2677         case AF_INET:
2678                 if ((a->addr32[0] & m->addr32[0]) ==
2679                     (b->addr32[0] & m->addr32[0]))
2680                         match++;
2681                 break;
2682 #endif /* INET */
2683 #ifdef INET6
2684         case AF_INET6:
2685                 if (((a->addr32[0] & m->addr32[0]) ==
2686                      (b->addr32[0] & m->addr32[0])) &&
2687                     ((a->addr32[1] & m->addr32[1]) ==
2688                      (b->addr32[1] & m->addr32[1])) &&
2689                     ((a->addr32[2] & m->addr32[2]) ==
2690                      (b->addr32[2] & m->addr32[2])) &&
2691                     ((a->addr32[3] & m->addr32[3]) ==
2692                      (b->addr32[3] & m->addr32[3])))
2693                         match++;
2694                 break;
2695 #endif /* INET6 */
2696         }
2697         if (match) {
2698                 if (n)
2699                         return (0);
2700                 else
2701                         return (1);
2702         } else {
2703                 if (n)
2704                         return (1);
2705                 else
2706                         return (0);
2707         }
2708 }
2709
2710 /*
2711  * Return 1 if b <= a <= e, otherwise return 0.
2712  */
2713 int
2714 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2715     struct pf_addr *a, sa_family_t af)
2716 {
2717         switch (af) {
2718 #ifdef INET
2719         case AF_INET:
2720                 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2721                     (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2722                         return (0);
2723                 break;
2724 #endif /* INET */
2725 #ifdef INET6
2726         case AF_INET6: {
2727                 int     i;
2728
2729                 /* check a >= b */
2730                 for (i = 0; i < 4; ++i)
2731                         if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2732                                 break;
2733                         else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2734                                 return (0);
2735                 /* check a <= e */
2736                 for (i = 0; i < 4; ++i)
2737                         if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2738                                 break;
2739                         else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2740                                 return (0);
2741                 break;
2742         }
2743 #endif /* INET6 */
2744         }
2745         return (1);
2746 }
2747
2748 static int
2749 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2750 {
2751         switch (op) {
2752         case PF_OP_IRG:
2753                 return ((p > a1) && (p < a2));
2754         case PF_OP_XRG:
2755                 return ((p < a1) || (p > a2));
2756         case PF_OP_RRG:
2757                 return ((p >= a1) && (p <= a2));
2758         case PF_OP_EQ:
2759                 return (p == a1);
2760         case PF_OP_NE:
2761                 return (p != a1);
2762         case PF_OP_LT:
2763                 return (p < a1);
2764         case PF_OP_LE:
2765                 return (p <= a1);
2766         case PF_OP_GT:
2767                 return (p > a1);
2768         case PF_OP_GE:
2769                 return (p >= a1);
2770         }
2771         return (0); /* never reached */
2772 }
2773
2774 int
2775 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2776 {
2777         NTOHS(a1);
2778         NTOHS(a2);
2779         NTOHS(p);
2780         return (pf_match(op, a1, a2, p));
2781 }
2782
2783 static int
2784 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2785 {
2786         if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2787                 return (0);
2788         return (pf_match(op, a1, a2, u));
2789 }
2790
2791 static int
2792 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2793 {
2794         if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2795                 return (0);
2796         return (pf_match(op, a1, a2, g));
2797 }
2798
2799 int
2800 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2801 {
2802         if (*tag == -1)
2803                 *tag = mtag;
2804
2805         return ((!r->match_tag_not && r->match_tag == *tag) ||
2806             (r->match_tag_not && r->match_tag != *tag));
2807 }
2808
2809 int
2810 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2811 {
2812
2813         KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2814
2815         if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2816                 return (ENOMEM);
2817
2818         pd->pf_mtag->tag = tag;
2819
2820         return (0);
2821 }
2822
2823 #define PF_ANCHOR_STACKSIZE     32
2824 struct pf_anchor_stackframe {
2825         struct pf_ruleset       *rs;
2826         struct pf_rule          *r;     /* XXX: + match bit */
2827         struct pf_anchor        *child;
2828 };
2829
2830 /*
2831  * XXX: We rely on malloc(9) returning pointer aligned addresses.
2832  */
2833 #define PF_ANCHORSTACK_MATCH    0x00000001
2834 #define PF_ANCHORSTACK_MASK     (PF_ANCHORSTACK_MATCH)
2835
2836 #define PF_ANCHOR_MATCH(f)      ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2837 #define PF_ANCHOR_RULE(f)       (struct pf_rule *)                      \
2838                                 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2839 #define PF_ANCHOR_SET_MATCH(f)  do { (f)->r = (void *)                  \
2840                                 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH);  \
2841 } while (0)
2842
2843 void
2844 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2845     struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2846     int *match)
2847 {
2848         struct pf_anchor_stackframe     *f;
2849
2850         PF_RULES_RASSERT();
2851
2852         if (match)
2853                 *match = 0;
2854         if (*depth >= PF_ANCHOR_STACKSIZE) {
2855                 printf("%s: anchor stack overflow on %s\n",
2856                     __func__, (*r)->anchor->name);
2857                 *r = TAILQ_NEXT(*r, entries);
2858                 return;
2859         } else if (*depth == 0 && a != NULL)
2860                 *a = *r;
2861         f = stack + (*depth)++;
2862         f->rs = *rs;
2863         f->r = *r;
2864         if ((*r)->anchor_wildcard) {
2865                 struct pf_anchor_node *parent = &(*r)->anchor->children;
2866
2867                 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2868                         *r = NULL;
2869                         return;
2870                 }
2871                 *rs = &f->child->ruleset;
2872         } else {
2873                 f->child = NULL;
2874                 *rs = &(*r)->anchor->ruleset;
2875         }
2876         *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2877 }
2878
2879 int
2880 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2881     struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2882     int *match)
2883 {
2884         struct pf_anchor_stackframe     *f;
2885         struct pf_rule *fr;
2886         int quick = 0;
2887
2888         PF_RULES_RASSERT();
2889
2890         do {
2891                 if (*depth <= 0)
2892                         break;
2893                 f = stack + *depth - 1;
2894                 fr = PF_ANCHOR_RULE(f);
2895                 if (f->child != NULL) {
2896                         struct pf_anchor_node *parent;
2897
2898                         /*
2899                          * This block traverses through
2900                          * a wildcard anchor.
2901                          */
2902                         parent = &fr->anchor->children;
2903                         if (match != NULL && *match) {
2904                                 /*
2905                                  * If any of "*" matched, then
2906                                  * "foo/ *" matched, mark frame
2907                                  * appropriately.
2908                                  */
2909                                 PF_ANCHOR_SET_MATCH(f);
2910                                 *match = 0;
2911                         }
2912                         f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2913                         if (f->child != NULL) {
2914                                 *rs = &f->child->ruleset;
2915                                 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2916                                 if (*r == NULL)
2917                                         continue;
2918                                 else
2919                                         break;
2920                         }
2921                 }
2922                 (*depth)--;
2923                 if (*depth == 0 && a != NULL)
2924                         *a = NULL;
2925                 *rs = f->rs;
2926                 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2927                         quick = fr->quick;
2928                 *r = TAILQ_NEXT(fr, entries);
2929         } while (*r == NULL);
2930
2931         return (quick);
2932 }
2933
2934 #ifdef INET6
2935 void
2936 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2937     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2938 {
2939         switch (af) {
2940 #ifdef INET
2941         case AF_INET:
2942                 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2943                 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2944                 break;
2945 #endif /* INET */
2946         case AF_INET6:
2947                 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2948                 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2949                 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2950                 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2951                 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2952                 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2953                 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2954                 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2955                 break;
2956         }
2957 }
2958
2959 void
2960 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2961 {
2962         switch (af) {
2963 #ifdef INET
2964         case AF_INET:
2965                 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2966                 break;
2967 #endif /* INET */
2968         case AF_INET6:
2969                 if (addr->addr32[3] == 0xffffffff) {
2970                         addr->addr32[3] = 0;
2971                         if (addr->addr32[2] == 0xffffffff) {
2972                                 addr->addr32[2] = 0;
2973                                 if (addr->addr32[1] == 0xffffffff) {
2974                                         addr->addr32[1] = 0;
2975                                         addr->addr32[0] =
2976                                             htonl(ntohl(addr->addr32[0]) + 1);
2977                                 } else
2978                                         addr->addr32[1] =
2979                                             htonl(ntohl(addr->addr32[1]) + 1);
2980                         } else
2981                                 addr->addr32[2] =
2982                                     htonl(ntohl(addr->addr32[2]) + 1);
2983                 } else
2984                         addr->addr32[3] =
2985                             htonl(ntohl(addr->addr32[3]) + 1);
2986                 break;
2987         }
2988 }
2989 #endif /* INET6 */
2990
2991 int
2992 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2993 {
2994         struct pf_addr          *saddr, *daddr;
2995         u_int16_t                sport, dport;
2996         struct inpcbinfo        *pi;
2997         struct inpcb            *inp;
2998
2999         pd->lookup.uid = UID_MAX;
3000         pd->lookup.gid = GID_MAX;
3001
3002         switch (pd->proto) {
3003         case IPPROTO_TCP:
3004                 if (pd->hdr.tcp == NULL)
3005                         return (-1);
3006                 sport = pd->hdr.tcp->th_sport;
3007                 dport = pd->hdr.tcp->th_dport;
3008                 pi = &V_tcbinfo;
3009                 break;
3010         case IPPROTO_UDP:
3011                 if (pd->hdr.udp == NULL)
3012                         return (-1);
3013                 sport = pd->hdr.udp->uh_sport;
3014                 dport = pd->hdr.udp->uh_dport;
3015                 pi = &V_udbinfo;
3016                 break;
3017         default:
3018                 return (-1);
3019         }
3020         if (direction == PF_IN) {
3021                 saddr = pd->src;
3022                 daddr = pd->dst;
3023         } else {
3024                 u_int16_t       p;
3025
3026                 p = sport;
3027                 sport = dport;
3028                 dport = p;
3029                 saddr = pd->dst;
3030                 daddr = pd->src;
3031         }
3032         switch (pd->af) {
3033 #ifdef INET
3034         case AF_INET:
3035                 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3036                     dport, INPLOOKUP_RLOCKPCB, NULL, m);
3037                 if (inp == NULL) {
3038                         inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3039                            daddr->v4, dport, INPLOOKUP_WILDCARD |
3040                            INPLOOKUP_RLOCKPCB, NULL, m);
3041                         if (inp == NULL)
3042                                 return (-1);
3043                 }
3044                 break;
3045 #endif /* INET */
3046 #ifdef INET6
3047         case AF_INET6:
3048                 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3049                     dport, INPLOOKUP_RLOCKPCB, NULL, m);
3050                 if (inp == NULL) {
3051                         inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3052                             &daddr->v6, dport, INPLOOKUP_WILDCARD |
3053                             INPLOOKUP_RLOCKPCB, NULL, m);
3054                         if (inp == NULL)
3055                                 return (-1);
3056                 }
3057                 break;
3058 #endif /* INET6 */
3059
3060         default:
3061                 return (-1);
3062         }
3063         INP_RLOCK_ASSERT(inp);
3064         pd->lookup.uid = inp->inp_cred->cr_uid;
3065         pd->lookup.gid = inp->inp_cred->cr_groups[0];
3066         INP_RUNLOCK(inp);
3067
3068         return (1);
3069 }
3070
3071 static u_int8_t
3072 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3073 {
3074         int              hlen;
3075         u_int8_t         hdr[60];
3076         u_int8_t        *opt, optlen;
3077         u_int8_t         wscale = 0;
3078
3079         hlen = th_off << 2;             /* hlen <= sizeof(hdr) */
3080         if (hlen <= sizeof(struct tcphdr))
3081                 return (0);
3082         if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3083                 return (0);
3084         opt = hdr + sizeof(struct tcphdr);
3085         hlen -= sizeof(struct tcphdr);
3086         while (hlen >= 3) {
3087                 switch (*opt) {
3088                 case TCPOPT_EOL:
3089                 case TCPOPT_NOP:
3090                         ++opt;
3091                         --hlen;
3092                         break;
3093                 case TCPOPT_WINDOW:
3094                         wscale = opt[2];
3095                         if (wscale > TCP_MAX_WINSHIFT)
3096                                 wscale = TCP_MAX_WINSHIFT;
3097                         wscale |= PF_WSCALE_FLAG;
3098                         /* FALLTHROUGH */
3099                 default:
3100                         optlen = opt[1];
3101                         if (optlen < 2)
3102                                 optlen = 2;
3103                         hlen -= optlen;
3104                         opt += optlen;
3105                         break;
3106                 }
3107         }
3108         return (wscale);
3109 }
3110
3111 static u_int16_t
3112 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3113 {
3114         int              hlen;
3115         u_int8_t         hdr[60];
3116         u_int8_t        *opt, optlen;
3117         u_int16_t        mss = V_tcp_mssdflt;
3118
3119         hlen = th_off << 2;     /* hlen <= sizeof(hdr) */
3120         if (hlen <= sizeof(struct tcphdr))
3121                 return (0);
3122         if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3123                 return (0);
3124         opt = hdr + sizeof(struct tcphdr);
3125         hlen -= sizeof(struct tcphdr);
3126         while (hlen >= TCPOLEN_MAXSEG) {
3127                 switch (*opt) {
3128                 case TCPOPT_EOL:
3129                 case TCPOPT_NOP:
3130                         ++opt;
3131                         --hlen;
3132                         break;
3133                 case TCPOPT_MAXSEG:
3134                         bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3135                         NTOHS(mss);
3136                         /* FALLTHROUGH */
3137                 default:
3138                         optlen = opt[1];
3139                         if (optlen < 2)
3140                                 optlen = 2;
3141                         hlen -= optlen;
3142                         opt += optlen;
3143                         break;
3144                 }
3145         }
3146         return (mss);
3147 }
3148
3149 static u_int16_t
3150 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3151 {
3152 #ifdef INET
3153         struct nhop4_basic      nh4;
3154 #endif /* INET */
3155 #ifdef INET6
3156         struct nhop6_basic      nh6;
3157         struct in6_addr         dst6;
3158         uint32_t                scopeid;
3159 #endif /* INET6 */
3160         int                      hlen = 0;
3161         uint16_t                 mss = 0;
3162
3163         switch (af) {
3164 #ifdef INET
3165         case AF_INET:
3166                 hlen = sizeof(struct ip);
3167                 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3168                         mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3169                 break;
3170 #endif /* INET */
3171 #ifdef INET6
3172         case AF_INET6:
3173                 hlen = sizeof(struct ip6_hdr);
3174                 in6_splitscope(&addr->v6, &dst6, &scopeid);
3175                 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3176                         mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3177                 break;
3178 #endif /* INET6 */
3179         }
3180
3181         mss = max(V_tcp_mssdflt, mss);
3182         mss = min(mss, offer);
3183         mss = max(mss, 64);             /* sanity - at least max opt space */
3184         return (mss);
3185 }
3186
3187 static u_int32_t
3188 pf_tcp_iss(struct pf_pdesc *pd)
3189 {
3190         MD5_CTX ctx;
3191         u_int32_t digest[4];
3192
3193         if (V_pf_tcp_secret_init == 0) {
3194                 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3195                 MD5Init(&V_pf_tcp_secret_ctx);
3196                 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3197                     sizeof(V_pf_tcp_secret));
3198                 V_pf_tcp_secret_init = 1;
3199         }
3200
3201         ctx = V_pf_tcp_secret_ctx;
3202
3203         MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3204         MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3205         if (pd->af == AF_INET6) {
3206                 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3207                 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3208         } else {
3209                 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3210                 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3211         }
3212         MD5Final((u_char *)digest, &ctx);
3213         V_pf_tcp_iss_off += 4096;
3214 #define ISN_RANDOM_INCREMENT (4096 - 1)
3215         return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3216             V_pf_tcp_iss_off);
3217 #undef  ISN_RANDOM_INCREMENT
3218 }
3219
3220 static int
3221 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3222     struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3223     struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3224 {
3225         struct pf_rule          *nr = NULL;
3226         struct pf_addr          * const saddr = pd->src;
3227         struct pf_addr          * const daddr = pd->dst;
3228         sa_family_t              af = pd->af;
3229         struct pf_rule          *r, *a = NULL;
3230         struct pf_ruleset       *ruleset = NULL;
3231         struct pf_src_node      *nsn = NULL;
3232         struct tcphdr           *th = pd->hdr.tcp;
3233         struct pf_state_key     *sk = NULL, *nk = NULL;
3234         u_short                  reason;
3235         int                      rewrite = 0, hdrlen = 0;
3236         int                      tag = -1, rtableid = -1;
3237         int                      asd = 0;
3238         int                      match = 0;
3239         int                      state_icmp = 0;
3240         u_int16_t                sport = 0, dport = 0;
3241         u_int16_t                bproto_sum = 0, bip_sum = 0;
3242         u_int8_t                 icmptype = 0, icmpcode = 0;
3243         struct pf_anchor_stackframe     anchor_stack[PF_ANCHOR_STACKSIZE];
3244
3245         PF_RULES_RASSERT();
3246
3247         if (inp != NULL) {
3248                 INP_LOCK_ASSERT(inp);
3249                 pd->lookup.uid = inp->inp_cred->cr_uid;
3250                 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3251                 pd->lookup.done = 1;
3252         }
3253
3254         switch (pd->proto) {
3255         case IPPROTO_TCP:
3256                 sport = th->th_sport;
3257                 dport = th->th_dport;
3258                 hdrlen = sizeof(*th);
3259                 break;
3260         case IPPROTO_UDP:
3261                 sport = pd->hdr.udp->uh_sport;
3262                 dport = pd->hdr.udp->uh_dport;
3263                 hdrlen = sizeof(*pd->hdr.udp);
3264                 break;
3265 #ifdef INET
3266         case IPPROTO_ICMP:
3267                 if (pd->af != AF_INET)
3268                         break;
3269                 sport = dport = pd->hdr.icmp->icmp_id;
3270                 hdrlen = sizeof(*pd->hdr.icmp);
3271                 icmptype = pd->hdr.icmp->icmp_type;
3272                 icmpcode = pd->hdr.icmp->icmp_code;
3273
3274                 if (icmptype == ICMP_UNREACH ||
3275                     icmptype == ICMP_SOURCEQUENCH ||
3276                     icmptype == ICMP_REDIRECT ||
3277                     icmptype == ICMP_TIMXCEED ||
3278                     icmptype == ICMP_PARAMPROB)
3279                         state_icmp++;
3280                 break;
3281 #endif /* INET */
3282 #ifdef INET6
3283         case IPPROTO_ICMPV6:
3284                 if (af != AF_INET6)
3285                         break;
3286                 sport = dport = pd->hdr.icmp6->icmp6_id;
3287                 hdrlen = sizeof(*pd->hdr.icmp6);
3288                 icmptype = pd->hdr.icmp6->icmp6_type;
3289                 icmpcode = pd->hdr.icmp6->icmp6_code;
3290
3291                 if (icmptype == ICMP6_DST_UNREACH ||
3292                     icmptype == ICMP6_PACKET_TOO_BIG ||
3293                     icmptype == ICMP6_TIME_EXCEEDED ||
3294                     icmptype == ICMP6_PARAM_PROB)
3295                         state_icmp++;
3296                 break;
3297 #endif /* INET6 */
3298         default:
3299                 sport = dport = hdrlen = 0;
3300                 break;
3301         }
3302
3303         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3304
3305         /* check packet for BINAT/NAT/RDR */
3306         if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3307             &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3308                 KASSERT(sk != NULL, ("%s: null sk", __func__));
3309                 KASSERT(nk != NULL, ("%s: null nk", __func__));
3310
3311                 if (pd->ip_sum)
3312                         bip_sum = *pd->ip_sum;
3313
3314                 switch (pd->proto) {
3315                 case IPPROTO_TCP:
3316                         bproto_sum = th->th_sum;
3317                         pd->proto_sum = &th->th_sum;
3318
3319                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3320                             nk->port[pd->sidx] != sport) {
3321                                 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3322                                     &th->th_sum, &nk->addr[pd->sidx],
3323                                     nk->port[pd->sidx], 0, af);
3324                                 pd->sport = &th->th_sport;
3325                                 sport = th->th_sport;
3326                         }
3327
3328                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3329                             nk->port[pd->didx] != dport) {
3330                                 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3331                                     &th->th_sum, &nk->addr[pd->didx],
3332                                     nk->port[pd->didx], 0, af);
3333                                 dport = th->th_dport;
3334                                 pd->dport = &th->th_dport;
3335                         }
3336                         rewrite++;
3337                         break;
3338                 case IPPROTO_UDP:
3339                         bproto_sum = pd->hdr.udp->uh_sum;
3340                         pd->proto_sum = &pd->hdr.udp->uh_sum;
3341
3342                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3343                             nk->port[pd->sidx] != sport) {
3344                                 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3345                                     pd->ip_sum, &pd->hdr.udp->uh_sum,
3346                                     &nk->addr[pd->sidx],
3347                                     nk->port[pd->sidx], 1, af);
3348                                 sport = pd->hdr.udp->uh_sport;
3349                                 pd->sport = &pd->hdr.udp->uh_sport;
3350                         }
3351
3352                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3353                             nk->port[pd->didx] != dport) {
3354                                 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3355                                     pd->ip_sum, &pd->hdr.udp->uh_sum,
3356                                     &nk->addr[pd->didx],
3357                                     nk->port[pd->didx], 1, af);
3358                                 dport = pd->hdr.udp->uh_dport;
3359                                 pd->dport = &pd->hdr.udp->uh_dport;
3360                         }
3361                         rewrite++;
3362                         break;
3363 #ifdef INET
3364                 case IPPROTO_ICMP:
3365                         nk->port[0] = nk->port[1];
3366                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3367                                 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3368                                     nk->addr[pd->sidx].v4.s_addr, 0);
3369
3370                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3371                                 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3372                                     nk->addr[pd->didx].v4.s_addr, 0);
3373
3374                         if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3375                                 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3376                                     pd->hdr.icmp->icmp_cksum, sport,
3377                                     nk->port[1], 0);
3378                                 pd->hdr.icmp->icmp_id = nk->port[1];
3379                                 pd->sport = &pd->hdr.icmp->icmp_id;
3380                         }
3381                         m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3382                         break;
3383 #endif /* INET */
3384 #ifdef INET6
3385                 case IPPROTO_ICMPV6:
3386                         nk->port[0] = nk->port[1];
3387                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3388                                 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3389                                     &nk->addr[pd->sidx], 0);
3390
3391                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3392                                 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3393                                     &nk->addr[pd->didx], 0);
3394                         rewrite++;
3395                         break;
3396 #endif /* INET */
3397                 default:
3398                         switch (af) {
3399 #ifdef INET
3400                         case AF_INET:
3401                                 if (PF_ANEQ(saddr,
3402                                     &nk->addr[pd->sidx], AF_INET))
3403                                         pf_change_a(&saddr->v4.s_addr,
3404                                             pd->ip_sum,
3405                                             nk->addr[pd->sidx].v4.s_addr, 0);
3406
3407                                 if (PF_ANEQ(daddr,
3408                                     &nk->addr[pd->didx], AF_INET))
3409                                         pf_change_a(&daddr->v4.s_addr,
3410                                             pd->ip_sum,
3411                                             nk->addr[pd->didx].v4.s_addr, 0);
3412                                 break;
3413 #endif /* INET */
3414 #ifdef INET6
3415                         case AF_INET6:
3416                                 if (PF_ANEQ(saddr,
3417                                     &nk->addr[pd->sidx], AF_INET6))
3418                                         PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3419
3420                                 if (PF_ANEQ(daddr,
3421                                     &nk->addr[pd->didx], AF_INET6))
3422                                         PF_ACPY(daddr, &nk->addr[pd->didx], af);
3423                                 break;
3424 #endif /* INET */
3425                         }
3426                         break;
3427                 }
3428                 if (nr->natpass)
3429                         r = NULL;
3430                 pd->nat_rule = nr;
3431         }
3432
3433         while (r != NULL) {
3434                 r->evaluations++;
3435                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3436                         r = r->skip[PF_SKIP_IFP].ptr;
3437                 else if (r->direction && r->direction != direction)
3438                         r = r->skip[PF_SKIP_DIR].ptr;
3439                 else if (r->af && r->af != af)
3440                         r = r->skip[PF_SKIP_AF].ptr;
3441                 else if (r->proto && r->proto != pd->proto)
3442                         r = r->skip[PF_SKIP_PROTO].ptr;
3443                 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3444                     r->src.neg, kif, M_GETFIB(m)))
3445                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3446                 /* tcp/udp only. port_op always 0 in other cases */
3447                 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3448                     r->src.port[0], r->src.port[1], sport))
3449                         r = r->skip[PF_SKIP_SRC_PORT].ptr;
3450                 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3451                     r->dst.neg, NULL, M_GETFIB(m)))
3452                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
3453                 /* tcp/udp only. port_op always 0 in other cases */
3454                 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3455                     r->dst.port[0], r->dst.port[1], dport))
3456                         r = r->skip[PF_SKIP_DST_PORT].ptr;
3457                 /* icmp only. type always 0 in other cases */
3458                 else if (r->type && r->type != icmptype + 1)
3459                         r = TAILQ_NEXT(r, entries);
3460                 /* icmp only. type always 0 in other cases */
3461                 else if (r->code && r->code != icmpcode + 1)
3462                         r = TAILQ_NEXT(r, entries);
3463                 else if (r->tos && !(r->tos == pd->tos))
3464                         r = TAILQ_NEXT(r, entries);
3465                 else if (r->rule_flag & PFRULE_FRAGMENT)
3466                         r = TAILQ_NEXT(r, entries);
3467                 else if (pd->proto == IPPROTO_TCP &&
3468                     (r->flagset & th->th_flags) != r->flags)
3469                         r = TAILQ_NEXT(r, entries);
3470                 /* tcp/udp only. uid.op always 0 in other cases */
3471                 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3472                     pf_socket_lookup(direction, pd, m), 1)) &&
3473                     !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3474                     pd->lookup.uid))
3475                         r = TAILQ_NEXT(r, entries);
3476                 /* tcp/udp only. gid.op always 0 in other cases */
3477                 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3478                     pf_socket_lookup(direction, pd, m), 1)) &&
3479                     !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3480                     pd->lookup.gid))
3481                         r = TAILQ_NEXT(r, entries);
3482                 else if (r->prio &&
3483                     !pf_match_ieee8021q_pcp(r->prio, m))
3484                         r = TAILQ_NEXT(r, entries);
3485                 else if (r->prob &&
3486                     r->prob <= arc4random())
3487                         r = TAILQ_NEXT(r, entries);
3488                 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3489                     pd->pf_mtag ? pd->pf_mtag->tag : 0))
3490                         r = TAILQ_NEXT(r, entries);
3491                 else if (r->os_fingerprint != PF_OSFP_ANY &&
3492                     (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3493                     pf_osfp_fingerprint(pd, m, off, th),
3494                     r->os_fingerprint)))
3495                         r = TAILQ_NEXT(r, entries);
3496                 else {
3497                         if (r->tag)
3498                                 tag = r->tag;
3499                         if (r->rtableid >= 0)
3500                                 rtableid = r->rtableid;
3501                         if (r->anchor == NULL) {
3502                                 match = 1;
3503                                 *rm = r;
3504                                 *am = a;
3505                                 *rsm = ruleset;
3506                                 if ((*rm)->quick)
3507                                         break;
3508                                 r = TAILQ_NEXT(r, entries);
3509                         } else
3510                                 pf_step_into_anchor(anchor_stack, &asd,
3511                                     &ruleset, PF_RULESET_FILTER, &r, &a,
3512                                     &match);
3513                 }
3514                 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3515                     &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3516                         break;
3517         }
3518         r = *rm;
3519         a = *am;
3520         ruleset = *rsm;
3521
3522         REASON_SET(&reason, PFRES_MATCH);
3523
3524         if (r->log || (nr != NULL && nr->log)) {
3525                 if (rewrite)
3526                         m_copyback(m, off, hdrlen, pd->hdr.any);
3527                 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3528                     ruleset, pd, 1);
3529         }
3530
3531         if ((r->action == PF_DROP) &&
3532             ((r->rule_flag & PFRULE_RETURNRST) ||
3533             (r->rule_flag & PFRULE_RETURNICMP) ||
3534             (r->rule_flag & PFRULE_RETURN))) {
3535                 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3536                     bip_sum, hdrlen, &reason);
3537         }
3538
3539         if (r->action == PF_DROP)
3540                 goto cleanup;
3541
3542         if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3543                 REASON_SET(&reason, PFRES_MEMORY);
3544                 goto cleanup;
3545         }
3546         if (rtableid >= 0)
3547                 M_SETFIB(m, rtableid);
3548
3549         if (!state_icmp && (r->keep_state || nr != NULL ||
3550             (pd->flags & PFDESC_TCP_NORM))) {
3551                 int action;
3552                 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3553                     sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3554                     hdrlen);
3555                 if (action != PF_PASS) {
3556                         if (action == PF_DROP &&
3557                             (r->rule_flag & PFRULE_RETURN))
3558                                 pf_return(r, nr, pd, sk, off, m, th, kif,
3559                                     bproto_sum, bip_sum, hdrlen, &reason);
3560                         return (action);
3561                 }
3562         } else {
3563                 if (sk != NULL)
3564                         uma_zfree(V_pf_state_key_z, sk);
3565                 if (nk != NULL)
3566                         uma_zfree(V_pf_state_key_z, nk);
3567         }
3568
3569         /* copy back packet headers if we performed NAT operations */
3570         if (rewrite)
3571                 m_copyback(m, off, hdrlen, pd->hdr.any);
3572
3573         if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3574             direction == PF_OUT &&
3575             V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3576                 /*
3577                  * We want the state created, but we dont
3578                  * want to send this in case a partner
3579                  * firewall has to know about it to allow
3580                  * replies through it.
3581                  */
3582                 return (PF_DEFER);
3583
3584         return (PF_PASS);
3585
3586 cleanup:
3587         if (sk != NULL)
3588                 uma_zfree(V_pf_state_key_z, sk);
3589         if (nk != NULL)
3590                 uma_zfree(V_pf_state_key_z, nk);
3591         return (PF_DROP);
3592 }
3593
3594 static int
3595 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3596     struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3597     struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3598     u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3599     int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3600 {
3601         struct pf_state         *s = NULL;
3602         struct pf_src_node      *sn = NULL;
3603         struct tcphdr           *th = pd->hdr.tcp;
3604         u_int16_t                mss = V_tcp_mssdflt;
3605         u_short                  reason;
3606
3607         /* check maximums */
3608         if (r->max_states &&
3609             (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3610                 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3611                 REASON_SET(&reason, PFRES_MAXSTATES);
3612                 goto csfailed;
3613         }
3614         /* src node for filter rule */
3615         if ((r->rule_flag & PFRULE_SRCTRACK ||
3616             r->rpool.opts & PF_POOL_STICKYADDR) &&
3617             pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3618                 REASON_SET(&reason, PFRES_SRCLIMIT);
3619                 goto csfailed;
3620         }
3621         /* src node for translation rule */
3622         if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3623             pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3624                 REASON_SET(&reason, PFRES_SRCLIMIT);
3625                 goto csfailed;
3626         }
3627         s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3628         if (s == NULL) {
3629                 REASON_SET(&reason, PFRES_MEMORY);
3630                 goto csfailed;
3631         }
3632         s->rule.ptr = r;
3633         s->nat_rule.ptr = nr;
3634         s->anchor.ptr = a;
3635         STATE_INC_COUNTERS(s);
3636         if (r->allow_opts)
3637                 s->state_flags |= PFSTATE_ALLOWOPTS;
3638         if (r->rule_flag & PFRULE_STATESLOPPY)
3639                 s->state_flags |= PFSTATE_SLOPPY;
3640         s->log = r->log & PF_LOG_ALL;
3641         s->sync_state = PFSYNC_S_NONE;
3642         if (nr != NULL)
3643                 s->log |= nr->log & PF_LOG_ALL;
3644         switch (pd->proto) {
3645         case IPPROTO_TCP:
3646                 s->src.seqlo = ntohl(th->th_seq);
3647                 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3648                 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3649                     r->keep_state == PF_STATE_MODULATE) {
3650                         /* Generate sequence number modulator */
3651                         if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3652                             0)
3653                                 s->src.seqdiff = 1;
3654                         pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3655                             htonl(s->src.seqlo + s->src.seqdiff), 0);
3656                         *rewrite = 1;
3657                 } else
3658                         s->src.seqdiff = 0;
3659                 if (th->th_flags & TH_SYN) {
3660                         s->src.seqhi++;
3661                         s->src.wscale = pf_get_wscale(m, off,
3662                             th->th_off, pd->af);
3663                 }
3664                 s->src.max_win = MAX(ntohs(th->th_win), 1);
3665                 if (s->src.wscale & PF_WSCALE_MASK) {
3666                         /* Remove scale factor from initial window */
3667                         int win = s->src.max_win;
3668                         win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3669                         s->src.max_win = (win - 1) >>
3670                             (s->src.wscale & PF_WSCALE_MASK);
3671                 }
3672                 if (th->th_flags & TH_FIN)
3673                         s->src.seqhi++;
3674                 s->dst.seqhi = 1;
3675                 s->dst.max_win = 1;
3676                 s->src.state = TCPS_SYN_SENT;
3677                 s->dst.state = TCPS_CLOSED;
3678                 s->timeout = PFTM_TCP_FIRST_PACKET;
3679                 break;
3680         case IPPROTO_UDP:
3681                 s->src.state = PFUDPS_SINGLE;
3682                 s->dst.state = PFUDPS_NO_TRAFFIC;
3683                 s->timeout = PFTM_UDP_FIRST_PACKET;
3684                 break;
3685         case IPPROTO_ICMP:
3686 #ifdef INET6
3687         case IPPROTO_ICMPV6:
3688 #endif
3689                 s->timeout = PFTM_ICMP_FIRST_PACKET;
3690                 break;
3691         default:
3692                 s->src.state = PFOTHERS_SINGLE;
3693                 s->dst.state = PFOTHERS_NO_TRAFFIC;
3694                 s->timeout = PFTM_OTHER_FIRST_PACKET;
3695         }
3696
3697         if (r->rt && r->rt != PF_FASTROUTE) {
3698                 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3699                         REASON_SET(&reason, PFRES_MAPFAILED);
3700                         pf_src_tree_remove_state(s);
3701                         STATE_DEC_COUNTERS(s);
3702                         uma_zfree(V_pf_state_z, s);
3703                         goto csfailed;
3704                 }
3705                 s->rt_kif = r->rpool.cur->kif;
3706         }
3707
3708         s->creation = time_uptime;
3709         s->expire = time_uptime;
3710
3711         if (sn != NULL)
3712                 s->src_node = sn;
3713         if (nsn != NULL) {
3714                 /* XXX We only modify one side for now. */
3715                 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3716                 s->nat_src_node = nsn;
3717         }
3718         if (pd->proto == IPPROTO_TCP) {
3719                 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3720                     off, pd, th, &s->src, &s->dst)) {
3721                         REASON_SET(&reason, PFRES_MEMORY);
3722                         pf_src_tree_remove_state(s);
3723                         STATE_DEC_COUNTERS(s);
3724                         uma_zfree(V_pf_state_z, s);
3725                         return (PF_DROP);
3726                 }
3727                 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3728                     pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3729                     &s->src, &s->dst, rewrite)) {
3730                         /* This really shouldn't happen!!! */
3731                         DPFPRINTF(PF_DEBUG_URGENT,
3732                             ("pf_normalize_tcp_stateful failed on first pkt"));
3733                         pf_normalize_tcp_cleanup(s);
3734                         pf_src_tree_remove_state(s);
3735                         STATE_DEC_COUNTERS(s);
3736                         uma_zfree(V_pf_state_z, s);
3737                         return (PF_DROP);
3738                 }
3739         }
3740         s->direction = pd->dir;
3741
3742         /*
3743          * sk/nk could already been setup by pf_get_translation().
3744          */
3745         if (nr == NULL) {
3746                 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3747                     __func__, nr, sk, nk));
3748                 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3749                 if (sk == NULL)
3750                         goto csfailed;
3751                 nk = sk;
3752         } else
3753                 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3754                     __func__, nr, sk, nk));
3755
3756         /* Swap sk/nk for PF_OUT. */
3757         if (pf_state_insert(BOUND_IFACE(r, kif),
3758             (pd->dir == PF_IN) ? sk : nk,
3759             (pd->dir == PF_IN) ? nk : sk, s)) {
3760                 if (pd->proto == IPPROTO_TCP)
3761                         pf_normalize_tcp_cleanup(s);
3762                 REASON_SET(&reason, PFRES_STATEINS);
3763                 pf_src_tree_remove_state(s);
3764                 STATE_DEC_COUNTERS(s);
3765                 uma_zfree(V_pf_state_z, s);
3766                 return (PF_DROP);
3767         } else
3768                 *sm = s;
3769
3770         if (tag > 0)
3771                 s->tag = tag;
3772         if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3773             TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3774                 s->src.state = PF_TCPS_PROXY_SRC;
3775                 /* undo NAT changes, if they have taken place */
3776                 if (nr != NULL) {
3777                         struct pf_state_key *skt = s->key[PF_SK_WIRE];
3778                         if (pd->dir == PF_OUT)
3779                                 skt = s->key[PF_SK_STACK];
3780                         PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3781                         PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3782                         if (pd->sport)
3783                                 *pd->sport = skt->port[pd->sidx];
3784                         if (pd->dport)
3785                                 *pd->dport = skt->port[pd->didx];
3786                         if (pd->proto_sum)
3787                                 *pd->proto_sum = bproto_sum;
3788                         if (pd->ip_sum)
3789                                 *pd->ip_sum = bip_sum;
3790                         m_copyback(m, off, hdrlen, pd->hdr.any);
3791                 }
3792                 s->src.seqhi = htonl(arc4random());
3793                 /* Find mss option */
3794                 int rtid = M_GETFIB(m);
3795                 mss = pf_get_mss(m, off, th->th_off, pd->af);
3796                 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3797                 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3798                 s->src.mss = mss;
3799                 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3800                     th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3801                     TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3802                 REASON_SET(&reason, PFRES_SYNPROXY);
3803                 return (PF_SYNPROXY_DROP);
3804         }
3805
3806         return (PF_PASS);
3807
3808 csfailed:
3809         if (sk != NULL)
3810                 uma_zfree(V_pf_state_key_z, sk);
3811         if (nk != NULL)
3812                 uma_zfree(V_pf_state_key_z, nk);
3813
3814         if (sn != NULL) {
3815                 struct pf_srchash *sh;
3816
3817                 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3818                 PF_HASHROW_LOCK(sh);
3819                 if (--sn->states == 0 && sn->expire == 0) {
3820                         pf_unlink_src_node(sn);
3821                         uma_zfree(V_pf_sources_z, sn);
3822                         counter_u64_add(
3823                             V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3824                 }
3825                 PF_HASHROW_UNLOCK(sh);
3826         }
3827
3828         if (nsn != sn && nsn != NULL) {
3829                 struct pf_srchash *sh;
3830
3831                 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3832                 PF_HASHROW_LOCK(sh);
3833                 if (--nsn->states == 0 && nsn->expire == 0) {
3834                         pf_unlink_src_node(nsn);
3835                         uma_zfree(V_pf_sources_z, nsn);
3836                         counter_u64_add(
3837                             V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3838                 }
3839                 PF_HASHROW_UNLOCK(sh);
3840         }
3841
3842         return (PF_DROP);
3843 }
3844
3845 static int
3846 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3847     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3848     struct pf_ruleset **rsm)
3849 {
3850         struct pf_rule          *r, *a = NULL;
3851         struct pf_ruleset       *ruleset = NULL;
3852         sa_family_t              af = pd->af;
3853         u_short                  reason;
3854         int                      tag = -1;
3855         int                      asd = 0;
3856         int                      match = 0;
3857         struct pf_anchor_stackframe     anchor_stack[PF_ANCHOR_STACKSIZE];
3858
3859         PF_RULES_RASSERT();
3860
3861         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3862         while (r != NULL) {
3863                 r->evaluations++;
3864                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3865                         r = r->skip[PF_SKIP_IFP].ptr;
3866                 else if (r->direction && r->direction != direction)
3867                         r = r->skip[PF_SKIP_DIR].ptr;
3868                 else if (r->af && r->af != af)
3869                         r = r->skip[PF_SKIP_AF].ptr;
3870                 else if (r->proto && r->proto != pd->proto)
3871                         r = r->skip[PF_SKIP_PROTO].ptr;
3872                 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3873                     r->src.neg, kif, M_GETFIB(m)))
3874                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3875                 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3876                     r->dst.neg, NULL, M_GETFIB(m)))
3877                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
3878                 else if (r->tos && !(r->tos == pd->tos))
3879                         r = TAILQ_NEXT(r, entries);
3880                 else if (r->os_fingerprint != PF_OSFP_ANY)
3881                         r = TAILQ_NEXT(r, entries);
3882                 else if (pd->proto == IPPROTO_UDP &&
3883                     (r->src.port_op || r->dst.port_op))
3884                         r = TAILQ_NEXT(r, entries);
3885                 else if (pd->proto == IPPROTO_TCP &&
3886                     (r->src.port_op || r->dst.port_op || r->flagset))
3887                         r = TAILQ_NEXT(r, entries);
3888                 else if ((pd->proto == IPPROTO_ICMP ||
3889                     pd->proto == IPPROTO_ICMPV6) &&
3890                     (r->type || r->code))
3891                         r = TAILQ_NEXT(r, entries);
3892                 else if (r->prio &&
3893                     !pf_match_ieee8021q_pcp(r->prio, m))
3894                         r = TAILQ_NEXT(r, entries);
3895                 else if (r->prob && r->prob <=
3896                     (arc4random() % (UINT_MAX - 1) + 1))
3897                         r = TAILQ_NEXT(r, entries);
3898                 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3899                     pd->pf_mtag ? pd->pf_mtag->tag : 0))
3900                         r = TAILQ_NEXT(r, entries);
3901                 else {
3902                         if (r->anchor == NULL) {
3903                                 match = 1;
3904                                 *rm = r;
3905                                 *am = a;
3906                                 *rsm = ruleset;
3907                                 if ((*rm)->quick)
3908                                         break;
3909                                 r = TAILQ_NEXT(r, entries);
3910                         } else
3911                                 pf_step_into_anchor(anchor_stack, &asd,
3912                                     &ruleset, PF_RULESET_FILTER, &r, &a,
3913                                     &match);
3914                 }
3915                 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3916                     &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3917                         break;
3918         }
3919         r = *rm;
3920         a = *am;
3921         ruleset = *rsm;
3922
3923         REASON_SET(&reason, PFRES_MATCH);
3924
3925         if (r->log)
3926                 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3927                     1);
3928
3929         if (r->action != PF_PASS)
3930                 return (PF_DROP);
3931
3932         if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3933                 REASON_SET(&reason, PFRES_MEMORY);
3934                 return (PF_DROP);
3935         }
3936
3937         return (PF_PASS);
3938 }
3939
3940 static int
3941 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3942         struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3943         struct pf_pdesc *pd, u_short *reason, int *copyback)
3944 {
3945         struct tcphdr           *th = pd->hdr.tcp;
3946         u_int16_t                win = ntohs(th->th_win);
3947         u_int32_t                ack, end, seq, orig_seq;
3948         u_int8_t                 sws, dws;
3949         int                      ackskew;
3950
3951         if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3952                 sws = src->wscale & PF_WSCALE_MASK;
3953                 dws = dst->wscale & PF_WSCALE_MASK;
3954         } else
3955                 sws = dws = 0;
3956
3957         /*
3958          * Sequence tracking algorithm from Guido van Rooij's paper:
3959          *   http://www.madison-gurkha.com/publications/tcp_filtering/
3960          *      tcp_filtering.ps
3961          */
3962
3963         orig_seq = seq = ntohl(th->th_seq);
3964         if (src->seqlo == 0) {
3965                 /* First packet from this end. Set its state */
3966
3967                 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3968                     src->scrub == NULL) {
3969                         if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3970                                 REASON_SET(reason, PFRES_MEMORY);
3971                                 return (PF_DROP);
3972                         }
3973                 }
3974
3975                 /* Deferred generation of sequence number modulator */
3976                 if (dst->seqdiff && !src->seqdiff) {
3977                         /* use random iss for the TCP server */
3978                         while ((src->seqdiff = arc4random() - seq) == 0)
3979                                 ;
3980                         ack = ntohl(th->th_ack) - dst->seqdiff;
3981                         pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3982                             src->seqdiff), 0);
3983                         pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3984                         *copyback = 1;
3985                 } else {
3986                         ack = ntohl(th->th_ack);
3987                 }
3988
3989                 end = seq + pd->p_len;
3990                 if (th->th_flags & TH_SYN) {
3991                         end++;
3992                         if (dst->wscale & PF_WSCALE_FLAG) {
3993                                 src->wscale = pf_get_wscale(m, off, th->th_off,
3994                                     pd->af);
3995                                 if (src->wscale & PF_WSCALE_FLAG) {
3996                                         /* Remove scale factor from initial
3997                                          * window */
3998                                         sws = src->wscale & PF_WSCALE_MASK;
3999                                         win = ((u_int32_t)win + (1 << sws) - 1)
4000                                             >> sws;
4001                                         dws = dst->wscale & PF_WSCALE_MASK;
4002                                 } else {
4003                                         /* fixup other window */
4004                                         dst->max_win <<= dst->wscale &
4005                                             PF_WSCALE_MASK;
4006                                         /* in case of a retrans SYN|ACK */
4007                                         dst->wscale = 0;
4008                                 }
4009                         }
4010                 }
4011                 if (th->th_flags & TH_FIN)
4012                         end++;
4013
4014                 src->seqlo = seq;
4015                 if (src->state < TCPS_SYN_SENT)
4016                         src->state = TCPS_SYN_SENT;
4017
4018                 /*
4019                  * May need to slide the window (seqhi may have been set by
4020                  * the crappy stack check or if we picked up the connection
4021                  * after establishment)
4022                  */
4023                 if (src->seqhi == 1 ||
4024                     SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4025                         src->seqhi = end + MAX(1, dst->max_win << dws);
4026                 if (win > src->max_win)
4027                         src->max_win = win;
4028
4029         } else {
4030                 ack = ntohl(th->th_ack) - dst->seqdiff;
4031                 if (src->seqdiff) {
4032                         /* Modulate sequence numbers */
4033                         pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4034                             src->seqdiff), 0);
4035                         pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4036                         *copyback = 1;
4037                 }
4038                 end = seq + pd->p_len;
4039                 if (th->th_flags & TH_SYN)
4040                         end++;
4041                 if (th->th_flags & TH_FIN)
4042                         end++;
4043         }
4044
4045         if ((th->th_flags & TH_ACK) == 0) {
4046                 /* Let it pass through the ack skew check */
4047                 ack = dst->seqlo;
4048         } else if ((ack == 0 &&
4049             (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4050             /* broken tcp stacks do not set ack */
4051             (dst->state < TCPS_SYN_SENT)) {
4052                 /*
4053                  * Many stacks (ours included) will set the ACK number in an
4054                  * FIN|ACK if the SYN times out -- no sequence to ACK.
4055                  */
4056                 ack = dst->seqlo;
4057         }
4058
4059         if (seq == end) {
4060                 /* Ease sequencing restrictions on no data packets */
4061                 seq = src->seqlo;
4062                 end = seq;
4063         }
4064
4065         ackskew = dst->seqlo - ack;
4066
4067
4068         /*
4069          * Need to demodulate the sequence numbers in any TCP SACK options
4070          * (Selective ACK). We could optionally validate the SACK values
4071          * against the current ACK window, either forwards or backwards, but
4072          * I'm not confident that SACK has been implemented properly
4073          * everywhere. It wouldn't surprise me if several stacks accidentally
4074          * SACK too far backwards of previously ACKed data. There really aren't
4075          * any security implications of bad SACKing unless the target stack
4076          * doesn't validate the option length correctly. Someone trying to
4077          * spoof into a TCP connection won't bother blindly sending SACK
4078          * options anyway.
4079          */
4080         if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4081                 if (pf_modulate_sack(m, off, pd, th, dst))
4082                         *copyback = 1;
4083         }
4084
4085
4086 #define MAXACKWINDOW (0xffff + 1500)    /* 1500 is an arbitrary fudge factor */
4087         if (SEQ_GEQ(src->seqhi, end) &&
4088             /* Last octet inside other's window space */
4089             SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4090             /* Retrans: not more than one window back */
4091             (ackskew >= -MAXACKWINDOW) &&
4092             /* Acking not more than one reassembled fragment backwards */
4093             (ackskew <= (MAXACKWINDOW << sws)) &&
4094             /* Acking not more than one window forward */
4095             ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4096             (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4097             (pd->flags & PFDESC_IP_REAS) == 0)) {
4098             /* Require an exact/+1 sequence match on resets when possible */
4099
4100                 if (dst->scrub || src->scrub) {
4101                         if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4102                             *state, src, dst, copyback))
4103                                 return (PF_DROP);
4104                 }
4105
4106                 /* update max window */
4107                 if (src->max_win < win)
4108                         src->max_win = win;
4109                 /* synchronize sequencing */
4110                 if (SEQ_GT(end, src->seqlo))
4111                         src->seqlo = end;
4112                 /* slide the window of what the other end can send */
4113                 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4114                         dst->seqhi = ack + MAX((win << sws), 1);
4115
4116
4117                 /* update states */
4118                 if (th->th_flags & TH_SYN)
4119                         if (src->state < TCPS_SYN_SENT)
4120                                 src->state = TCPS_SYN_SENT;
4121                 if (th->th_flags & TH_FIN)
4122                         if (src->state < TCPS_CLOSING)
4123                                 src->state = TCPS_CLOSING;
4124                 if (th->th_flags & TH_ACK) {
4125                         if (dst->state == TCPS_SYN_SENT) {
4126                                 dst->state = TCPS_ESTABLISHED;
4127                                 if (src->state == TCPS_ESTABLISHED &&
4128                                     (*state)->src_node != NULL &&
4129                                     pf_src_connlimit(state)) {
4130                                         REASON_SET(reason, PFRES_SRCLIMIT);
4131                                         return (PF_DROP);
4132                                 }
4133                         } else if (dst->state == TCPS_CLOSING)
4134                                 dst->state = TCPS_FIN_WAIT_2;
4135                 }
4136                 if (th->th_flags & TH_RST)
4137                         src->state = dst->state = TCPS_TIME_WAIT;
4138
4139                 /* update expire time */
4140                 (*state)->expire = time_uptime;
4141                 if (src->state >= TCPS_FIN_WAIT_2 &&
4142                     dst->state >= TCPS_FIN_WAIT_2)
4143                         (*state)->timeout = PFTM_TCP_CLOSED;
4144                 else if (src->state >= TCPS_CLOSING &&
4145                     dst->state >= TCPS_CLOSING)
4146                         (*state)->timeout = PFTM_TCP_FIN_WAIT;
4147                 else if (src->state < TCPS_ESTABLISHED ||
4148                     dst->state < TCPS_ESTABLISHED)
4149                         (*state)->timeout = PFTM_TCP_OPENING;
4150                 else if (src->state >= TCPS_CLOSING ||
4151                     dst->state >= TCPS_CLOSING)
4152                         (*state)->timeout = PFTM_TCP_CLOSING;
4153                 else
4154                         (*state)->timeout = PFTM_TCP_ESTABLISHED;
4155
4156                 /* Fall through to PASS packet */
4157
4158         } else if ((dst->state < TCPS_SYN_SENT ||
4159                 dst->state >= TCPS_FIN_WAIT_2 ||
4160                 src->state >= TCPS_FIN_WAIT_2) &&
4161             SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4162             /* Within a window forward of the originating packet */
4163             SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4164             /* Within a window backward of the originating packet */
4165
4166                 /*
4167                  * This currently handles three situations:
4168                  *  1) Stupid stacks will shotgun SYNs before their peer
4169                  *     replies.
4170                  *  2) When PF catches an already established stream (the
4171                  *     firewall rebooted, the state table was flushed, routes
4172                  *     changed...)
4173                  *  3) Packets get funky immediately after the connection
4174                  *     closes (this should catch Solaris spurious ACK|FINs
4175                  *     that web servers like to spew after a close)
4176                  *
4177                  * This must be a little more careful than the above code
4178                  * since packet floods will also be caught here. We don't
4179                  * update the TTL here to mitigate the damage of a packet
4180                  * flood and so the same code can handle awkward establishment
4181                  * and a loosened connection close.
4182                  * In the establishment case, a correct peer response will
4183                  * validate the connection, go through the normal state code
4184                  * and keep updating the state TTL.
4185                  */
4186
4187                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4188                         printf("pf: loose state match: ");
4189                         pf_print_state(*state);
4190                         pf_print_flags(th->th_flags);
4191                         printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4192                             "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4193                             pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4194                             (unsigned long long)(*state)->packets[1],
4195                             pd->dir == PF_IN ? "in" : "out",
4196                             pd->dir == (*state)->direction ? "fwd" : "rev");
4197                 }
4198
4199                 if (dst->scrub || src->scrub) {
4200                         if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4201                             *state, src, dst, copyback))
4202                                 return (PF_DROP);
4203                 }
4204
4205                 /* update max window */
4206                 if (src->max_win < win)
4207                         src->max_win = win;
4208                 /* synchronize sequencing */
4209                 if (SEQ_GT(end, src->seqlo))
4210                         src->seqlo = end;
4211                 /* slide the window of what the other end can send */
4212                 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4213                         dst->seqhi = ack + MAX((win << sws), 1);
4214
4215                 /*
4216                  * Cannot set dst->seqhi here since this could be a shotgunned
4217                  * SYN and not an already established connection.
4218                  */
4219
4220                 if (th->th_flags & TH_FIN)
4221                         if (src->state < TCPS_CLOSING)
4222                                 src->state = TCPS_CLOSING;
4223                 if (th->th_flags & TH_RST)
4224                         src->state = dst->state = TCPS_TIME_WAIT;
4225
4226                 /* Fall through to PASS packet */
4227
4228         } else {
4229                 if ((*state)->dst.state == TCPS_SYN_SENT &&
4230                     (*state)->src.state == TCPS_SYN_SENT) {
4231                         /* Send RST for state mismatches during handshake */
4232                         if (!(th->th_flags & TH_RST))
4233                                 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4234                                     pd->dst, pd->src, th->th_dport,
4235                                     th->th_sport, ntohl(th->th_ack), 0,
4236                                     TH_RST, 0, 0,
4237                                     (*state)->rule.ptr->return_ttl, 1, 0,
4238                                     kif->pfik_ifp);
4239                         src->seqlo = 0;
4240                         src->seqhi = 1;
4241                         src->max_win = 1;
4242                 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4243                         printf("pf: BAD state: ");
4244                         pf_print_state(*state);
4245                         pf_print_flags(th->th_flags);
4246                         printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4247                             "pkts=%llu:%llu dir=%s,%s\n",
4248                             seq, orig_seq, ack, pd->p_len, ackskew,
4249                             (unsigned long long)(*state)->packets[0],
4250                             (unsigned long long)(*state)->packets[1],
4251                             pd->dir == PF_IN ? "in" : "out",
4252                             pd->dir == (*state)->direction ? "fwd" : "rev");
4253                         printf("pf: State failure on: %c %c %c %c | %c %c\n",
4254                             SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4255                             SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4256                             ' ': '2',
4257                             (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4258                             (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4259                             SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4260                             SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4261                 }
4262                 REASON_SET(reason, PFRES_BADSTATE);
4263                 return (PF_DROP);
4264         }
4265
4266         return (PF_PASS);
4267 }
4268
4269 static int
4270 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4271         struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4272 {
4273         struct tcphdr           *th = pd->hdr.tcp;
4274
4275         if (th->th_flags & TH_SYN)
4276                 if (src->state < TCPS_SYN_SENT)
4277                         src->state = TCPS_SYN_SENT;
4278         if (th->th_flags & TH_FIN)
4279                 if (src->state < TCPS_CLOSING)
4280                         src->state = TCPS_CLOSING;
4281         if (th->th_flags & TH_ACK) {
4282                 if (dst->state == TCPS_SYN_SENT) {
4283                         dst->state = TCPS_ESTABLISHED;
4284                         if (src->state == TCPS_ESTABLISHED &&
4285                             (*state)->src_node != NULL &&
4286                             pf_src_connlimit(state)) {
4287                                 REASON_SET(reason, PFRES_SRCLIMIT);
4288                                 return (PF_DROP);
4289                         }
4290                 } else if (dst->state == TCPS_CLOSING) {
4291                         dst->state = TCPS_FIN_WAIT_2;
4292                 } else if (src->state == TCPS_SYN_SENT &&
4293                     dst->state < TCPS_SYN_SENT) {
4294                         /*
4295                          * Handle a special sloppy case where we only see one
4296                          * half of the connection. If there is a ACK after
4297                          * the initial SYN without ever seeing a packet from
4298                          * the destination, set the connection to established.
4299                          */
4300                         dst->state = src->state = TCPS_ESTABLISHED;
4301                         if ((*state)->src_node != NULL &&
4302                             pf_src_connlimit(state)) {
4303                                 REASON_SET(reason, PFRES_SRCLIMIT);
4304                                 return (PF_DROP);
4305                         }
4306                 } else if (src->state == TCPS_CLOSING &&
4307                     dst->state == TCPS_ESTABLISHED &&
4308                     dst->seqlo == 0) {
4309                         /*
4310                          * Handle the closing of half connections where we
4311                          * don't see the full bidirectional FIN/ACK+ACK
4312                          * handshake.
4313                          */
4314                         dst->state = TCPS_CLOSING;
4315                 }
4316         }
4317         if (th->th_flags & TH_RST)
4318                 src->state = dst->state = TCPS_TIME_WAIT;
4319
4320         /* update expire time */
4321         (*state)->expire = time_uptime;
4322         if (src->state >= TCPS_FIN_WAIT_2 &&
4323             dst->state >= TCPS_FIN_WAIT_2)
4324                 (*state)->timeout = PFTM_TCP_CLOSED;
4325         else if (src->state >= TCPS_CLOSING &&
4326             dst->state >= TCPS_CLOSING)
4327                 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4328         else if (src->state < TCPS_ESTABLISHED ||
4329             dst->state < TCPS_ESTABLISHED)
4330                 (*state)->timeout = PFTM_TCP_OPENING;
4331         else if (src->state >= TCPS_CLOSING ||
4332             dst->state >= TCPS_CLOSING)
4333                 (*state)->timeout = PFTM_TCP_CLOSING;
4334         else
4335                 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4336
4337         return (PF_PASS);
4338 }
4339
4340 static int
4341 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4342     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4343     u_short *reason)
4344 {
4345         struct pf_state_key_cmp  key;
4346         struct tcphdr           *th = pd->hdr.tcp;
4347         int                      copyback = 0;
4348         struct pf_state_peer    *src, *dst;
4349         struct pf_state_key     *sk;
4350
4351         bzero(&key, sizeof(key));
4352         key.af = pd->af;
4353         key.proto = IPPROTO_TCP;
4354         if (direction == PF_IN) {       /* wire side, straight */
4355                 PF_ACPY(&key.addr[0], pd->src, key.af);
4356                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4357                 key.port[0] = th->th_sport;
4358                 key.port[1] = th->th_dport;
4359         } else {                        /* stack side, reverse */
4360                 PF_ACPY(&key.addr[1], pd->src, key.af);
4361                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4362                 key.port[1] = th->th_sport;
4363                 key.port[0] = th->th_dport;
4364         }
4365
4366         STATE_LOOKUP(kif, &key, direction, *state, pd);
4367
4368         if (direction == (*state)->direction) {
4369                 src = &(*state)->src;
4370                 dst = &(*state)->dst;
4371         } else {
4372                 src = &(*state)->dst;
4373                 dst = &(*state)->src;
4374         }
4375
4376         sk = (*state)->key[pd->didx];
4377
4378         if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4379                 if (direction != (*state)->direction) {
4380                         REASON_SET(reason, PFRES_SYNPROXY);
4381                         return (PF_SYNPROXY_DROP);
4382                 }
4383                 if (th->th_flags & TH_SYN) {
4384                         if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4385                                 REASON_SET(reason, PFRES_SYNPROXY);
4386                                 return (PF_DROP);
4387                         }
4388                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4389                             pd->src, th->th_dport, th->th_sport,
4390                             (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4391                             TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4392                         REASON_SET(reason, PFRES_SYNPROXY);
4393                         return (PF_SYNPROXY_DROP);
4394                 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4395                     (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4396                     (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4397                         REASON_SET(reason, PFRES_SYNPROXY);
4398                         return (PF_DROP);
4399                 } else if ((*state)->src_node != NULL &&
4400                     pf_src_connlimit(state)) {
4401                         REASON_SET(reason, PFRES_SRCLIMIT);
4402                         return (PF_DROP);
4403                 } else
4404                         (*state)->src.state = PF_TCPS_PROXY_DST;
4405         }
4406         if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4407                 if (direction == (*state)->direction) {
4408                         if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4409                             (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4410                             (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4411                                 REASON_SET(reason, PFRES_SYNPROXY);
4412                                 return (PF_DROP);
4413                         }
4414                         (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4415                         if ((*state)->dst.seqhi == 1)
4416                                 (*state)->dst.seqhi = htonl(arc4random());
4417                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4418                             &sk->addr[pd->sidx], &sk->addr[pd->didx],
4419                             sk->port[pd->sidx], sk->port[pd->didx],
4420                             (*state)->dst.seqhi, 0, TH_SYN, 0,
4421                             (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4422                         REASON_SET(reason, PFRES_SYNPROXY);
4423                         return (PF_SYNPROXY_DROP);
4424                 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4425                     (TH_SYN|TH_ACK)) ||
4426                     (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4427                         REASON_SET(reason, PFRES_SYNPROXY);
4428                         return (PF_DROP);
4429                 } else {
4430                         (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4431                         (*state)->dst.seqlo = ntohl(th->th_seq);
4432                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4433                             pd->src, th->th_dport, th->th_sport,
4434                             ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4435                             TH_ACK, (*state)->src.max_win, 0, 0, 0,
4436                             (*state)->tag, NULL);
4437                         pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4438                             &sk->addr[pd->sidx], &sk->addr[pd->didx],
4439                             sk->port[pd->sidx], sk->port[pd->didx],
4440                             (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4441                             TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4442                         (*state)->src.seqdiff = (*state)->dst.seqhi -
4443                             (*state)->src.seqlo;
4444                         (*state)->dst.seqdiff = (*state)->src.seqhi -
4445                             (*state)->dst.seqlo;
4446                         (*state)->src.seqhi = (*state)->src.seqlo +
4447                             (*state)->dst.max_win;
4448                         (*state)->dst.seqhi = (*state)->dst.seqlo +
4449                             (*state)->src.max_win;
4450                         (*state)->src.wscale = (*state)->dst.wscale = 0;
4451                         (*state)->src.state = (*state)->dst.state =
4452                             TCPS_ESTABLISHED;
4453                         REASON_SET(reason, PFRES_SYNPROXY);
4454                         return (PF_SYNPROXY_DROP);
4455                 }
4456         }
4457
4458         if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4459             dst->state >= TCPS_FIN_WAIT_2 &&
4460             src->state >= TCPS_FIN_WAIT_2) {
4461                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4462                         printf("pf: state reuse ");
4463                         pf_print_state(*state);
4464                         pf_print_flags(th->th_flags);
4465                         printf("\n");
4466                 }
4467                 /* XXX make sure it's the same direction ?? */
4468                 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4469                 pf_unlink_state(*state, PF_ENTER_LOCKED);
4470                 *state = NULL;
4471                 return (PF_DROP);
4472         }
4473
4474         if ((*state)->state_flags & PFSTATE_SLOPPY) {
4475                 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4476                         return (PF_DROP);
4477         } else {
4478                 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4479                     &copyback) == PF_DROP)
4480                         return (PF_DROP);
4481         }
4482
4483         /* translate source/destination address, if necessary */
4484         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4485                 struct pf_state_key *nk = (*state)->key[pd->didx];
4486
4487                 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4488                     nk->port[pd->sidx] != th->th_sport)
4489                         pf_change_ap(m, pd->src, &th->th_sport,
4490                             pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4491                             nk->port[pd->sidx], 0, pd->af);
4492
4493                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4494                     nk->port[pd->didx] != th->th_dport)
4495                         pf_change_ap(m, pd->dst, &th->th_dport,
4496                             pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4497                             nk->port[pd->didx], 0, pd->af);
4498                 copyback = 1;
4499         }
4500
4501         /* Copyback sequence modulation or stateful scrub changes if needed */
4502         if (copyback)
4503                 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4504
4505         return (PF_PASS);
4506 }
4507
4508 static int
4509 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4510     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4511 {
4512         struct pf_state_peer    *src, *dst;
4513         struct pf_state_key_cmp  key;
4514         struct udphdr           *uh = pd->hdr.udp;
4515
4516         bzero(&key, sizeof(key));
4517         key.af = pd->af;
4518         key.proto = IPPROTO_UDP;
4519         if (direction == PF_IN) {       /* wire side, straight */
4520                 PF_ACPY(&key.addr[0], pd->src, key.af);
4521                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4522                 key.port[0] = uh->uh_sport;
4523                 key.port[1] = uh->uh_dport;
4524         } else {                        /* stack side, reverse */
4525                 PF_ACPY(&key.addr[1], pd->src, key.af);
4526                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4527                 key.port[1] = uh->uh_sport;
4528                 key.port[0] = uh->uh_dport;
4529         }
4530
4531         STATE_LOOKUP(kif, &key, direction, *state, pd);
4532
4533         if (direction == (*state)->direction) {
4534                 src = &(*state)->src;
4535                 dst = &(*state)->dst;
4536         } else {
4537                 src = &(*state)->dst;
4538                 dst = &(*state)->src;
4539         }
4540
4541         /* update states */
4542         if (src->state < PFUDPS_SINGLE)
4543                 src->state = PFUDPS_SINGLE;
4544         if (dst->state == PFUDPS_SINGLE)
4545                 dst->state = PFUDPS_MULTIPLE;
4546
4547         /* update expire time */
4548         (*state)->expire = time_uptime;
4549         if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4550                 (*state)->timeout = PFTM_UDP_MULTIPLE;
4551         else
4552                 (*state)->timeout = PFTM_UDP_SINGLE;
4553
4554         /* translate source/destination address, if necessary */
4555         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4556                 struct pf_state_key *nk = (*state)->key[pd->didx];
4557
4558                 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4559                     nk->port[pd->sidx] != uh->uh_sport)
4560                         pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4561                             &uh->uh_sum, &nk->addr[pd->sidx],
4562                             nk->port[pd->sidx], 1, pd->af);
4563
4564                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4565                     nk->port[pd->didx] != uh->uh_dport)
4566                         pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4567                             &uh->uh_sum, &nk->addr[pd->didx],
4568                             nk->port[pd->didx], 1, pd->af);
4569                 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4570         }
4571
4572         return (PF_PASS);
4573 }
4574
4575 static int
4576 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4577     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4578 {
4579         struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
4580         u_int16_t        icmpid = 0, *icmpsum;
4581         u_int8_t         icmptype;
4582         int              state_icmp = 0;
4583         struct pf_state_key_cmp key;
4584
4585         bzero(&key, sizeof(key));
4586         switch (pd->proto) {
4587 #ifdef INET
4588         case IPPROTO_ICMP:
4589                 icmptype = pd->hdr.icmp->icmp_type;
4590                 icmpid = pd->hdr.icmp->icmp_id;
4591                 icmpsum = &pd->hdr.icmp->icmp_cksum;
4592
4593                 if (icmptype == ICMP_UNREACH ||
4594                     icmptype == ICMP_SOURCEQUENCH ||
4595                     icmptype == ICMP_REDIRECT ||
4596                     icmptype == ICMP_TIMXCEED ||
4597                     icmptype == ICMP_PARAMPROB)
4598                         state_icmp++;
4599                 break;
4600 #endif /* INET */
4601 #ifdef INET6
4602         case IPPROTO_ICMPV6:
4603                 icmptype = pd->hdr.icmp6->icmp6_type;
4604                 icmpid = pd->hdr.icmp6->icmp6_id;
4605                 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4606
4607                 if (icmptype == ICMP6_DST_UNREACH ||
4608                     icmptype == ICMP6_PACKET_TOO_BIG ||
4609                     icmptype == ICMP6_TIME_EXCEEDED ||
4610                     icmptype == ICMP6_PARAM_PROB)
4611                         state_icmp++;
4612                 break;
4613 #endif /* INET6 */
4614         }
4615
4616         if (!state_icmp) {
4617
4618                 /*
4619                  * ICMP query/reply message not related to a TCP/UDP packet.
4620                  * Search for an ICMP state.
4621                  */
4622                 key.af = pd->af;
4623                 key.proto = pd->proto;
4624                 key.port[0] = key.port[1] = icmpid;
4625                 if (direction == PF_IN) {       /* wire side, straight */
4626                         PF_ACPY(&key.addr[0], pd->src, key.af);
4627                         PF_ACPY(&key.addr[1], pd->dst, key.af);
4628                 } else {                        /* stack side, reverse */
4629                         PF_ACPY(&key.addr[1], pd->src, key.af);
4630                         PF_ACPY(&key.addr[0], pd->dst, key.af);
4631                 }
4632
4633                 STATE_LOOKUP(kif, &key, direction, *state, pd);
4634
4635                 (*state)->expire = time_uptime;
4636                 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4637
4638                 /* translate source/destination address, if necessary */
4639                 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4640                         struct pf_state_key *nk = (*state)->key[pd->didx];
4641
4642                         switch (pd->af) {
4643 #ifdef INET
4644                         case AF_INET:
4645                                 if (PF_ANEQ(pd->src,
4646                                     &nk->addr[pd->sidx], AF_INET))
4647                                         pf_change_a(&saddr->v4.s_addr,
4648                                             pd->ip_sum,
4649                                             nk->addr[pd->sidx].v4.s_addr, 0);
4650
4651                                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4652                                     AF_INET))
4653                                         pf_change_a(&daddr->v4.s_addr,
4654                                             pd->ip_sum,
4655                                             nk->addr[pd->didx].v4.s_addr, 0);
4656
4657                                 if (nk->port[0] !=
4658                                     pd->hdr.icmp->icmp_id) {
4659                                         pd->hdr.icmp->icmp_cksum =
4660                                             pf_cksum_fixup(
4661                                             pd->hdr.icmp->icmp_cksum, icmpid,
4662                                             nk->port[pd->sidx], 0);
4663                                         pd->hdr.icmp->icmp_id =
4664                                             nk->port[pd->sidx];
4665                                 }
4666
4667                                 m_copyback(m, off, ICMP_MINLEN,
4668                                     (caddr_t )pd->hdr.icmp);
4669                                 break;
4670 #endif /* INET */
4671 #ifdef INET6
4672                         case AF_INET6:
4673                                 if (PF_ANEQ(pd->src,
4674                                     &nk->addr[pd->sidx], AF_INET6))
4675                                         pf_change_a6(saddr,
4676                                             &pd->hdr.icmp6->icmp6_cksum,
4677                                             &nk->addr[pd->sidx], 0);
4678
4679                                 if (PF_ANEQ(pd->dst,
4680                                     &nk->addr[pd->didx], AF_INET6))
4681                                         pf_change_a6(daddr,
4682                                             &pd->hdr.icmp6->icmp6_cksum,
4683                                             &nk->addr[pd->didx], 0);
4684
4685                                 m_copyback(m, off, sizeof(struct icmp6_hdr),
4686                                     (caddr_t )pd->hdr.icmp6);
4687                                 break;
4688 #endif /* INET6 */
4689                         }
4690                 }
4691                 return (PF_PASS);
4692
4693         } else {
4694                 /*
4695                  * ICMP error message in response to a TCP/UDP packet.
4696                  * Extract the inner TCP/UDP header and search for that state.
4697                  */
4698
4699                 struct pf_pdesc pd2;
4700                 bzero(&pd2, sizeof pd2);
4701 #ifdef INET
4702                 struct ip       h2;
4703 #endif /* INET */
4704 #ifdef INET6
4705                 struct ip6_hdr  h2_6;
4706                 int             terminal = 0;
4707 #endif /* INET6 */
4708                 int             ipoff2 = 0;
4709                 int             off2 = 0;
4710
4711                 pd2.af = pd->af;
4712                 /* Payload packet is from the opposite direction. */
4713                 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4714                 pd2.didx = (direction == PF_IN) ? 0 : 1;
4715                 switch (pd->af) {
4716 #ifdef INET
4717                 case AF_INET:
4718                         /* offset of h2 in mbuf chain */
4719                         ipoff2 = off + ICMP_MINLEN;
4720
4721                         if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4722                             NULL, reason, pd2.af)) {
4723                                 DPFPRINTF(PF_DEBUG_MISC,
4724                                     ("pf: ICMP error message too short "
4725                                     "(ip)\n"));
4726                                 return (PF_DROP);
4727                         }
4728                         /*
4729                          * ICMP error messages don't refer to non-first
4730                          * fragments
4731                          */
4732                         if (h2.ip_off & htons(IP_OFFMASK)) {
4733                                 REASON_SET(reason, PFRES_FRAG);
4734                                 return (PF_DROP);
4735                         }
4736
4737                         /* offset of protocol header that follows h2 */
4738                         off2 = ipoff2 + (h2.ip_hl << 2);
4739
4740                         pd2.proto = h2.ip_p;
4741                         pd2.src = (struct pf_addr *)&h2.ip_src;
4742                         pd2.dst = (struct pf_addr *)&h2.ip_dst;
4743                         pd2.ip_sum = &h2.ip_sum;
4744                         break;
4745 #endif /* INET */
4746 #ifdef INET6
4747                 case AF_INET6:
4748                         ipoff2 = off + sizeof(struct icmp6_hdr);
4749
4750                         if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4751                             NULL, reason, pd2.af)) {
4752                                 DPFPRINTF(PF_DEBUG_MISC,
4753                                     ("pf: ICMP error message too short "
4754                                     "(ip6)\n"));
4755                                 return (PF_DROP);
4756                         }
4757                         pd2.proto = h2_6.ip6_nxt;
4758                         pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4759                         pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4760                         pd2.ip_sum = NULL;
4761                         off2 = ipoff2 + sizeof(h2_6);
4762                         do {
4763                                 switch (pd2.proto) {
4764                                 case IPPROTO_FRAGMENT:
4765                                         /*
4766                                          * ICMPv6 error messages for
4767                                          * non-first fragments
4768                                          */
4769                                         REASON_SET(reason, PFRES_FRAG);
4770                                         return (PF_DROP);
4771                                 case IPPROTO_AH:
4772                                 case IPPROTO_HOPOPTS:
4773                                 case IPPROTO_ROUTING:
4774                                 case IPPROTO_DSTOPTS: {
4775                                         /* get next header and header length */
4776                                         struct ip6_ext opt6;
4777
4778                                         if (!pf_pull_hdr(m, off2, &opt6,
4779                                             sizeof(opt6), NULL, reason,
4780                                             pd2.af)) {
4781                                                 DPFPRINTF(PF_DEBUG_MISC,
4782                                                     ("pf: ICMPv6 short opt\n"));
4783                                                 return (PF_DROP);
4784                                         }
4785                                         if (pd2.proto == IPPROTO_AH)
4786                                                 off2 += (opt6.ip6e_len + 2) * 4;
4787                                         else
4788                                                 off2 += (opt6.ip6e_len + 1) * 8;
4789                                         pd2.proto = opt6.ip6e_nxt;
4790                                         /* goto the next header */
4791                                         break;
4792                                 }
4793                                 default:
4794                                         terminal++;
4795                                         break;
4796                                 }
4797                         } while (!terminal);
4798                         break;
4799 #endif /* INET6 */
4800                 }
4801
4802                 switch (pd2.proto) {
4803                 case IPPROTO_TCP: {
4804                         struct tcphdr            th;
4805                         u_int32_t                seq;
4806                         struct pf_state_peer    *src, *dst;
4807                         u_int8_t                 dws;
4808                         int                      copyback = 0;
4809
4810                         /*
4811                          * Only the first 8 bytes of the TCP header can be
4812                          * expected. Don't access any TCP header fields after
4813                          * th_seq, an ackskew test is not possible.
4814                          */
4815                         if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4816                             pd2.af)) {
4817                                 DPFPRINTF(PF_DEBUG_MISC,
4818                                     ("pf: ICMP error message too short "
4819                                     "(tcp)\n"));
4820                                 return (PF_DROP);
4821                         }
4822
4823                         key.af = pd2.af;
4824                         key.proto = IPPROTO_TCP;
4825                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4826                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4827                         key.port[pd2.sidx] = th.th_sport;
4828                         key.port[pd2.didx] = th.th_dport;
4829
4830                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4831
4832                         if (direction == (*state)->direction) {
4833                                 src = &(*state)->dst;
4834                                 dst = &(*state)->src;
4835                         } else {
4836                                 src = &(*state)->src;
4837                                 dst = &(*state)->dst;
4838                         }
4839
4840                         if (src->wscale && dst->wscale)
4841                                 dws = dst->wscale & PF_WSCALE_MASK;
4842                         else
4843                                 dws = 0;
4844
4845                         /* Demodulate sequence number */
4846                         seq = ntohl(th.th_seq) - src->seqdiff;
4847                         if (src->seqdiff) {
4848                                 pf_change_a(&th.th_seq, icmpsum,
4849                                     htonl(seq), 0);
4850                                 copyback = 1;
4851                         }
4852
4853                         if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4854                             (!SEQ_GEQ(src->seqhi, seq) ||
4855                             !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4856                                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4857                                         printf("pf: BAD ICMP %d:%d ",
4858                                             icmptype, pd->hdr.icmp->icmp_code);
4859                                         pf_print_host(pd->src, 0, pd->af);
4860                                         printf(" -> ");
4861                                         pf_print_host(pd->dst, 0, pd->af);
4862                                         printf(" state: ");
4863                                         pf_print_state(*state);
4864                                         printf(" seq=%u\n", seq);
4865                                 }
4866                                 REASON_SET(reason, PFRES_BADSTATE);
4867                                 return (PF_DROP);
4868                         } else {
4869                                 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4870                                         printf("pf: OK ICMP %d:%d ",
4871                                             icmptype, pd->hdr.icmp->icmp_code);
4872                                         pf_print_host(pd->src, 0, pd->af);
4873                                         printf(" -> ");
4874                                         pf_print_host(pd->dst, 0, pd->af);
4875                                         printf(" state: ");
4876                                         pf_print_state(*state);
4877                                         printf(" seq=%u\n", seq);
4878                                 }
4879                         }
4880
4881                         /* translate source/destination address, if necessary */
4882                         if ((*state)->key[PF_SK_WIRE] !=
4883                             (*state)->key[PF_SK_STACK]) {
4884                                 struct pf_state_key *nk =
4885                                     (*state)->key[pd->didx];
4886
4887                                 if (PF_ANEQ(pd2.src,
4888                                     &nk->addr[pd2.sidx], pd2.af) ||
4889                                     nk->port[pd2.sidx] != th.th_sport)
4890                                         pf_change_icmp(pd2.src, &th.th_sport,
4891                                             daddr, &nk->addr[pd2.sidx],
4892                                             nk->port[pd2.sidx], NULL,
4893                                             pd2.ip_sum, icmpsum,
4894                                             pd->ip_sum, 0, pd2.af);
4895
4896                                 if (PF_ANEQ(pd2.dst,
4897                                     &nk->addr[pd2.didx], pd2.af) ||
4898                                     nk->port[pd2.didx] != th.th_dport)
4899                                         pf_change_icmp(pd2.dst, &th.th_dport,
4900                                             saddr, &nk->addr[pd2.didx],
4901                                             nk->port[pd2.didx], NULL,
4902                                             pd2.ip_sum, icmpsum,
4903                                             pd->ip_sum, 0, pd2.af);
4904                                 copyback = 1;
4905                         }
4906
4907                         if (copyback) {
4908                                 switch (pd2.af) {
4909 #ifdef INET
4910                                 case AF_INET:
4911                                         m_copyback(m, off, ICMP_MINLEN,
4912                                             (caddr_t )pd->hdr.icmp);
4913                                         m_copyback(m, ipoff2, sizeof(h2),
4914                                             (caddr_t )&h2);
4915                                         break;
4916 #endif /* INET */
4917 #ifdef INET6
4918                                 case AF_INET6:
4919                                         m_copyback(m, off,
4920                                             sizeof(struct icmp6_hdr),
4921                                             (caddr_t )pd->hdr.icmp6);
4922                                         m_copyback(m, ipoff2, sizeof(h2_6),
4923                                             (caddr_t )&h2_6);
4924                                         break;
4925 #endif /* INET6 */
4926                                 }
4927                                 m_copyback(m, off2, 8, (caddr_t)&th);
4928                         }
4929
4930                         return (PF_PASS);
4931                         break;
4932                 }
4933                 case IPPROTO_UDP: {
4934                         struct udphdr           uh;
4935
4936                         if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4937                             NULL, reason, pd2.af)) {
4938                                 DPFPRINTF(PF_DEBUG_MISC,
4939                                     ("pf: ICMP error message too short "
4940                                     "(udp)\n"));
4941                                 return (PF_DROP);
4942                         }
4943
4944                         key.af = pd2.af;
4945                         key.proto = IPPROTO_UDP;
4946                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4947                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4948                         key.port[pd2.sidx] = uh.uh_sport;
4949                         key.port[pd2.didx] = uh.uh_dport;
4950
4951                         STATE_LOOKUP(kif, &key, direction, *state, pd);
4952
4953                         /* translate source/destination address, if necessary */
4954                         if ((*state)->key[PF_SK_WIRE] !=
4955                             (*state)->key[PF_SK_STACK]) {
4956                                 struct pf_state_key *nk =
4957                                     (*state)->key[pd->didx];
4958
4959                                 if (PF_ANEQ(pd2.src,
4960                                     &nk->addr[pd2.sidx], pd2.af) ||
4961                                     nk->port[pd2.sidx] != uh.uh_sport)
4962                                         pf_change_icmp(pd2.src, &uh.uh_sport,
4963                                             daddr, &nk->addr[pd2.sidx],
4964                                             nk->port[pd2.sidx], &uh.uh_sum,
4965                                             pd2.ip_sum, icmpsum,
4966                                             pd->ip_sum, 1, pd2.af);
4967
4968                                 if (PF_ANEQ(pd2.dst,
4969                                     &nk->addr[pd2.didx], pd2.af) ||
4970                                     nk->port[pd2.didx] != uh.uh_dport)
4971                                         pf_change_icmp(pd2.dst, &uh.uh_dport,
4972                                             saddr, &nk->addr[pd2.didx],
4973                                             nk->port[pd2.didx], &uh.uh_sum,
4974                                             pd2.ip_sum, icmpsum,
4975                                             pd->ip_sum, 1, pd2.af);
4976
4977                                 switch (pd2.af) {
4978 #ifdef INET
4979                                 case AF_INET:
4980                                         m_copyback(m, off, ICMP_MINLEN,
4981                                             (caddr_t )pd->hdr.icmp);
4982                                         m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4983                                         break;
4984 #endif /* INET */
4985 #ifdef INET6
4986                                 case AF_INET6:
4987                                         m_copyback(m, off,
4988                                             sizeof(struct icmp6_hdr),
4989                                             (caddr_t )pd->hdr.icmp6);
4990                                         m_copyback(m, ipoff2, sizeof(h2_6),
4991                                             (caddr_t )&h2_6);
4992                                         break;
4993 #endif /* INET6 */
4994                                 }
4995                                 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4996                         }
4997                         return (PF_PASS);
4998                         break;
4999                 }
5000 #ifdef INET
5001                 case IPPROTO_ICMP: {
5002                         struct icmp             iih;
5003
5004                         if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5005                             NULL, reason, pd2.af)) {
5006                                 DPFPRINTF(PF_DEBUG_MISC,
5007                                     ("pf: ICMP error message too short i"
5008                                     "(icmp)\n"));
5009                                 return (PF_DROP);
5010                         }
5011
5012                         key.af = pd2.af;
5013                         key.proto = IPPROTO_ICMP;
5014                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5015                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5016                         key.port[0] = key.port[1] = iih.icmp_id;
5017
5018                         STATE_LOOKUP(kif, &key, direction, *state, pd);
5019
5020                         /* translate source/destination address, if necessary */
5021                         if ((*state)->key[PF_SK_WIRE] !=
5022                             (*state)->key[PF_SK_STACK]) {
5023                                 struct pf_state_key *nk =
5024                                     (*state)->key[pd->didx];
5025
5026                                 if (PF_ANEQ(pd2.src,
5027                                     &nk->addr[pd2.sidx], pd2.af) ||
5028                                     nk->port[pd2.sidx] != iih.icmp_id)
5029                                         pf_change_icmp(pd2.src, &iih.icmp_id,
5030                                             daddr, &nk->addr[pd2.sidx],
5031                                             nk->port[pd2.sidx], NULL,
5032                                             pd2.ip_sum, icmpsum,
5033                                             pd->ip_sum, 0, AF_INET);
5034
5035                                 if (PF_ANEQ(pd2.dst,
5036                                     &nk->addr[pd2.didx], pd2.af) ||
5037                                     nk->port[pd2.didx] != iih.icmp_id)
5038                                         pf_change_icmp(pd2.dst, &iih.icmp_id,
5039                                             saddr, &nk->addr[pd2.didx],
5040                                             nk->port[pd2.didx], NULL,
5041                                             pd2.ip_sum, icmpsum,
5042                                             pd->ip_sum, 0, AF_INET);
5043
5044                                 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5045                                 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5046                                 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5047                         }
5048                         return (PF_PASS);
5049                         break;
5050                 }
5051 #endif /* INET */
5052 #ifdef INET6
5053                 case IPPROTO_ICMPV6: {
5054                         struct icmp6_hdr        iih;
5055
5056                         if (!pf_pull_hdr(m, off2, &iih,
5057                             sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5058                                 DPFPRINTF(PF_DEBUG_MISC,
5059                                     ("pf: ICMP error message too short "
5060                                     "(icmp6)\n"));
5061                                 return (PF_DROP);
5062                         }
5063
5064                         key.af = pd2.af;
5065                         key.proto = IPPROTO_ICMPV6;
5066                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5067                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5068                         key.port[0] = key.port[1] = iih.icmp6_id;
5069
5070                         STATE_LOOKUP(kif, &key, direction, *state, pd);
5071
5072                         /* translate source/destination address, if necessary */
5073                         if ((*state)->key[PF_SK_WIRE] !=
5074                             (*state)->key[PF_SK_STACK]) {
5075                                 struct pf_state_key *nk =
5076                                     (*state)->key[pd->didx];
5077
5078                                 if (PF_ANEQ(pd2.src,
5079                                     &nk->addr[pd2.sidx], pd2.af) ||
5080                                     nk->port[pd2.sidx] != iih.icmp6_id)
5081                                         pf_change_icmp(pd2.src, &iih.icmp6_id,
5082                                             daddr, &nk->addr[pd2.sidx],
5083                                             nk->port[pd2.sidx], NULL,
5084                                             pd2.ip_sum, icmpsum,
5085                                             pd->ip_sum, 0, AF_INET6);
5086
5087                                 if (PF_ANEQ(pd2.dst,
5088                                     &nk->addr[pd2.didx], pd2.af) ||
5089                                     nk->port[pd2.didx] != iih.icmp6_id)
5090                                         pf_change_icmp(pd2.dst, &iih.icmp6_id,
5091                                             saddr, &nk->addr[pd2.didx],
5092                                             nk->port[pd2.didx], NULL,
5093                                             pd2.ip_sum, icmpsum,
5094                                             pd->ip_sum, 0, AF_INET6);
5095
5096                                 m_copyback(m, off, sizeof(struct icmp6_hdr),
5097                                     (caddr_t)pd->hdr.icmp6);
5098                                 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5099                                 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5100                                     (caddr_t)&iih);
5101                         }
5102                         return (PF_PASS);
5103                         break;
5104                 }
5105 #endif /* INET6 */
5106                 default: {
5107                         key.af = pd2.af;
5108                         key.proto = pd2.proto;
5109                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5110                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5111                         key.port[0] = key.port[1] = 0;
5112
5113                         STATE_LOOKUP(kif, &key, direction, *state, pd);
5114
5115                         /* translate source/destination address, if necessary */
5116                         if ((*state)->key[PF_SK_WIRE] !=
5117                             (*state)->key[PF_SK_STACK]) {
5118                                 struct pf_state_key *nk =
5119                                     (*state)->key[pd->didx];
5120
5121                                 if (PF_ANEQ(pd2.src,
5122                                     &nk->addr[pd2.sidx], pd2.af))
5123                                         pf_change_icmp(pd2.src, NULL, daddr,
5124                                             &nk->addr[pd2.sidx], 0, NULL,
5125                                             pd2.ip_sum, icmpsum,
5126                                             pd->ip_sum, 0, pd2.af);
5127
5128                                 if (PF_ANEQ(pd2.dst,
5129                                     &nk->addr[pd2.didx], pd2.af))
5130                                         pf_change_icmp(pd2.dst, NULL, saddr,
5131                                             &nk->addr[pd2.didx], 0, NULL,
5132                                             pd2.ip_sum, icmpsum,
5133                                             pd->ip_sum, 0, pd2.af);
5134
5135                                 switch (pd2.af) {
5136 #ifdef INET
5137                                 case AF_INET:
5138                                         m_copyback(m, off, ICMP_MINLEN,
5139                                             (caddr_t)pd->hdr.icmp);
5140                                         m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5141                                         break;
5142 #endif /* INET */
5143 #ifdef INET6
5144                                 case AF_INET6:
5145                                         m_copyback(m, off,
5146                                             sizeof(struct icmp6_hdr),
5147                                             (caddr_t )pd->hdr.icmp6);
5148                                         m_copyback(m, ipoff2, sizeof(h2_6),
5149                                             (caddr_t )&h2_6);
5150                                         break;
5151 #endif /* INET6 */
5152                                 }
5153                         }
5154                         return (PF_PASS);
5155                         break;
5156                 }
5157                 }
5158         }
5159 }
5160
5161 static int
5162 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5163     struct mbuf *m, struct pf_pdesc *pd)
5164 {
5165         struct pf_state_peer    *src, *dst;
5166         struct pf_state_key_cmp  key;
5167
5168         bzero(&key, sizeof(key));
5169         key.af = pd->af;
5170         key.proto = pd->proto;
5171         if (direction == PF_IN) {
5172                 PF_ACPY(&key.addr[0], pd->src, key.af);
5173                 PF_ACPY(&key.addr[1], pd->dst, key.af);
5174                 key.port[0] = key.port[1] = 0;
5175         } else {
5176                 PF_ACPY(&key.addr[1], pd->src, key.af);
5177                 PF_ACPY(&key.addr[0], pd->dst, key.af);
5178                 key.port[1] = key.port[0] = 0;
5179         }
5180
5181         STATE_LOOKUP(kif, &key, direction, *state, pd);
5182
5183         if (direction == (*state)->direction) {
5184                 src = &(*state)->src;
5185                 dst = &(*state)->dst;
5186         } else {
5187                 src = &(*state)->dst;
5188                 dst = &(*state)->src;
5189         }
5190
5191         /* update states */
5192         if (src->state < PFOTHERS_SINGLE)
5193                 src->state = PFOTHERS_SINGLE;
5194         if (dst->state == PFOTHERS_SINGLE)
5195                 dst->state = PFOTHERS_MULTIPLE;
5196
5197         /* update expire time */
5198         (*state)->expire = time_uptime;
5199         if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5200                 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5201         else
5202                 (*state)->timeout = PFTM_OTHER_SINGLE;
5203
5204         /* translate source/destination address, if necessary */
5205         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5206                 struct pf_state_key *nk = (*state)->key[pd->didx];
5207
5208                 KASSERT(nk, ("%s: nk is null", __func__));
5209                 KASSERT(pd, ("%s: pd is null", __func__));
5210                 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5211                 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5212                 switch (pd->af) {
5213 #ifdef INET
5214                 case AF_INET:
5215                         if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5216                                 pf_change_a(&pd->src->v4.s_addr,
5217                                     pd->ip_sum,
5218                                     nk->addr[pd->sidx].v4.s_addr,
5219                                     0);
5220
5221
5222                         if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5223                                 pf_change_a(&pd->dst->v4.s_addr,
5224                                     pd->ip_sum,
5225                                     nk->addr[pd->didx].v4.s_addr,
5226                                     0);
5227
5228                                 break;
5229 #endif /* INET */
5230 #ifdef INET6
5231                 case AF_INET6:
5232                         if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5233                                 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5234
5235                         if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5236                                 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5237 #endif /* INET6 */
5238                 }
5239         }
5240         return (PF_PASS);
5241 }
5242
5243 /*
5244  * ipoff and off are measured from the start of the mbuf chain.
5245  * h must be at "ipoff" on the mbuf chain.
5246  */
5247 void *
5248 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5249     u_short *actionp, u_short *reasonp, sa_family_t af)
5250 {
5251         switch (af) {
5252 #ifdef INET
5253         case AF_INET: {
5254                 struct ip       *h = mtod(m, struct ip *);
5255                 u_int16_t        fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5256
5257                 if (fragoff) {
5258                         if (fragoff >= len)
5259                                 ACTION_SET(actionp, PF_PASS);
5260                         else {
5261                                 ACTION_SET(actionp, PF_DROP);
5262                                 REASON_SET(reasonp, PFRES_FRAG);
5263                         }
5264                         return (NULL);
5265                 }
5266                 if (m->m_pkthdr.len < off + len ||
5267                     ntohs(h->ip_len) < off + len) {
5268                         ACTION_SET(actionp, PF_DROP);
5269                         REASON_SET(reasonp, PFRES_SHORT);
5270                         return (NULL);
5271                 }
5272                 break;
5273         }
5274 #endif /* INET */
5275 #ifdef INET6
5276         case AF_INET6: {
5277                 struct ip6_hdr  *h = mtod(m, struct ip6_hdr *);
5278
5279                 if (m->m_pkthdr.len < off + len ||
5280                     (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5281                     (unsigned)(off + len)) {
5282                         ACTION_SET(actionp, PF_DROP);
5283                         REASON_SET(reasonp, PFRES_SHORT);
5284                         return (NULL);
5285                 }
5286                 break;
5287         }
5288 #endif /* INET6 */
5289         }
5290         m_copydata(m, off, len, p);
5291         return (p);
5292 }
5293
5294 #ifdef RADIX_MPATH
5295 static int
5296 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5297     int rtableid)
5298 {
5299         struct radix_node_head  *rnh;
5300         struct sockaddr_in      *dst;
5301         int                      ret = 1;
5302         int                      check_mpath;
5303 #ifdef INET6
5304         struct sockaddr_in6     *dst6;
5305         struct route_in6         ro;
5306 #else
5307         struct route             ro;
5308 #endif
5309         struct radix_node       *rn;
5310         struct rtentry          *rt;
5311         struct ifnet            *ifp;
5312
5313         check_mpath = 0;
5314         /* XXX: stick to table 0 for now */
5315         rnh = rt_tables_get_rnh(0, af);
5316         if (rnh != NULL && rn_mpath_capable(rnh))
5317                 check_mpath = 1;
5318         bzero(&ro, sizeof(ro));
5319         switch (af) {
5320         case AF_INET:
5321                 dst = satosin(&ro.ro_dst);
5322                 dst->sin_family = AF_INET;
5323                 dst->sin_len = sizeof(*dst);
5324                 dst->sin_addr = addr->v4;
5325                 break;
5326 #ifdef INET6
5327         case AF_INET6:
5328                 /*
5329                  * Skip check for addresses with embedded interface scope,
5330                  * as they would always match anyway.
5331                  */
5332                 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5333                         goto out;
5334                 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5335                 dst6->sin6_family = AF_INET6;
5336                 dst6->sin6_len = sizeof(*dst6);
5337                 dst6->sin6_addr = addr->v6;
5338                 break;
5339 #endif /* INET6 */
5340         default:
5341                 return (0);
5342         }
5343
5344         /* Skip checks for ipsec interfaces */
5345         if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5346                 goto out;
5347
5348         switch (af) {
5349 #ifdef INET6
5350         case AF_INET6:
5351                 in6_rtalloc_ign(&ro, 0, rtableid);
5352                 break;
5353 #endif
5354 #ifdef INET
5355         case AF_INET:
5356                 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5357                 break;
5358 #endif
5359         }
5360
5361         if (ro.ro_rt != NULL) {
5362                 /* No interface given, this is a no-route check */
5363                 if (kif == NULL)
5364                         goto out;
5365
5366                 if (kif->pfik_ifp == NULL) {
5367                         ret = 0;
5368                         goto out;
5369                 }
5370
5371                 /* Perform uRPF check if passed input interface */
5372                 ret = 0;
5373                 rn = (struct radix_node *)ro.ro_rt;
5374                 do {
5375                         rt = (struct rtentry *)rn;
5376                         ifp = rt->rt_ifp;
5377
5378                         if (kif->pfik_ifp == ifp)
5379                                 ret = 1;
5380                         rn = rn_mpath_next(rn);
5381                 } while (check_mpath == 1 && rn != NULL && ret == 0);
5382         } else
5383                 ret = 0;
5384 out:
5385         if (ro.ro_rt != NULL)
5386                 RTFREE(ro.ro_rt);
5387         return (ret);
5388 }
5389 #endif
5390
5391 int
5392 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5393     int rtableid)
5394 {
5395 #ifdef INET
5396         struct nhop4_basic      nh4;
5397 #endif
5398 #ifdef INET6
5399         struct nhop6_basic      nh6;
5400 #endif
5401         struct ifnet            *ifp;
5402 #ifdef RADIX_MPATH
5403         struct radix_node_head  *rnh;
5404
5405         /* XXX: stick to table 0 for now */
5406         rnh = rt_tables_get_rnh(0, af);
5407         if (rnh != NULL && rn_mpath_capable(rnh))
5408                 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5409 #endif
5410         /*
5411          * Skip check for addresses with embedded interface scope,
5412          * as they would always match anyway.
5413          */
5414         if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5415                 return (1);
5416
5417         if (af != AF_INET && af != AF_INET6)
5418                 return (0);
5419
5420         /* Skip checks for ipsec interfaces */
5421         if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5422                 return (1);
5423
5424         ifp = NULL;
5425
5426         switch (af) {
5427 #ifdef INET6
5428         case AF_INET6:
5429                 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5430                         return (0);
5431                 ifp = nh6.nh_ifp;
5432                 break;
5433 #endif
5434 #ifdef INET
5435         case AF_INET:
5436                 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5437                         return (0);
5438                 ifp = nh4.nh_ifp;
5439                 break;
5440 #endif
5441         }
5442
5443         /* No interface given, this is a no-route check */
5444         if (kif == NULL)
5445                 return (1);
5446
5447         if (kif->pfik_ifp == NULL)
5448                 return (0);
5449
5450         /* Perform uRPF check if passed input interface */
5451         if (kif->pfik_ifp == ifp)
5452                 return (1);
5453         return (0);
5454 }
5455
5456 #ifdef INET
5457 static void
5458 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5459     struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5460 {
5461         struct mbuf             *m0, *m1;
5462         struct sockaddr_in      dst;
5463         struct ip               *ip;
5464         struct ifnet            *ifp = NULL;
5465         struct pf_addr           naddr;
5466         struct pf_src_node      *sn = NULL;
5467         int                      error = 0;
5468         uint16_t                 ip_len, ip_off;
5469
5470         KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5471         KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5472             __func__));
5473
5474         if ((pd->pf_mtag == NULL &&
5475             ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5476             pd->pf_mtag->routed++ > 3) {
5477                 m0 = *m;
5478                 *m = NULL;
5479                 goto bad_locked;
5480         }
5481
5482         if (r->rt == PF_DUPTO) {
5483                 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5484                         if (s)
5485                                 PF_STATE_UNLOCK(s);
5486                         return;
5487                 }
5488         } else {
5489                 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5490                         if (s)
5491                                 PF_STATE_UNLOCK(s);
5492                         return;
5493                 }
5494                 m0 = *m;
5495         }
5496
5497         ip = mtod(m0, struct ip *);
5498
5499         bzero(&dst, sizeof(dst));
5500         dst.sin_family = AF_INET;
5501         dst.sin_len = sizeof(dst);
5502         dst.sin_addr = ip->ip_dst;
5503
5504         if (r->rt == PF_FASTROUTE) {
5505                 struct nhop4_basic nh4;
5506
5507                 if (s)
5508                         PF_STATE_UNLOCK(s);
5509
5510                 if (fib4_lookup_nh_basic(M_GETFIB(m0), ip->ip_dst, 0,
5511                     m0->m_pkthdr.flowid, &nh4) != 0) {
5512                         KMOD_IPSTAT_INC(ips_noroute);
5513                         error = EHOSTUNREACH;
5514                         goto bad;
5515                 }
5516
5517                 ifp = nh4.nh_ifp;
5518                 dst.sin_addr = nh4.nh_addr;
5519         } else {
5520                 bzero(&naddr, sizeof(naddr));
5521
5522                 if (TAILQ_EMPTY(&r->rpool.list)) {
5523                         DPFPRINTF(PF_DEBUG_URGENT,
5524                             ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5525                         goto bad_locked;
5526                 }
5527                 if (s == NULL) {
5528                         pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5529                             &naddr, NULL, &sn);
5530                         if (!PF_AZERO(&naddr, AF_INET))
5531                                 dst.sin_addr.s_addr = naddr.v4.s_addr;
5532                         ifp = r->rpool.cur->kif ?
5533                             r->rpool.cur->kif->pfik_ifp : NULL;
5534                 } else {
5535                         if (!PF_AZERO(&s->rt_addr, AF_INET))
5536                                 dst.sin_addr.s_addr =
5537                                     s->rt_addr.v4.s_addr;
5538                         ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5539                         PF_STATE_UNLOCK(s);
5540                 }
5541         }
5542         if (ifp == NULL)
5543                 goto bad;
5544
5545         if (oifp != ifp) {
5546                 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5547                         goto bad;
5548                 else if (m0 == NULL)
5549                         goto done;
5550                 if (m0->m_len < sizeof(struct ip)) {
5551                         DPFPRINTF(PF_DEBUG_URGENT,
5552                             ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5553                         goto bad;
5554                 }
5555                 ip = mtod(m0, struct ip *);
5556         }
5557
5558         if (ifp->if_flags & IFF_LOOPBACK)
5559                 m0->m_flags |= M_SKIP_FIREWALL;
5560
5561         ip_len = ntohs(ip->ip_len);
5562         ip_off = ntohs(ip->ip_off);
5563
5564         /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5565         m0->m_pkthdr.csum_flags |= CSUM_IP;
5566         if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5567                 in_delayed_cksum(m0);
5568                 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5569         }
5570 #ifdef SCTP
5571         if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5572                 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5573                 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5574         }
5575 #endif
5576
5577         /*
5578          * If small enough for interface, or the interface will take
5579          * care of the fragmentation for us, we can just send directly.
5580          */
5581         if (ip_len <= ifp->if_mtu ||
5582             (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5583                 ip->ip_sum = 0;
5584                 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5585                         ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5586                         m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5587                 }
5588                 m_clrprotoflags(m0);    /* Avoid confusing lower layers. */
5589                 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5590                 goto done;
5591         }
5592
5593         /* Balk when DF bit is set or the interface didn't support TSO. */
5594         if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5595                 error = EMSGSIZE;
5596                 KMOD_IPSTAT_INC(ips_cantfrag);
5597                 if (r->rt != PF_DUPTO) {
5598                         icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5599                             ifp->if_mtu);
5600                         goto done;
5601                 } else
5602                         goto bad;
5603         }
5604
5605         error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5606         if (error)
5607                 goto bad;
5608
5609         for (; m0; m0 = m1) {
5610                 m1 = m0->m_nextpkt;
5611                 m0->m_nextpkt = NULL;
5612                 if (error == 0) {
5613                         m_clrprotoflags(m0);
5614                         error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5615                 } else
5616                         m_freem(m0);
5617         }
5618
5619         if (error == 0)
5620                 KMOD_IPSTAT_INC(ips_fragmented);
5621
5622 done:
5623         if (r->rt != PF_DUPTO)
5624                 *m = NULL;
5625         return;
5626
5627 bad_locked:
5628         if (s)
5629                 PF_STATE_UNLOCK(s);
5630 bad:
5631         m_freem(m0);
5632         goto done;
5633 }
5634 #endif /* INET */
5635
5636 #ifdef INET6
5637 static void
5638 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5639     struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5640 {
5641         struct mbuf             *m0;
5642         struct sockaddr_in6     dst;
5643         struct ip6_hdr          *ip6;
5644         struct ifnet            *ifp = NULL;
5645         struct pf_addr           naddr;
5646         struct pf_src_node      *sn = NULL;
5647
5648         KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5649         KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5650             __func__));
5651
5652         if ((pd->pf_mtag == NULL &&
5653             ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5654             pd->pf_mtag->routed++ > 3) {
5655                 m0 = *m;
5656                 *m = NULL;
5657                 goto bad_locked;
5658         }
5659
5660         if (r->rt == PF_DUPTO) {
5661                 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5662                         if (s)
5663                                 PF_STATE_UNLOCK(s);
5664                         return;
5665                 }
5666         } else {
5667                 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5668                         if (s)
5669                                 PF_STATE_UNLOCK(s);
5670                         return;
5671                 }
5672                 m0 = *m;
5673         }
5674
5675         ip6 = mtod(m0, struct ip6_hdr *);
5676
5677         bzero(&dst, sizeof(dst));
5678         dst.sin6_family = AF_INET6;
5679         dst.sin6_len = sizeof(dst);
5680         dst.sin6_addr = ip6->ip6_dst;
5681
5682         /* Cheat. XXX why only in the v6 case??? */
5683         if (r->rt == PF_FASTROUTE) {
5684                 if (s)
5685                         PF_STATE_UNLOCK(s);
5686                 m0->m_flags |= M_SKIP_FIREWALL;
5687                 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5688                 *m = NULL;
5689                 return;
5690         }
5691
5692         bzero(&naddr, sizeof(naddr));
5693
5694         if (TAILQ_EMPTY(&r->rpool.list)) {
5695                 DPFPRINTF(PF_DEBUG_URGENT,
5696                     ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5697                 goto bad_locked;
5698         }
5699         if (s == NULL) {
5700                 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5701                     &naddr, NULL, &sn);
5702                 if (!PF_AZERO(&naddr, AF_INET6))
5703                         PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5704                             &naddr, AF_INET6);
5705                 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5706         } else {
5707                 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5708                         PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5709                             &s->rt_addr, AF_INET6);
5710                 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5711         }
5712
5713         if (s)
5714                 PF_STATE_UNLOCK(s);
5715
5716         if (ifp == NULL)
5717                 goto bad;
5718
5719         if (oifp != ifp) {
5720                 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5721                         goto bad;
5722                 else if (m0 == NULL)
5723                         goto done;
5724                 if (m0->m_len < sizeof(struct ip6_hdr)) {
5725                         DPFPRINTF(PF_DEBUG_URGENT,
5726                             ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5727                             __func__));
5728                         goto bad;
5729                 }
5730                 ip6 = mtod(m0, struct ip6_hdr *);
5731         }
5732
5733         if (ifp->if_flags & IFF_LOOPBACK)
5734                 m0->m_flags |= M_SKIP_FIREWALL;
5735
5736         if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5737             ~ifp->if_hwassist) {
5738                 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5739                 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5740                 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5741         }
5742
5743         /*
5744          * If the packet is too large for the outgoing interface,
5745          * send back an icmp6 error.
5746          */
5747         if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5748                 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5749         if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5750                 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5751         else {
5752                 in6_ifstat_inc(ifp, ifs6_in_toobig);
5753                 if (r->rt != PF_DUPTO)
5754                         icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5755                 else
5756                         goto bad;
5757         }
5758
5759 done:
5760         if (r->rt != PF_DUPTO)
5761                 *m = NULL;
5762         return;
5763
5764 bad_locked:
5765         if (s)
5766                 PF_STATE_UNLOCK(s);
5767 bad:
5768         m_freem(m0);
5769         goto done;
5770 }
5771 #endif /* INET6 */
5772
5773 /*
5774  * FreeBSD supports cksum offloads for the following drivers.
5775  *  em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5776  *   ti(4), txp(4), xl(4)
5777  *
5778  * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5779  *  network driver performed cksum including pseudo header, need to verify
5780  *   csum_data
5781  * CSUM_DATA_VALID :
5782  *  network driver performed cksum, needs to additional pseudo header
5783  *  cksum computation with partial csum_data(i.e. lack of H/W support for
5784  *  pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5785  *
5786  * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5787  * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5788  * TCP/UDP layer.
5789  * Also, set csum_data to 0xffff to force cksum validation.
5790  */
5791 static int
5792 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5793 {
5794         u_int16_t sum = 0;
5795         int hw_assist = 0;
5796         struct ip *ip;
5797
5798         if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5799                 return (1);
5800         if (m->m_pkthdr.len < off + len)
5801                 return (1);
5802
5803         switch (p) {
5804         case IPPROTO_TCP:
5805                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5806                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5807                                 sum = m->m_pkthdr.csum_data;
5808                         } else {
5809                                 ip = mtod(m, struct ip *);
5810                                 sum = in_pseudo(ip->ip_src.s_addr,
5811                                 ip->ip_dst.s_addr, htonl((u_short)len +
5812                                 m->m_pkthdr.csum_data + IPPROTO_TCP));
5813                         }
5814                         sum ^= 0xffff;
5815                         ++hw_assist;
5816                 }
5817                 break;
5818         case IPPROTO_UDP:
5819                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5820                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5821                                 sum = m->m_pkthdr.csum_data;
5822                         } else {
5823                                 ip = mtod(m, struct ip *);
5824                                 sum = in_pseudo(ip->ip_src.s_addr,
5825                                 ip->ip_dst.s_addr, htonl((u_short)len +
5826                                 m->m_pkthdr.csum_data + IPPROTO_UDP));
5827                         }
5828                         sum ^= 0xffff;
5829                         ++hw_assist;
5830                 }
5831                 break;
5832         case IPPROTO_ICMP:
5833 #ifdef INET6
5834         case IPPROTO_ICMPV6:
5835 #endif /* INET6 */
5836                 break;
5837         default:
5838                 return (1);
5839         }
5840
5841         if (!hw_assist) {
5842                 switch (af) {
5843                 case AF_INET:
5844                         if (p == IPPROTO_ICMP) {
5845                                 if (m->m_len < off)
5846                                         return (1);
5847                                 m->m_data += off;
5848                                 m->m_len -= off;
5849                                 sum = in_cksum(m, len);
5850                                 m->m_data -= off;
5851                                 m->m_len += off;
5852                         } else {
5853                                 if (m->m_len < sizeof(struct ip))
5854                                         return (1);
5855                                 sum = in4_cksum(m, p, off, len);
5856                         }
5857                         break;
5858 #ifdef INET6
5859                 case AF_INET6:
5860                         if (m->m_len < sizeof(struct ip6_hdr))
5861                                 return (1);
5862                         sum = in6_cksum(m, p, off, len);
5863                         break;
5864 #endif /* INET6 */
5865                 default:
5866                         return (1);
5867                 }
5868         }
5869         if (sum) {
5870                 switch (p) {
5871                 case IPPROTO_TCP:
5872                     {
5873                         KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5874                         break;
5875                     }
5876                 case IPPROTO_UDP:
5877                     {
5878                         KMOD_UDPSTAT_INC(udps_badsum);
5879                         break;
5880                     }
5881 #ifdef INET
5882                 case IPPROTO_ICMP:
5883                     {
5884                         KMOD_ICMPSTAT_INC(icps_checksum);
5885                         break;
5886                     }
5887 #endif
5888 #ifdef INET6
5889                 case IPPROTO_ICMPV6:
5890                     {
5891                         KMOD_ICMP6STAT_INC(icp6s_checksum);
5892                         break;
5893                     }
5894 #endif /* INET6 */
5895                 }
5896                 return (1);
5897         } else {
5898                 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5899                         m->m_pkthdr.csum_flags |=
5900                             (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5901                         m->m_pkthdr.csum_data = 0xffff;
5902                 }
5903         }
5904         return (0);
5905 }
5906
5907
5908 #ifdef INET
5909 int
5910 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5911 {
5912         struct pfi_kif          *kif;
5913         u_short                  action, reason = 0, log = 0;
5914         struct mbuf             *m = *m0;
5915         struct ip               *h = NULL;
5916         struct m_tag            *ipfwtag;
5917         struct pf_rule          *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5918         struct pf_state         *s = NULL;
5919         struct pf_ruleset       *ruleset = NULL;
5920         struct pf_pdesc          pd;
5921         int                      off, dirndx, pqid = 0;
5922
5923         PF_RULES_RLOCK_TRACKER;
5924
5925         M_ASSERTPKTHDR(m);
5926
5927         if (!V_pf_status.running)
5928                 return (PF_PASS);
5929
5930         memset(&pd, 0, sizeof(pd));
5931
5932         kif = (struct pfi_kif *)ifp->if_pf_kif;
5933
5934         if (kif == NULL) {
5935                 DPFPRINTF(PF_DEBUG_URGENT,
5936                     ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5937                 return (PF_DROP);
5938         }
5939         if (kif->pfik_flags & PFI_IFLAG_SKIP)
5940                 return (PF_PASS);
5941
5942         if (m->m_flags & M_SKIP_FIREWALL)
5943                 return (PF_PASS);
5944
5945         pd.pf_mtag = pf_find_mtag(m);
5946
5947         PF_RULES_RLOCK();
5948
5949         if (ip_divert_ptr != NULL &&
5950             ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5951                 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5952                 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5953                         if (pd.pf_mtag == NULL &&
5954                             ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5955                                 action = PF_DROP;
5956                                 goto done;
5957                         }
5958                         pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5959                         m_tag_delete(m, ipfwtag);
5960                 }
5961                 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5962                         m->m_flags |= M_FASTFWD_OURS;
5963                         pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5964                 }
5965         } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5966                 /* We do IP header normalization and packet reassembly here */
5967                 action = PF_DROP;
5968                 goto done;
5969         }
5970         m = *m0;        /* pf_normalize messes with m0 */
5971         h = mtod(m, struct ip *);
5972
5973         off = h->ip_hl << 2;
5974         if (off < (int)sizeof(struct ip)) {
5975                 action = PF_DROP;
5976                 REASON_SET(&reason, PFRES_SHORT);
5977                 log = 1;
5978                 goto done;
5979         }
5980
5981         pd.src = (struct pf_addr *)&h->ip_src;
5982         pd.dst = (struct pf_addr *)&h->ip_dst;
5983         pd.sport = pd.dport = NULL;
5984         pd.ip_sum = &h->ip_sum;
5985         pd.proto_sum = NULL;
5986         pd.proto = h->ip_p;
5987         pd.dir = dir;
5988         pd.sidx = (dir == PF_IN) ? 0 : 1;
5989         pd.didx = (dir == PF_IN) ? 1 : 0;
5990         pd.af = AF_INET;
5991         pd.tos = h->ip_tos;
5992         pd.tot_len = ntohs(h->ip_len);
5993
5994         /* handle fragments that didn't get reassembled by normalization */
5995         if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5996                 action = pf_test_fragment(&r, dir, kif, m, h,
5997                     &pd, &a, &ruleset);
5998                 goto done;
5999         }
6000
6001         switch (h->ip_p) {
6002
6003         case IPPROTO_TCP: {
6004                 struct tcphdr   th;
6005
6006                 pd.hdr.tcp = &th;
6007                 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6008                     &action, &reason, AF_INET)) {
6009                         log = action != PF_PASS;
6010                         goto done;
6011                 }
6012                 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6013                 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6014                         pqid = 1;
6015                 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6016                 if (action == PF_DROP)
6017                         goto done;
6018                 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6019                     &reason);
6020                 if (action == PF_PASS) {
6021                         if (V_pfsync_update_state_ptr != NULL)
6022                                 V_pfsync_update_state_ptr(s);
6023                         r = s->rule.ptr;
6024                         a = s->anchor.ptr;
6025                         log = s->log;
6026                 } else if (s == NULL)
6027                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6028                             &a, &ruleset, inp);
6029                 break;
6030         }
6031
6032         case IPPROTO_UDP: {
6033                 struct udphdr   uh;
6034
6035                 pd.hdr.udp = &uh;
6036                 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6037                     &action, &reason, AF_INET)) {
6038                         log = action != PF_PASS;
6039                         goto done;
6040                 }
6041                 if (uh.uh_dport == 0 ||
6042                     ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6043                     ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6044                         action = PF_DROP;
6045                         REASON_SET(&reason, PFRES_SHORT);
6046                         goto done;
6047                 }
6048                 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6049                 if (action == PF_PASS) {
6050                         if (V_pfsync_update_state_ptr != NULL)
6051                                 V_pfsync_update_state_ptr(s);
6052                         r = s->rule.ptr;
6053                         a = s->anchor.ptr;
6054                         log = s->log;
6055                 } else if (s == NULL)
6056                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6057                             &a, &ruleset, inp);
6058                 break;
6059         }
6060
6061         case IPPROTO_ICMP: {
6062                 struct icmp     ih;
6063
6064                 pd.hdr.icmp = &ih;
6065                 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6066                     &action, &reason, AF_INET)) {
6067                         log = action != PF_PASS;
6068                         goto done;
6069                 }
6070                 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6071                     &reason);
6072                 if (action == PF_PASS) {
6073                         if (V_pfsync_update_state_ptr != NULL)
6074                                 V_pfsync_update_state_ptr(s);
6075                         r = s->rule.ptr;
6076                         a = s->anchor.ptr;
6077                         log = s->log;
6078                 } else if (s == NULL)
6079                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6080                             &a, &ruleset, inp);
6081                 break;
6082         }
6083
6084 #ifdef INET6
6085         case IPPROTO_ICMPV6: {
6086                 action = PF_DROP;
6087                 DPFPRINTF(PF_DEBUG_MISC,
6088                     ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6089                 goto done;
6090         }
6091 #endif
6092
6093         default:
6094                 action = pf_test_state_other(&s, dir, kif, m, &pd);
6095                 if (action == PF_PASS) {
6096                         if (V_pfsync_update_state_ptr != NULL)
6097                                 V_pfsync_update_state_ptr(s);
6098                         r = s->rule.ptr;
6099                         a = s->anchor.ptr;
6100                         log = s->log;
6101                 } else if (s == NULL)
6102                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6103                             &a, &ruleset, inp);
6104                 break;
6105         }
6106
6107 done:
6108         PF_RULES_RUNLOCK();
6109         if (action == PF_PASS && h->ip_hl > 5 &&
6110             !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6111                 action = PF_DROP;
6112                 REASON_SET(&reason, PFRES_IPOPTIONS);
6113                 log = r->log;
6114                 DPFPRINTF(PF_DEBUG_MISC,
6115                     ("pf: dropping packet with ip options\n"));
6116         }
6117
6118         if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6119                 action = PF_DROP;
6120                 REASON_SET(&reason, PFRES_MEMORY);
6121         }
6122         if (r->rtableid >= 0)
6123                 M_SETFIB(m, r->rtableid);
6124
6125         if (r->scrub_flags & PFSTATE_SETPRIO) {
6126                 if (pd.tos & IPTOS_LOWDELAY)
6127                         pqid = 1;
6128                 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6129                         action = PF_DROP;
6130                         REASON_SET(&reason, PFRES_MEMORY);
6131                         log = 1;
6132                         DPFPRINTF(PF_DEBUG_MISC,
6133                             ("pf: failed to allocate 802.1q mtag\n"));
6134                 }
6135         }
6136
6137 #ifdef ALTQ
6138         if (action == PF_PASS && r->qid) {
6139                 if (pd.pf_mtag == NULL &&
6140                     ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6141                         action = PF_DROP;
6142                         REASON_SET(&reason, PFRES_MEMORY);
6143                 } else {
6144                         if (s != NULL)
6145                                 pd.pf_mtag->qid_hash = pf_state_hash(s);
6146                         if (pqid || (pd.tos & IPTOS_LOWDELAY))
6147                                 pd.pf_mtag->qid = r->pqid;
6148                         else
6149                                 pd.pf_mtag->qid = r->qid;
6150                         /* Add hints for ecn. */
6151                         pd.pf_mtag->hdr = h;
6152                 }
6153
6154         }
6155 #endif /* ALTQ */
6156
6157         /*
6158          * connections redirected to loopback should not match sockets
6159          * bound specifically to loopback due to security implications,
6160          * see tcp_input() and in_pcblookup_listen().
6161          */
6162         if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6163             pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6164             (s->nat_rule.ptr->action == PF_RDR ||
6165             s->nat_rule.ptr->action == PF_BINAT) &&
6166             (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6167                 m->m_flags |= M_SKIP_FIREWALL;
6168
6169         if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6170             !PACKET_LOOPED(&pd)) {
6171
6172                 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6173                     sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6174                 if (ipfwtag != NULL) {
6175                         ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6176                             ntohs(r->divert.port);
6177                         ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6178
6179                         if (s)
6180                                 PF_STATE_UNLOCK(s);
6181
6182                         m_tag_prepend(m, ipfwtag);
6183                         if (m->m_flags & M_FASTFWD_OURS) {
6184                                 if (pd.pf_mtag == NULL &&
6185                                     ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6186                                         action = PF_DROP;
6187                                         REASON_SET(&reason, PFRES_MEMORY);
6188                                         log = 1;
6189                                         DPFPRINTF(PF_DEBUG_MISC,
6190                                             ("pf: failed to allocate tag\n"));
6191                                 } else {
6192                                         pd.pf_mtag->flags |=
6193                                             PF_FASTFWD_OURS_PRESENT;
6194                                         m->m_flags &= ~M_FASTFWD_OURS;
6195                                 }
6196                         }
6197                         ip_divert_ptr(*m0, dir ==  PF_IN ? DIR_IN : DIR_OUT);
6198                         *m0 = NULL;
6199
6200                         return (action);
6201                 } else {
6202                         /* XXX: ipfw has the same behaviour! */
6203                         action = PF_DROP;
6204                         REASON_SET(&reason, PFRES_MEMORY);
6205                         log = 1;
6206                         DPFPRINTF(PF_DEBUG_MISC,
6207                             ("pf: failed to allocate divert tag\n"));
6208                 }
6209         }
6210
6211         if (log) {
6212                 struct pf_rule *lr;
6213
6214                 if (s != NULL && s->nat_rule.ptr != NULL &&
6215                     s->nat_rule.ptr->log & PF_LOG_ALL)
6216                         lr = s->nat_rule.ptr;
6217                 else
6218                         lr = r;
6219                 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6220                     (s == NULL));
6221         }
6222
6223         kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6224         kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6225
6226         if (action == PF_PASS || r->action == PF_DROP) {
6227                 dirndx = (dir == PF_OUT);
6228                 r->packets[dirndx]++;
6229                 r->bytes[dirndx] += pd.tot_len;
6230                 if (a != NULL) {
6231                         a->packets[dirndx]++;
6232                         a->bytes[dirndx] += pd.tot_len;
6233                 }
6234                 if (s != NULL) {
6235                         if (s->nat_rule.ptr != NULL) {
6236                                 s->nat_rule.ptr->packets[dirndx]++;
6237                                 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6238                         }
6239                         if (s->src_node != NULL) {
6240                                 s->src_node->packets[dirndx]++;
6241                                 s->src_node->bytes[dirndx] += pd.tot_len;
6242                         }
6243                         if (s->nat_src_node != NULL) {
6244                                 s->nat_src_node->packets[dirndx]++;
6245                                 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6246                         }
6247                         dirndx = (dir == s->direction) ? 0 : 1;
6248                         s->packets[dirndx]++;
6249                         s->bytes[dirndx] += pd.tot_len;
6250                 }
6251                 tr = r;
6252                 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6253                 if (nr != NULL && r == &V_pf_default_rule)
6254                         tr = nr;
6255                 if (tr->src.addr.type == PF_ADDR_TABLE)
6256                         pfr_update_stats(tr->src.addr.p.tbl,
6257                             (s == NULL) ? pd.src :
6258                             &s->key[(s->direction == PF_IN)]->
6259                                 addr[(s->direction == PF_OUT)],
6260                             pd.af, pd.tot_len, dir == PF_OUT,
6261                             r->action == PF_PASS, tr->src.neg);
6262                 if (tr->dst.addr.type == PF_ADDR_TABLE)
6263                         pfr_update_stats(tr->dst.addr.p.tbl,
6264                             (s == NULL) ? pd.dst :
6265                             &s->key[(s->direction == PF_IN)]->
6266                                 addr[(s->direction == PF_IN)],
6267                             pd.af, pd.tot_len, dir == PF_OUT,
6268                             r->action == PF_PASS, tr->dst.neg);
6269         }
6270
6271         switch (action) {
6272         case PF_SYNPROXY_DROP:
6273                 m_freem(*m0);
6274         case PF_DEFER:
6275                 *m0 = NULL;
6276                 action = PF_PASS;
6277                 break;
6278         case PF_DROP:
6279                 m_freem(*m0);
6280                 *m0 = NULL;
6281                 break;
6282         default:
6283                 /* pf_route() returns unlocked. */
6284                 if (r->rt) {
6285                         pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6286                         return (action);
6287                 }
6288                 break;
6289         }
6290         if (s)
6291                 PF_STATE_UNLOCK(s);
6292
6293         return (action);
6294 }
6295 #endif /* INET */
6296
6297 #ifdef INET6
6298 int
6299 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6300 {
6301         struct pfi_kif          *kif;
6302         u_short                  action, reason = 0, log = 0;
6303         struct mbuf             *m = *m0, *n = NULL;
6304         struct m_tag            *mtag;
6305         struct ip6_hdr          *h = NULL;
6306         struct pf_rule          *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6307         struct pf_state         *s = NULL;
6308         struct pf_ruleset       *ruleset = NULL;
6309         struct pf_pdesc          pd;
6310         int                      off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6311
6312         PF_RULES_RLOCK_TRACKER;
6313         M_ASSERTPKTHDR(m);
6314
6315         if (!V_pf_status.running)
6316                 return (PF_PASS);
6317
6318         memset(&pd, 0, sizeof(pd));
6319         pd.pf_mtag = pf_find_mtag(m);
6320
6321         if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6322                 return (PF_PASS);
6323
6324         kif = (struct pfi_kif *)ifp->if_pf_kif;
6325         if (kif == NULL) {
6326                 DPFPRINTF(PF_DEBUG_URGENT,
6327                     ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6328                 return (PF_DROP);
6329         }
6330         if (kif->pfik_flags & PFI_IFLAG_SKIP)
6331                 return (PF_PASS);
6332
6333         if (m->m_flags & M_SKIP_FIREWALL)
6334                 return (PF_PASS);
6335
6336         PF_RULES_RLOCK();
6337
6338         /* We do IP header normalization and packet reassembly here */
6339         if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6340                 action = PF_DROP;
6341                 goto done;
6342         }
6343         m = *m0;        /* pf_normalize messes with m0 */
6344         h = mtod(m, struct ip6_hdr *);
6345
6346 #if 1
6347         /*
6348          * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6349          * will do something bad, so drop the packet for now.
6350          */
6351         if (htons(h->ip6_plen) == 0) {
6352                 action = PF_DROP;
6353                 REASON_SET(&reason, PFRES_NORM);        /*XXX*/
6354                 goto done;
6355         }
6356 #endif
6357
6358         pd.src = (struct pf_addr *)&h->ip6_src;
6359         pd.dst = (struct pf_addr *)&h->ip6_dst;
6360         pd.sport = pd.dport = NULL;
6361         pd.ip_sum = NULL;
6362         pd.proto_sum = NULL;
6363         pd.dir = dir;
6364         pd.sidx = (dir == PF_IN) ? 0 : 1;
6365         pd.didx = (dir == PF_IN) ? 1 : 0;
6366         pd.af = AF_INET6;
6367         pd.tos = 0;
6368         pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6369
6370         off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6371         pd.proto = h->ip6_nxt;
6372         do {
6373                 switch (pd.proto) {
6374                 case IPPROTO_FRAGMENT:
6375                         action = pf_test_fragment(&r, dir, kif, m, h,
6376                             &pd, &a, &ruleset);
6377                         if (action == PF_DROP)
6378                                 REASON_SET(&reason, PFRES_FRAG);
6379                         goto done;
6380                 case IPPROTO_ROUTING: {
6381                         struct ip6_rthdr rthdr;
6382
6383                         if (rh_cnt++) {
6384                                 DPFPRINTF(PF_DEBUG_MISC,
6385                                     ("pf: IPv6 more than one rthdr\n"));
6386                                 action = PF_DROP;
6387                                 REASON_SET(&reason, PFRES_IPOPTIONS);
6388                                 log = 1;
6389                                 goto done;
6390                         }
6391                         if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6392                             &reason, pd.af)) {
6393                                 DPFPRINTF(PF_DEBUG_MISC,
6394                                     ("pf: IPv6 short rthdr\n"));
6395                                 action = PF_DROP;
6396                                 REASON_SET(&reason, PFRES_SHORT);
6397                                 log = 1;
6398                                 goto done;
6399                         }
6400                         if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6401                                 DPFPRINTF(PF_DEBUG_MISC,
6402                                     ("pf: IPv6 rthdr0\n"));
6403                                 action = PF_DROP;
6404                                 REASON_SET(&reason, PFRES_IPOPTIONS);
6405                                 log = 1;
6406                                 goto done;
6407                         }
6408                         /* FALLTHROUGH */
6409                 }
6410                 case IPPROTO_AH:
6411                 case IPPROTO_HOPOPTS:
6412                 case IPPROTO_DSTOPTS: {
6413                         /* get next header and header length */
6414                         struct ip6_ext  opt6;
6415
6416                         if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6417                             NULL, &reason, pd.af)) {
6418                                 DPFPRINTF(PF_DEBUG_MISC,
6419                                     ("pf: IPv6 short opt\n"));
6420                                 action = PF_DROP;
6421                                 log = 1;
6422                                 goto done;
6423                         }
6424                         if (pd.proto == IPPROTO_AH)
6425                                 off += (opt6.ip6e_len + 2) * 4;
6426                         else
6427                                 off += (opt6.ip6e_len + 1) * 8;
6428                         pd.proto = opt6.ip6e_nxt;
6429                         /* goto the next header */
6430                         break;
6431                 }
6432                 default:
6433                         terminal++;
6434                         break;
6435                 }
6436         } while (!terminal);
6437
6438         /* if there's no routing header, use unmodified mbuf for checksumming */
6439         if (!n)
6440                 n = m;
6441
6442         switch (pd.proto) {
6443
6444         case IPPROTO_TCP: {
6445                 struct tcphdr   th;
6446
6447                 pd.hdr.tcp = &th;
6448                 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6449                     &action, &reason, AF_INET6)) {
6450                         log = action != PF_PASS;
6451                         goto done;
6452                 }
6453                 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6454                 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6455                 if (action == PF_DROP)
6456                         goto done;
6457                 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6458                     &reason);
6459                 if (action == PF_PASS) {
6460                         if (V_pfsync_update_state_ptr != NULL)
6461                                 V_pfsync_update_state_ptr(s);
6462                         r = s->rule.ptr;
6463                         a = s->anchor.ptr;
6464                         log = s->log;
6465                 } else if (s == NULL)
6466                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6467                             &a, &ruleset, inp);
6468                 break;
6469         }
6470
6471         case IPPROTO_UDP: {
6472                 struct udphdr   uh;
6473
6474                 pd.hdr.udp = &uh;
6475                 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6476                     &action, &reason, AF_INET6)) {
6477                         log = action != PF_PASS;
6478                         goto done;
6479                 }
6480                 if (uh.uh_dport == 0 ||
6481                     ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6482                     ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6483                         action = PF_DROP;
6484                         REASON_SET(&reason, PFRES_SHORT);
6485                         goto done;
6486                 }
6487                 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6488                 if (action == PF_PASS) {
6489                         if (V_pfsync_update_state_ptr != NULL)
6490                                 V_pfsync_update_state_ptr(s);
6491                         r = s->rule.ptr;
6492                         a = s->anchor.ptr;
6493                         log = s->log;
6494                 } else if (s == NULL)
6495                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6496                             &a, &ruleset, inp);
6497                 break;
6498         }
6499
6500         case IPPROTO_ICMP: {
6501                 action = PF_DROP;
6502                 DPFPRINTF(PF_DEBUG_MISC,
6503                     ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6504                 goto done;
6505         }
6506
6507         case IPPROTO_ICMPV6: {
6508                 struct icmp6_hdr        ih;
6509
6510                 pd.hdr.icmp6 = &ih;
6511                 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6512                     &action, &reason, AF_INET6)) {
6513                         log = action != PF_PASS;
6514                         goto done;
6515                 }
6516                 action = pf_test_state_icmp(&s, dir, kif,
6517                     m, off, h, &pd, &reason);
6518                 if (action == PF_PASS) {
6519                         if (V_pfsync_update_state_ptr != NULL)
6520                                 V_pfsync_update_state_ptr(s);
6521                         r = s->rule.ptr;
6522                         a = s->anchor.ptr;
6523                         log = s->log;
6524                 } else if (s == NULL)
6525                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6526                             &a, &ruleset, inp);
6527                 break;
6528         }
6529
6530         default:
6531                 action = pf_test_state_other(&s, dir, kif, m, &pd);
6532                 if (action == PF_PASS) {
6533                         if (V_pfsync_update_state_ptr != NULL)
6534                                 V_pfsync_update_state_ptr(s);
6535                         r = s->rule.ptr;
6536                         a = s->anchor.ptr;
6537                         log = s->log;
6538                 } else if (s == NULL)
6539                         action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6540                             &a, &ruleset, inp);
6541                 break;
6542         }
6543
6544 done:
6545         PF_RULES_RUNLOCK();
6546         if (n != m) {
6547                 m_freem(n);
6548                 n = NULL;
6549         }
6550
6551         /* handle dangerous IPv6 extension headers. */
6552         if (action == PF_PASS && rh_cnt &&
6553             !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6554                 action = PF_DROP;
6555                 REASON_SET(&reason, PFRES_IPOPTIONS);
6556                 log = r->log;
6557                 DPFPRINTF(PF_DEBUG_MISC,
6558                     ("pf: dropping packet with dangerous v6 headers\n"));
6559         }
6560
6561         if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6562                 action = PF_DROP;
6563                 REASON_SET(&reason, PFRES_MEMORY);
6564         }
6565         if (r->rtableid >= 0)
6566                 M_SETFIB(m, r->rtableid);
6567
6568         if (r->scrub_flags & PFSTATE_SETPRIO) {
6569                 if (pd.tos & IPTOS_LOWDELAY)
6570                         pqid = 1;
6571                 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6572                         action = PF_DROP;
6573                         REASON_SET(&reason, PFRES_MEMORY);
6574                         log = 1;
6575                         DPFPRINTF(PF_DEBUG_MISC,
6576                             ("pf: failed to allocate 802.1q mtag\n"));
6577                 }
6578         }
6579
6580 #ifdef ALTQ
6581         if (action == PF_PASS && r->qid) {
6582                 if (pd.pf_mtag == NULL &&
6583                     ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6584                         action = PF_DROP;
6585                         REASON_SET(&reason, PFRES_MEMORY);
6586                 } else {
6587                         if (s != NULL)
6588                                 pd.pf_mtag->qid_hash = pf_state_hash(s);
6589                         if (pd.tos & IPTOS_LOWDELAY)
6590                                 pd.pf_mtag->qid = r->pqid;
6591                         else
6592                                 pd.pf_mtag->qid = r->qid;
6593                         /* Add hints for ecn. */
6594                         pd.pf_mtag->hdr = h;
6595                 }
6596         }
6597 #endif /* ALTQ */
6598
6599         if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6600             pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6601             (s->nat_rule.ptr->action == PF_RDR ||
6602             s->nat_rule.ptr->action == PF_BINAT) &&
6603             IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6604                 m->m_flags |= M_SKIP_FIREWALL;
6605
6606         /* XXX: Anybody working on it?! */
6607         if (r->divert.port)
6608                 printf("pf: divert(9) is not supported for IPv6\n");
6609
6610         if (log) {
6611                 struct pf_rule *lr;
6612
6613                 if (s != NULL && s->nat_rule.ptr != NULL &&
6614                     s->nat_rule.ptr->log & PF_LOG_ALL)
6615                         lr = s->nat_rule.ptr;
6616                 else
6617                         lr = r;
6618                 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6619                     &pd, (s == NULL));
6620         }
6621
6622         kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6623         kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6624
6625         if (action == PF_PASS || r->action == PF_DROP) {
6626                 dirndx = (dir == PF_OUT);
6627                 r->packets[dirndx]++;
6628                 r->bytes[dirndx] += pd.tot_len;
6629                 if (a != NULL) {
6630                         a->packets[dirndx]++;
6631                         a->bytes[dirndx] += pd.tot_len;
6632                 }
6633                 if (s != NULL) {
6634                         if (s->nat_rule.ptr != NULL) {
6635                                 s->nat_rule.ptr->packets[dirndx]++;
6636                                 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6637                         }
6638                         if (s->src_node != NULL) {
6639                                 s->src_node->packets[dirndx]++;
6640                                 s->src_node->bytes[dirndx] += pd.tot_len;
6641                         }
6642                         if (s->nat_src_node != NULL) {
6643                                 s->nat_src_node->packets[dirndx]++;
6644                                 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6645                         }
6646                         dirndx = (dir == s->direction) ? 0 : 1;
6647                         s->packets[dirndx]++;
6648                         s->bytes[dirndx] += pd.tot_len;
6649                 }
6650                 tr = r;
6651                 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6652                 if (nr != NULL && r == &V_pf_default_rule)
6653                         tr = nr;
6654                 if (tr->src.addr.type == PF_ADDR_TABLE)
6655                         pfr_update_stats(tr->src.addr.p.tbl,
6656                             (s == NULL) ? pd.src :
6657                             &s->key[(s->direction == PF_IN)]->addr[0],
6658                             pd.af, pd.tot_len, dir == PF_OUT,
6659                             r->action == PF_PASS, tr->src.neg);
6660                 if (tr->dst.addr.type == PF_ADDR_TABLE)
6661                         pfr_update_stats(tr->dst.addr.p.tbl,
6662                             (s == NULL) ? pd.dst :
6663                             &s->key[(s->direction == PF_IN)]->addr[1],
6664                             pd.af, pd.tot_len, dir == PF_OUT,
6665                             r->action == PF_PASS, tr->dst.neg);
6666         }
6667
6668         switch (action) {
6669         case PF_SYNPROXY_DROP:
6670                 m_freem(*m0);
6671         case PF_DEFER:
6672                 *m0 = NULL;
6673                 action = PF_PASS;
6674                 break;
6675         case PF_DROP:
6676                 m_freem(*m0);
6677                 *m0 = NULL;
6678                 break;
6679         default:
6680                 /* pf_route6() returns unlocked. */
6681                 if (r->rt) {
6682                         pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6683                         return (action);
6684                 }
6685                 break;
6686         }
6687
6688         if (s)
6689                 PF_STATE_UNLOCK(s);
6690
6691         /* If reassembled packet passed, create new fragments. */
6692         if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6693             (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6694                 action = pf_refragment6(ifp, m0, mtag);
6695
6696         return (action);
6697 }
6698 #endif /* INET6 */