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