The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netpfil/pf/pf.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: 2a954c3ef11d18300db3f6a251e389b4


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.