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