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