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