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