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