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