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