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