1 /*
   2  * Copyright (C) 1995-2003 by Darren Reed.
   3  *
   4  * See the IPFILTER.LICENCE file for details on licencing.
   5  *
   6  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
   7  *
   8  * Copyright (c) 2014, Joyent, Inc.  All rights reserved.
   9  */
  10 
  11 #if defined(KERNEL) || defined(_KERNEL)
  12 # undef KERNEL
  13 # undef _KERNEL
  14 # define        KERNEL  1
  15 # define        _KERNEL 1
  16 #endif
  17 #include <sys/errno.h>
  18 #include <sys/types.h>
  19 #include <sys/param.h>
  20 #include <sys/file.h>
  21 #if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
  22     defined(_KERNEL)
  23 # include "opt_ipfilter_log.h"
  24 #endif
  25 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
  26     (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
  27 #include "opt_inet6.h"
  28 #endif
  29 #if !defined(_KERNEL) && !defined(__KERNEL__)
  30 # include <stdio.h>
  31 # include <stdlib.h>
  32 # include <string.h>
  33 # define _KERNEL
  34 # ifdef __OpenBSD__
  35 struct file;
  36 # endif
  37 # include <sys/uio.h>
  38 # undef _KERNEL
  39 #endif
  40 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
  41 # include <sys/filio.h>
  42 # include <sys/fcntl.h>
  43 # if (__FreeBSD_version >= 300000) && !defined(IPFILTER_LKM)
  44 #  include "opt_ipfilter.h"
  45 # endif
  46 #else
  47 # include <sys/ioctl.h>
  48 #endif
  49 #include <sys/time.h>
  50 #if !defined(linux)
  51 # include <sys/protosw.h>
  52 #endif
  53 #include <sys/socket.h>
  54 #if defined(_KERNEL)
  55 # include <sys/systm.h>
  56 # if !defined(__SVR4) && !defined(__svr4__)
  57 #  include <sys/mbuf.h>
  58 # endif
  59 #endif
  60 #if defined(__SVR4) || defined(__svr4__)
  61 # include <sys/filio.h>
  62 # include <sys/byteorder.h>
  63 # ifdef _KERNEL
  64 #  include <sys/dditypes.h>
  65 # endif
  66 # include <sys/stream.h>
  67 # include <sys/kmem.h>
  68 #endif
  69 
  70 #include <net/if.h>
  71 #ifdef sun
  72 # include <net/af.h>
  73 #endif
  74 #include <net/route.h>
  75 #include <netinet/in.h>
  76 #include <netinet/in_systm.h>
  77 #include <netinet/ip.h>
  78 #include <netinet/tcp.h>
  79 #if !defined(linux)
  80 # include <netinet/ip_var.h>
  81 #endif
  82 #if !defined(__hpux) && !defined(linux)
  83 # include <netinet/tcp_fsm.h>
  84 #endif
  85 #include <netinet/udp.h>
  86 #include <netinet/ip_icmp.h>
  87 #include "netinet/ip_compat.h"
  88 #include <netinet/tcpip.h>
  89 #include "netinet/ip_fil.h"
  90 #include "netinet/ip_nat.h"
  91 #include "netinet/ip_frag.h"
  92 #include "netinet/ip_state.h"
  93 #include "netinet/ip_proxy.h"
  94 #include "netinet/ipf_stack.h"
  95 #ifdef  IPFILTER_SYNC
  96 #include "netinet/ip_sync.h"
  97 #endif
  98 #ifdef  IPFILTER_SCAN
  99 #include "netinet/ip_scan.h"
 100 #endif
 101 #ifdef  USE_INET6
 102 #include <netinet/icmp6.h>
 103 #endif
 104 #if (__FreeBSD_version >= 300000)
 105 # include <sys/malloc.h>
 106 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
 107 #  include <sys/libkern.h>
 108 #  include <sys/systm.h>
 109 # endif
 110 #endif
 111 /* END OF INCLUDES */
 112 
 113 
 114 #if !defined(lint)
 115 static const char sccsid[] = "@(#)ip_state.c    1.8 6/5/96 (C) 1993-2000 Darren Reed";
 116 static const char rcsid[] = "@(#)$Id: ip_state.c,v 2.186.2.36 2005/08/11 19:58:03 darrenr Exp $";
 117 #endif
 118 
 119 #ifdef  USE_INET6
 120 static ipstate_t *fr_checkicmp6matchingstate __P((fr_info_t *));
 121 #endif
 122 static ipstate_t *fr_matchsrcdst __P((fr_info_t *, ipstate_t *, i6addr_t *,
 123                                       i6addr_t *, tcphdr_t *, u_32_t));
 124 static ipstate_t *fr_checkicmpmatchingstate __P((fr_info_t *));
 125 static int fr_state_flush __P((int, int, ipf_stack_t *));
 126 static ips_stat_t *fr_statetstats __P((ipf_stack_t *));
 127 static int fr_state_remove __P((caddr_t, ipf_stack_t *));
 128 static void fr_ipsmove __P((ipstate_t *, u_int, ipf_stack_t *));
 129 static int fr_tcpstate __P((fr_info_t *, tcphdr_t *, ipstate_t *));
 130 static int fr_tcpoptions __P((fr_info_t *, tcphdr_t *, tcpdata_t *));
 131 static ipstate_t *fr_stclone __P((fr_info_t *, tcphdr_t *, ipstate_t *));
 132 static void fr_fixinisn __P((fr_info_t *, ipstate_t *));
 133 static void fr_fixoutisn __P((fr_info_t *, ipstate_t *));
 134 static void fr_checknewisn __P((fr_info_t *, ipstate_t *));
 135 static int fr_stateiter __P((ipftoken_t *, ipfgeniter_t *, ipf_stack_t *));
 136 
 137 int fr_stputent __P((caddr_t, ipf_stack_t *));
 138 int fr_stgetent __P((caddr_t, ipf_stack_t *));
 139 
 140 #define ONE_DAY         IPF_TTLVAL(1 * 86400)   /* 1 day */
 141 #define FIVE_DAYS       (5 * ONE_DAY)
 142 #define DOUBLE_HASH(x, ifs)     \
 143     (((x) + ifs->ifs_ips_seed[(x) % ifs->ifs_fr_statesize]) % ifs->ifs_fr_statesize)
 144 
 145 
 146 /* ------------------------------------------------------------------------ */
 147 /* Function:    fr_stateinit                                                */
 148 /* Returns:     int - 0 == success, -1 == failure                           */
 149 /* Parameters:  ifs - ipf stack instance                                    */
 150 /*                                                                          */
 151 /* Initialise all the global variables used within the state code.          */
 152 /* This action also includes initiailising locks.                           */
 153 /* ------------------------------------------------------------------------ */
 154 int fr_stateinit(ifs)
 155 ipf_stack_t *ifs;
 156 {
 157 #if defined(NEED_LOCAL_RAND) || !defined(_KERNEL)
 158         struct timeval tv;
 159 #endif
 160         int i;
 161 
 162         KMALLOCS(ifs->ifs_ips_table, ipstate_t **, 
 163                  ifs->ifs_fr_statesize * sizeof(ipstate_t *));
 164         if (ifs->ifs_ips_table == NULL)
 165                 return -1;
 166         bzero((char *)ifs->ifs_ips_table, 
 167               ifs->ifs_fr_statesize * sizeof(ipstate_t *));
 168 
 169         KMALLOCS(ifs->ifs_ips_seed, u_long *,
 170                  ifs->ifs_fr_statesize * sizeof(*ifs->ifs_ips_seed));
 171         if (ifs->ifs_ips_seed == NULL)
 172                 return -2;
 173 #if defined(NEED_LOCAL_RAND) || !defined(_KERNEL)
 174         tv.tv_sec = 0;
 175         GETKTIME(&tv);
 176 #endif
 177         for (i = 0; i < ifs->ifs_fr_statesize; i++) {
 178                 /*
 179                  * XXX - ips_seed[X] should be a random number of sorts.
 180                  */
 181 #if !defined(NEED_LOCAL_RAND) && defined(_KERNEL)
 182                 ifs->ifs_ips_seed[i] = ipf_random();
 183 #else
 184                 ifs->ifs_ips_seed[i] = ((u_long)ifs->ifs_ips_seed + i) *
 185                     ifs->ifs_fr_statesize;
 186                 ifs->ifs_ips_seed[i] += tv.tv_sec;
 187                 ifs->ifs_ips_seed[i] *= (u_long)ifs->ifs_ips_seed;
 188                 ifs->ifs_ips_seed[i] ^= 0x5a5aa5a5;
 189                 ifs->ifs_ips_seed[i] *= ifs->ifs_fr_statemax;
 190 #endif
 191         }
 192 
 193         /* fill icmp reply type table */
 194         for (i = 0; i <= ICMP_MAXTYPE; i++)
 195                 icmpreplytype4[i] = -1;
 196         icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
 197         icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
 198         icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
 199         icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
 200 #ifdef  USE_INET6
 201         /* fill icmp reply type table */
 202         for (i = 0; i <= ICMP6_MAXTYPE; i++)
 203                 icmpreplytype6[i] = -1;
 204         icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
 205         icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
 206         icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
 207         icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
 208         icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
 209 #endif
 210 
 211         KMALLOCS(ifs->ifs_ips_stats.iss_bucketlen, u_long *,
 212                  ifs->ifs_fr_statesize * sizeof(u_long));
 213         if (ifs->ifs_ips_stats.iss_bucketlen == NULL)
 214                 return -1;
 215         bzero((char *)ifs->ifs_ips_stats.iss_bucketlen, 
 216               ifs->ifs_fr_statesize * sizeof(u_long));
 217 
 218         if (ifs->ifs_fr_state_maxbucket == 0) {
 219                 for (i = ifs->ifs_fr_statesize; i > 0; i >>= 1)
 220                         ifs->ifs_fr_state_maxbucket++;
 221                 ifs->ifs_fr_state_maxbucket *= 2;
 222         }
 223 
 224         fr_sttab_init(ifs->ifs_ips_tqtqb, ifs);
 225         ifs->ifs_ips_tqtqb[IPF_TCP_NSTATES - 1].ifq_next = &ifs->ifs_ips_udptq;
 226         ifs->ifs_ips_udptq.ifq_ttl = (u_long)ifs->ifs_fr_udptimeout;
 227         ifs->ifs_ips_udptq.ifq_ref = 1;
 228         ifs->ifs_ips_udptq.ifq_head = NULL;
 229         ifs->ifs_ips_udptq.ifq_tail = &ifs->ifs_ips_udptq.ifq_head;
 230         MUTEX_INIT(&ifs->ifs_ips_udptq.ifq_lock, "ipftq udp tab");
 231         ifs->ifs_ips_udptq.ifq_next = &ifs->ifs_ips_udpacktq;
 232         ifs->ifs_ips_udpacktq.ifq_ttl = (u_long)ifs->ifs_fr_udpacktimeout;
 233         ifs->ifs_ips_udpacktq.ifq_ref = 1;
 234         ifs->ifs_ips_udpacktq.ifq_head = NULL;
 235         ifs->ifs_ips_udpacktq.ifq_tail = &ifs->ifs_ips_udpacktq.ifq_head;
 236         MUTEX_INIT(&ifs->ifs_ips_udpacktq.ifq_lock, "ipftq udpack tab");
 237         ifs->ifs_ips_udpacktq.ifq_next = &ifs->ifs_ips_icmptq;
 238         ifs->ifs_ips_icmptq.ifq_ttl = (u_long)ifs->ifs_fr_icmptimeout;
 239         ifs->ifs_ips_icmptq.ifq_ref = 1;
 240         ifs->ifs_ips_icmptq.ifq_head = NULL;
 241         ifs->ifs_ips_icmptq.ifq_tail = &ifs->ifs_ips_icmptq.ifq_head;
 242         MUTEX_INIT(&ifs->ifs_ips_icmptq.ifq_lock, "ipftq icmp tab");
 243         ifs->ifs_ips_icmptq.ifq_next = &ifs->ifs_ips_icmpacktq;
 244         ifs->ifs_ips_icmpacktq.ifq_ttl = (u_long)ifs->ifs_fr_icmpacktimeout;
 245         ifs->ifs_ips_icmpacktq.ifq_ref = 1;
 246         ifs->ifs_ips_icmpacktq.ifq_head = NULL;
 247         ifs->ifs_ips_icmpacktq.ifq_tail = &ifs->ifs_ips_icmpacktq.ifq_head;
 248         MUTEX_INIT(&ifs->ifs_ips_icmpacktq.ifq_lock, "ipftq icmpack tab");
 249         ifs->ifs_ips_icmpacktq.ifq_next = &ifs->ifs_ips_iptq;
 250         ifs->ifs_ips_iptq.ifq_ttl = (u_long)ifs->ifs_fr_iptimeout;
 251         ifs->ifs_ips_iptq.ifq_ref = 1;
 252         ifs->ifs_ips_iptq.ifq_head = NULL;
 253         ifs->ifs_ips_iptq.ifq_tail = &ifs->ifs_ips_iptq.ifq_head;
 254         MUTEX_INIT(&ifs->ifs_ips_iptq.ifq_lock, "ipftq ip tab");
 255         ifs->ifs_ips_iptq.ifq_next = &ifs->ifs_ips_deletetq;
 256         /* entry's ttl in deletetq is just 1 tick */
 257         ifs->ifs_ips_deletetq.ifq_ttl = (u_long) 1;
 258         ifs->ifs_ips_deletetq.ifq_ref = 1;
 259         ifs->ifs_ips_deletetq.ifq_head = NULL;
 260         ifs->ifs_ips_deletetq.ifq_tail = &ifs->ifs_ips_deletetq.ifq_head;
 261         MUTEX_INIT(&ifs->ifs_ips_deletetq.ifq_lock, "state delete queue");
 262         ifs->ifs_ips_deletetq.ifq_next = NULL;
 263 
 264         RWLOCK_INIT(&ifs->ifs_ipf_state, "ipf IP state rwlock");
 265         MUTEX_INIT(&ifs->ifs_ipf_stinsert, "ipf state insert mutex");
 266         ifs->ifs_fr_state_init = 1;
 267 
 268         ifs->ifs_ips_last_force_flush = ifs->ifs_fr_ticks;
 269         return 0;
 270 }
 271 
 272 
 273 /* ------------------------------------------------------------------------ */
 274 /* Function:    fr_stateunload                                              */
 275 /* Returns:     Nil                                                         */
 276 /* Parameters:  ifs - ipf stack instance                                    */
 277 /*                                                                          */
 278 /* Release and destroy any resources acquired or initialised so that        */
 279 /* IPFilter can be unloaded or re-initialised.                              */
 280 /* ------------------------------------------------------------------------ */
 281 void fr_stateunload(ifs)
 282 ipf_stack_t *ifs;
 283 {
 284         ipftq_t *ifq, *ifqnext;
 285         ipstate_t *is;
 286 
 287         while ((is = ifs->ifs_ips_list) != NULL)
 288             (void) fr_delstate(is, 0, ifs);
 289 
 290         /*
 291          * Proxy timeout queues are not cleaned here because although they
 292          * exist on the state list, appr_unload is called after fr_stateunload
 293          * and the proxies actually are responsible for them being created.
 294          * Should the proxy timeouts have their own list?  There's no real
 295          * justification as this is the only complicationA
 296          */
 297         for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifqnext) {
 298                 ifqnext = ifq->ifq_next;
 299                 if (((ifq->ifq_flags & IFQF_PROXY) == 0) &&
 300                     (fr_deletetimeoutqueue(ifq) == 0))
 301                         fr_freetimeoutqueue(ifq, ifs);
 302         }
 303 
 304         ifs->ifs_ips_stats.iss_inuse = 0;
 305         ifs->ifs_ips_num = 0;
 306 
 307         if (ifs->ifs_fr_state_init == 1) {
 308                 fr_sttab_destroy(ifs->ifs_ips_tqtqb);
 309                 MUTEX_DESTROY(&ifs->ifs_ips_udptq.ifq_lock);
 310                 MUTEX_DESTROY(&ifs->ifs_ips_icmptq.ifq_lock);
 311                 MUTEX_DESTROY(&ifs->ifs_ips_udpacktq.ifq_lock);
 312                 MUTEX_DESTROY(&ifs->ifs_ips_icmpacktq.ifq_lock);
 313                 MUTEX_DESTROY(&ifs->ifs_ips_iptq.ifq_lock);
 314                 MUTEX_DESTROY(&ifs->ifs_ips_deletetq.ifq_lock);
 315         }
 316 
 317         if (ifs->ifs_ips_table != NULL) {
 318                 KFREES(ifs->ifs_ips_table, 
 319                        ifs->ifs_fr_statesize * sizeof(*ifs->ifs_ips_table));
 320                 ifs->ifs_ips_table = NULL;
 321         }
 322 
 323         if (ifs->ifs_ips_seed != NULL) {
 324                 KFREES(ifs->ifs_ips_seed, 
 325                        ifs->ifs_fr_statesize * sizeof(*ifs->ifs_ips_seed));
 326                 ifs->ifs_ips_seed = NULL;
 327         }
 328 
 329         if (ifs->ifs_ips_stats.iss_bucketlen != NULL) {
 330                 KFREES(ifs->ifs_ips_stats.iss_bucketlen, 
 331                        ifs->ifs_fr_statesize * sizeof(u_long));
 332                 ifs->ifs_ips_stats.iss_bucketlen = NULL;
 333         }
 334 
 335         if (ifs->ifs_fr_state_maxbucket_reset == 1)
 336                 ifs->ifs_fr_state_maxbucket = 0;
 337 
 338         if (ifs->ifs_fr_state_init == 1) {
 339                 ifs->ifs_fr_state_init = 0;
 340                 RW_DESTROY(&ifs->ifs_ipf_state);
 341                 MUTEX_DESTROY(&ifs->ifs_ipf_stinsert);
 342         }
 343 }
 344 
 345 
 346 /* ------------------------------------------------------------------------ */
 347 /* Function:    fr_statetstats                                              */
 348 /* Returns:     ips_state_t* - pointer to state stats structure             */
 349 /* Parameters:  Nil                                                         */
 350 /*                                                                          */
 351 /* Put all the current numbers and pointers into a single struct and return */
 352 /* a pointer to it.                                                         */
 353 /* ------------------------------------------------------------------------ */
 354 static ips_stat_t *fr_statetstats(ifs)
 355 ipf_stack_t *ifs;
 356 {
 357         ifs->ifs_ips_stats.iss_active = ifs->ifs_ips_num;
 358         ifs->ifs_ips_stats.iss_statesize = ifs->ifs_fr_statesize;
 359         ifs->ifs_ips_stats.iss_statemax = ifs->ifs_fr_statemax;
 360         ifs->ifs_ips_stats.iss_table = ifs->ifs_ips_table;
 361         ifs->ifs_ips_stats.iss_list = ifs->ifs_ips_list;
 362         ifs->ifs_ips_stats.iss_ticks = ifs->ifs_fr_ticks;
 363         return &ifs->ifs_ips_stats;
 364 }
 365 
 366 /* ------------------------------------------------------------------------ */
 367 /* Function:    fr_state_remove                                             */
 368 /* Returns:     int - 0 == success, != 0 == failure                         */
 369 /* Parameters:  data(I) - pointer to state structure to delete from table   */
 370 /*              ifs - ipf stack instance                                    */
 371 /*                                                                          */
 372 /* Search for a state structure that matches the one passed, according to   */
 373 /* the IP addresses and other protocol specific information.                */
 374 /* ------------------------------------------------------------------------ */
 375 static int fr_state_remove(data, ifs)
 376 caddr_t data;
 377 ipf_stack_t *ifs;
 378 {
 379         ipstate_t *sp, st;
 380         int error;
 381 
 382         sp = &st;
 383         error = fr_inobj(data, &st, IPFOBJ_IPSTATE);
 384         if (error)
 385                 return EFAULT;
 386 
 387         WRITE_ENTER(&ifs->ifs_ipf_state);
 388         for (sp = ifs->ifs_ips_list; sp; sp = sp->is_next)
 389                 if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
 390                     !bcmp((caddr_t)&sp->is_src, (caddr_t)&st.is_src,
 391                           sizeof(st.is_src)) &&
 392                     !bcmp((caddr_t)&sp->is_dst, (caddr_t)&st.is_dst,
 393                           sizeof(st.is_dst)) &&
 394                     !bcmp((caddr_t)&sp->is_ps, (caddr_t)&st.is_ps,
 395                           sizeof(st.is_ps))) {
 396                         (void) fr_delstate(sp, ISL_REMOVE, ifs);
 397                         RWLOCK_EXIT(&ifs->ifs_ipf_state);
 398                         return 0;
 399                 }
 400         RWLOCK_EXIT(&ifs->ifs_ipf_state);
 401         return ESRCH;
 402 }
 403 
 404 
 405 /* ------------------------------------------------------------------------ */
 406 /* Function:    fr_state_ioctl                                              */
 407 /* Returns:     int - 0 == success, != 0 == failure                         */
 408 /* Parameters:  data(I) - pointer to ioctl data                             */
 409 /*              cmd(I)  - ioctl command integer                             */
 410 /*              mode(I) - file mode bits used with open                     */
 411 /*              uid(I)  - uid of caller                                     */
 412 /*              ctx(I)  - pointer to give the uid context                   */
 413 /*              ifs     - ipf stack instance                                */
 414 /*                                                                          */
 415 /* Processes an ioctl call made to operate on the IP Filter state device.   */
 416 /* ------------------------------------------------------------------------ */
 417 int fr_state_ioctl(data, cmd, mode, uid, ctx, ifs)
 418 caddr_t data;
 419 ioctlcmd_t cmd;
 420 int mode, uid;
 421 void *ctx;
 422 ipf_stack_t *ifs;
 423 {
 424         int arg, ret, error = 0;
 425 
 426         switch (cmd)
 427         {
 428         /*
 429          * Delete an entry from the state table.
 430          */
 431         case SIOCDELST :
 432                 error = fr_state_remove(data, ifs);
 433                 break;
 434         /*
 435          * Flush the state table
 436          */
 437         case SIOCIPFFL :
 438                 error = BCOPYIN(data, (char *)&arg, sizeof(arg));
 439                 if (error != 0) {
 440                         error = EFAULT;
 441                 } else {
 442                         if (VALID_TABLE_FLUSH_OPT(arg)) {
 443                                 WRITE_ENTER(&ifs->ifs_ipf_state);
 444                                 ret = fr_state_flush(arg, 4, ifs);
 445                                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
 446                                 error = BCOPYOUT((char *)&ret, data,
 447                                                 sizeof(ret));
 448                                 if (error != 0)
 449                                         return EFAULT;
 450                         } else {
 451                                 error = EINVAL;
 452                         }
 453                 }
 454                 break;
 455 
 456 #ifdef  USE_INET6
 457         case SIOCIPFL6 :
 458                 error = BCOPYIN(data, (char *)&arg, sizeof(arg));
 459                 if (error != 0) {
 460                         error = EFAULT;
 461                 } else {
 462                         if (VALID_TABLE_FLUSH_OPT(arg)) {
 463                                 WRITE_ENTER(&ifs->ifs_ipf_state);
 464                                 ret = fr_state_flush(arg, 6, ifs);
 465                                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
 466                                 error = BCOPYOUT((char *)&ret, data,
 467                                                 sizeof(ret));
 468                                 if (error != 0)
 469                                         return EFAULT;
 470                         } else {
 471                                 error = EINVAL;
 472                         }
 473                 }
 474                 break;
 475 #endif
 476 #ifdef  IPFILTER_LOG
 477         /*
 478          * Flush the state log.
 479          */
 480         case SIOCIPFFB :
 481                 if (!(mode & FWRITE))
 482                         error = EPERM;
 483                 else {
 484                         int tmp;
 485 
 486                         tmp = ipflog_clear(IPL_LOGSTATE, ifs);
 487                         error = BCOPYOUT((char *)&tmp, data, sizeof(tmp));
 488                         if (error != 0)
 489                                 error = EFAULT;
 490                 }
 491                 break;
 492         /*
 493          * Turn logging of state information on/off.
 494          */
 495         case SIOCSETLG :
 496                 if (!(mode & FWRITE)) {
 497                         error = EPERM;
 498                 } else {
 499                         error = BCOPYIN((char *)data,
 500                                         (char *)&ifs->ifs_ipstate_logging,
 501                                         sizeof(ifs->ifs_ipstate_logging));
 502                         if (error != 0)
 503                                 error = EFAULT;
 504                 }
 505                 break;
 506         /*
 507          * Return the current state of logging.
 508          */
 509         case SIOCGETLG :
 510                 error = BCOPYOUT((char *)&ifs->ifs_ipstate_logging,
 511                                 (char *)data,
 512                                 sizeof(ifs->ifs_ipstate_logging));
 513                 if (error != 0)
 514                         error = EFAULT;
 515                 break;
 516         /*
 517          * Return the number of bytes currently waiting to be read.
 518          */
 519         case FIONREAD :
 520                 arg = ifs->ifs_iplused[IPL_LOGSTATE]; /* returned in an int */
 521                 error = BCOPYOUT((char *)&arg, data, sizeof(arg));
 522                 if (error != 0)
 523                         error = EFAULT;
 524                 break;
 525 #endif
 526         /*
 527          * Get the current state statistics.
 528          */
 529         case SIOCGETFS :
 530                 error = fr_outobj(data, fr_statetstats(ifs), IPFOBJ_STATESTAT);
 531                 break;
 532         /*
 533          * Lock/Unlock the state table.  (Locking prevents any changes, which
 534          * means no packets match).
 535          */
 536         case SIOCSTLCK :
 537                 if (!(mode & FWRITE)) {
 538                         error = EPERM;
 539                 } else {
 540                         error = fr_lock(data, &ifs->ifs_fr_state_lock);
 541                 }
 542                 break;
 543         /*
 544          * Add an entry to the current state table.
 545          */
 546         case SIOCSTPUT :
 547                 if (!ifs->ifs_fr_state_lock || !(mode & FWRITE)) {
 548                         error = EACCES;
 549                         break;
 550                 }
 551                 error = fr_stputent(data, ifs);
 552                 break;
 553         /*
 554          * Get a state table entry.
 555          */
 556         case SIOCSTGET :
 557                 if (!ifs->ifs_fr_state_lock) {
 558                         error = EACCES;
 559                         break;
 560                 }
 561                 error = fr_stgetent(data, ifs);
 562                 break;
 563 
 564         case SIOCGENITER :
 565             {
 566                 ipftoken_t *token;
 567                 ipfgeniter_t iter;
 568 
 569                 error = fr_inobj(data, &iter, IPFOBJ_GENITER);
 570                 if (error != 0)
 571                         break;
 572 
 573                 token = ipf_findtoken(IPFGENITER_STATE, uid, ctx, ifs);
 574                 if (token != NULL)
 575                         error = fr_stateiter(token, &iter, ifs);
 576                 else
 577                         error = ESRCH;
 578                 RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
 579                 break;
 580             }
 581 
 582         case SIOCIPFDELTOK :
 583                 error = BCOPYIN(data, (char *)&arg, sizeof(arg));
 584                 if (error != 0) {
 585                         error = EFAULT;
 586                 } else {
 587                         error = ipf_deltoken(arg, uid, ctx, ifs);
 588                 }
 589                 break;
 590 
 591         default :
 592                 error = EINVAL;
 593                 break;
 594         }
 595         return error;
 596 }
 597 
 598 
 599 /* ------------------------------------------------------------------------ */
 600 /* Function:    fr_stgetent                                                 */
 601 /* Returns:     int - 0 == success, != 0 == failure                         */
 602 /* Parameters:  data(I) - pointer to state structure to retrieve from table */
 603 /*                                                                          */
 604 /* Copy out state information from the kernel to a user space process.  If  */
 605 /* there is a filter rule associated with the state entry, copy that out    */
 606 /* as well.  The entry to copy out is taken from the value of "ips_next" in */
 607 /* the struct passed in and if not null and not found in the list of current*/
 608 /* state entries, the retrieval fails.                                      */
 609 /* ------------------------------------------------------------------------ */
 610 int fr_stgetent(data, ifs)
 611 caddr_t data;
 612 ipf_stack_t *ifs;
 613 {
 614         ipstate_t *is, *isn;
 615         ipstate_save_t ips;
 616         int error;
 617 
 618         error = fr_inobj(data, &ips, IPFOBJ_STATESAVE);
 619         if (error)
 620                 return EFAULT;
 621 
 622         isn = ips.ips_next;
 623         if (isn == NULL) {
 624                 isn = ifs->ifs_ips_list;
 625                 if (isn == NULL) {
 626                         if (ips.ips_next == NULL)
 627                                 return ENOENT;
 628                         return 0;
 629                 }
 630         } else {
 631                 /*
 632                  * Make sure the pointer we're copying from exists in the
 633                  * current list of entries.  Security precaution to prevent
 634                  * copying of random kernel data.
 635                  */
 636                 for (is = ifs->ifs_ips_list; is; is = is->is_next)
 637                         if (is == isn)
 638                                 break;
 639                 if (!is)
 640                         return ESRCH;
 641         }
 642         ips.ips_next = isn->is_next;
 643         bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
 644         ips.ips_rule = isn->is_rule;
 645         if (isn->is_rule != NULL)
 646                 bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
 647                       sizeof(ips.ips_fr));
 648         error = fr_outobj(data, &ips, IPFOBJ_STATESAVE);
 649         if (error)
 650                 return EFAULT;
 651         return 0;
 652 }
 653 
 654 
 655 /* ------------------------------------------------------------------------ */
 656 /* Function:    fr_stputent                                                 */
 657 /* Returns:     int - 0 == success, != 0 == failure                         */
 658 /* Parameters:  data(I) - pointer to state information struct               */
 659 /*              ifs     - ipf stack instance                                */
 660 /*                                                                          */
 661 /* This function implements the SIOCSTPUT ioctl: insert a state entry into  */
 662 /* the state table.  If the state info. includes a pointer to a filter rule */
 663 /* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
 664 /* output.                                                                  */
 665 /* ------------------------------------------------------------------------ */
 666 int fr_stputent(data, ifs)
 667 caddr_t data;
 668 ipf_stack_t *ifs;
 669 {
 670         ipstate_t *is, *isn;
 671         ipstate_save_t ips;
 672         int error, i;
 673         frentry_t *fr;
 674         char *name;
 675 
 676         error = fr_inobj(data, &ips, IPFOBJ_STATESAVE);
 677         if (error)
 678                 return EFAULT;
 679 
 680         /*
 681          * Trigger automatic call to fr_state_flush() if the
 682          * table has reached capacity specified by hi watermark.
 683          */
 684         if (ST_TAB_WATER_LEVEL(ifs) > ifs->ifs_state_flush_level_hi)
 685                 ifs->ifs_fr_state_doflush = 1;
 686 
 687         /*
 688          * If automatic flushing did not do its job, and the table
 689          * has filled up, don't try to create a new entry.
 690          */
 691         if (ifs->ifs_ips_num >= ifs->ifs_fr_statemax) {
 692                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_max);
 693                 return ENOMEM;
 694         }
 695 
 696         KMALLOC(isn, ipstate_t *);
 697         if (isn == NULL)
 698                 return ENOMEM;
 699 
 700         bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
 701         bzero((char *)isn, offsetof(struct ipstate, is_pkts));
 702         isn->is_sti.tqe_pnext = NULL;
 703         isn->is_sti.tqe_next = NULL;
 704         isn->is_sti.tqe_ifq = NULL;
 705         isn->is_sti.tqe_parent = isn;
 706         isn->is_ifp[0] = NULL;
 707         isn->is_ifp[1] = NULL;
 708         isn->is_ifp[2] = NULL;
 709         isn->is_ifp[3] = NULL;
 710         isn->is_sync = NULL;
 711         fr = ips.ips_rule;
 712 
 713         if (fr == NULL) {
 714                 READ_ENTER(&ifs->ifs_ipf_state);
 715                 fr_stinsert(isn, 0, ifs);
 716                 MUTEX_EXIT(&isn->is_lock);
 717                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
 718                 return 0;
 719         }
 720 
 721         if (isn->is_flags & SI_NEWFR) {
 722                 KMALLOC(fr, frentry_t *);
 723                 if (fr == NULL) {
 724                         KFREE(isn);
 725                         return ENOMEM;
 726                 }
 727                 bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
 728                 isn->is_rule = fr;
 729                 ips.ips_is.is_rule = fr;
 730                 MUTEX_NUKE(&fr->fr_lock);
 731                 MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
 732 
 733                 /*
 734                  * Look up all the interface names in the rule.
 735                  */
 736                 for (i = 0; i < 4; i++) {
 737                         name = fr->fr_ifnames[i];
 738                         fr->fr_ifas[i] = fr_resolvenic(name, fr->fr_v, ifs);
 739                         name = isn->is_ifname[i];
 740                         isn->is_ifp[i] = fr_resolvenic(name, isn->is_v, ifs);
 741                 }
 742 
 743                 fr->fr_ref = 0;
 744                 fr->fr_dsize = 0;
 745                 fr->fr_data = NULL;
 746                 fr->fr_type = FR_T_NONE;
 747 
 748                 fr_resolvedest(&fr->fr_tif, fr->fr_v, ifs);
 749                 fr_resolvedest(&fr->fr_dif, fr->fr_v, ifs);
 750                 fr_resolvedest(&fr->fr_rif, fr->fr_v, ifs);
 751 
 752                 /*
 753                  * send a copy back to userland of what we ended up
 754                  * to allow for verification.
 755                  */
 756                 error = fr_outobj(data, &ips, IPFOBJ_STATESAVE);
 757                 if (error) {
 758                         KFREE(isn);
 759                         MUTEX_DESTROY(&fr->fr_lock);
 760                         KFREE(fr);
 761                         return EFAULT;
 762                 }
 763                 READ_ENTER(&ifs->ifs_ipf_state);
 764                 fr_stinsert(isn, 0, ifs);
 765                 MUTEX_EXIT(&isn->is_lock);
 766                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
 767 
 768         } else {
 769                 READ_ENTER(&ifs->ifs_ipf_state);
 770                 for (is = ifs->ifs_ips_list; is; is = is->is_next)
 771                         if (is->is_rule == fr) {
 772                                 fr_stinsert(isn, 0, ifs);
 773                                 MUTEX_EXIT(&isn->is_lock);
 774                                 break;
 775                         }
 776 
 777                 if (is == NULL) {
 778                         KFREE(isn);
 779                         isn = NULL;
 780                 }
 781                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
 782 
 783                 return (isn == NULL) ? ESRCH : 0;
 784         }
 785 
 786         return 0;
 787 }
 788 
 789 
 790 /* ------------------------------------------------------------------------ */
 791 /* Function:   fr_stinsert                                                  */
 792 /* Returns:    Nil                                                          */
 793 /* Parameters: is(I)  - pointer to state structure                          */
 794 /*             rev(I) - flag indicating forward/reverse direction of packet */
 795 /*                                                                          */
 796 /* Inserts a state structure into the hash table (for lookups) and the list */
 797 /* of state entries (for enumeration).  Resolves all of the interface names */
 798 /* to pointers and adjusts running stats for the hash table as appropriate. */
 799 /*                                                                          */
 800 /* Locking: it is assumed that some kind of lock on ipf_state is held.      */
 801 /*          Exits with is_lock initialised and held.                        */
 802 /* ------------------------------------------------------------------------ */
 803 void fr_stinsert(is, rev, ifs)
 804 ipstate_t *is;
 805 int rev;
 806 ipf_stack_t *ifs;
 807 {
 808         frentry_t *fr;
 809         u_int hv;
 810         int i;
 811 
 812         MUTEX_INIT(&is->is_lock, "ipf state entry");
 813 
 814         fr = is->is_rule;
 815         if (fr != NULL) {
 816                 MUTEX_ENTER(&fr->fr_lock);
 817                 fr->fr_ref++;
 818                 fr->fr_statecnt++;
 819                 MUTEX_EXIT(&fr->fr_lock);
 820         }
 821 
 822         /*
 823          * Look up all the interface names in the state entry.
 824          */
 825         for (i = 0; i < 4; i++) {
 826                 if (is->is_ifp[i] != NULL)
 827                         continue;
 828                 is->is_ifp[i] = fr_resolvenic(is->is_ifname[i], is->is_v, ifs);
 829         }
 830 
 831         /*
 832          * If we could trust is_hv, then the modulous would not be needed, but
 833          * when running with IPFILTER_SYNC, this stops bad values.
 834          */
 835         hv = is->is_hv % ifs->ifs_fr_statesize;
 836         is->is_hv = hv;
 837 
 838         /*
 839          * We need to get both of these locks...the first because it is
 840          * possible that once the insert is complete another packet might
 841          * come along, match the entry and want to update it.
 842          */
 843         MUTEX_ENTER(&is->is_lock);
 844         MUTEX_ENTER(&ifs->ifs_ipf_stinsert);
 845 
 846         /*
 847          * add into list table.
 848          */
 849         if (ifs->ifs_ips_list != NULL)
 850                 ifs->ifs_ips_list->is_pnext = &is->is_next;
 851         is->is_pnext = &ifs->ifs_ips_list;
 852         is->is_next = ifs->ifs_ips_list;
 853         ifs->ifs_ips_list = is;
 854 
 855         if (ifs->ifs_ips_table[hv] != NULL)
 856                 ifs->ifs_ips_table[hv]->is_phnext = &is->is_hnext;
 857         else
 858                 ifs->ifs_ips_stats.iss_inuse++;
 859         is->is_phnext = ifs->ifs_ips_table + hv;
 860         is->is_hnext = ifs->ifs_ips_table[hv];
 861         ifs->ifs_ips_table[hv] = is;
 862         ifs->ifs_ips_stats.iss_bucketlen[hv]++;
 863         ifs->ifs_ips_num++;
 864         MUTEX_EXIT(&ifs->ifs_ipf_stinsert);
 865 
 866         fr_setstatequeue(is, rev, ifs);
 867 }
 868 
 869 /* ------------------------------------------------------------------------ */
 870 /* Function:    fr_match_ipv4addrs                                          */
 871 /* Returns:     int -   2 strong match (same addresses, same direction)     */
 872 /*                      1 weak match (same address, opposite direction)     */
 873 /*                      0 no match                                          */
 874 /*                                                                          */
 875 /* Function matches IPv4 addresses.                                         */
 876 /* ------------------------------------------------------------------------ */
 877 static int fr_match_ipv4addrs(is1, is2)
 878 ipstate_t *is1;
 879 ipstate_t *is2;
 880 {
 881         int     rv;
 882 
 883         if (is1->is_saddr == is2->is_saddr && is1->is_daddr == is2->is_daddr)
 884                 rv = 2;
 885         else if (is1->is_saddr == is2->is_daddr &&
 886             is1->is_daddr == is2->is_saddr)
 887                 rv = 1;
 888         else
 889                 rv = 0;
 890 
 891         return (rv);
 892 }
 893 
 894 /* ------------------------------------------------------------------------ */
 895 /* Function:    fr_match_ipv6addrs                                          */
 896 /* Returns:     int -   2 strong match (same addresses, same direction)     */
 897 /*                      1 weak match (same addresses, opposite direction)   */
 898 /*                      0 no match                                          */
 899 /*                                                                          */
 900 /* Function matches IPv6 addresses.                                         */
 901 /* ------------------------------------------------------------------------ */
 902 static int fr_match_ipv6addrs(is1, is2)
 903 ipstate_t *is1;
 904 ipstate_t *is2;
 905 {
 906         int     rv;
 907 
 908         if (IP6_EQ(&is1->is_src, &is2->is_src) &&
 909             IP6_EQ(&is1->is_dst, &is2->is_dst))
 910                 rv = 2;
 911         else if (IP6_EQ(&is1->is_src, &is2->is_dst) &&
 912             IP6_EQ(&is1->is_dst, &is2->is_src)) {
 913                 rv = 1;
 914         }
 915         else
 916                 rv = 0;
 917 
 918         return (rv);
 919 }
 920 /* ------------------------------------------------------------------------ */
 921 /* Function:    fr_match_addresses                                          */
 922 /* Returns:     int -   2 strong match (same addresses, same direction)     */
 923 /*                      1 weak match (same address, opposite directions)    */
 924 /*                      0 no match                                          */
 925 /* Parameters:  is1, is2 pointers to states we are checking                 */
 926 /*                                                                          */
 927 /* Matches addresses, function uses fr_match_ipvXaddrs() to deal with IPv4  */
 928 /* and IPv6 address format.                                                 */
 929 /* ------------------------------------------------------------------------ */
 930 static int fr_match_addresses(is1, is2)
 931 ipstate_t *is1;
 932 ipstate_t *is2;
 933 {
 934         int     rv;
 935 
 936         if (is1->is_v == 4) {
 937                 rv = fr_match_ipv4addrs(is1, is2);
 938         } else {
 939                 rv = fr_match_ipv6addrs(is1, is2);
 940         }
 941 
 942         return (rv);
 943 }
 944 
 945 /* ------------------------------------------------------------------------ */
 946 /* Function:    fr_match_ppairs                                             */
 947 /* Returns:     int -   2 strong match (same ports, same direction)         */
 948 /*                      1 weak match (same ports, different direction)      */
 949 /*                      0 no match                                          */
 950 /* Parameters   ppairs1, ppairs - src, dst ports we want to match.          */
 951 /*                                                                          */
 952 /* Matches two port_pair_t types (port pairs). Each port pair contains      */
 953 /* src, dst port, which belong to session (state entry).                    */
 954 /* ------------------------------------------------------------------------ */
 955 static int fr_match_ppairs(ppairs1, ppairs2)
 956 port_pair_t *ppairs1;
 957 port_pair_t *ppairs2;
 958 {
 959         int     rv;
 960 
 961         if (ppairs1->pp_sport == ppairs2->pp_sport &&
 962             ppairs1->pp_dport == ppairs2->pp_dport)
 963                 rv = 2;
 964         else if (ppairs1->pp_sport == ppairs2->pp_dport &&
 965                     ppairs1->pp_dport == ppairs2->pp_sport)
 966                 rv = 1;
 967         else
 968                 rv = 0;
 969 
 970         return (rv);
 971 }
 972 
 973 /* ------------------------------------------------------------------------ */
 974 /* Function:    fr_match_l4_hdr                                             */
 975 /* Returns:     int -   0 no match,                                         */
 976 /*                      1 weak match (same ports, different directions)     */
 977 /*                      2 strong match (same ports, same direction)         */
 978 /* Parameters   is1, is2 - states we want to match                          */
 979 /*                                                                          */
 980 /* Function matches L4 header data (source ports for TCP, UDP, CallIds for  */
 981 /* GRE protocol).                                                           */
 982 /* ------------------------------------------------------------------------ */
 983 static int fr_match_l4_hdr(is1, is2)
 984 ipstate_t *is1;
 985 ipstate_t *is2;
 986 {
 987         int     rv = 0;
 988         port_pair_t     pp1;
 989         port_pair_t     pp2;
 990 
 991         if (is1->is_p != is2->is_p)
 992                 return (0);
 993 
 994         switch (is1->is_p) {
 995                 case    IPPROTO_TCP:
 996                         pp1.pp_sport = is1->is_ps.is_ts.ts_sport;
 997                         pp1.pp_dport = is1->is_ps.is_ts.ts_dport;
 998                         pp2.pp_sport = is2->is_ps.is_ts.ts_sport;
 999                         pp2.pp_dport = is2->is_ps.is_ts.ts_dport;
1000                         rv = fr_match_ppairs(&pp1, &pp2);
1001                         break;
1002                 case    IPPROTO_UDP:
1003                         pp1.pp_sport = is1->is_ps.is_us.us_sport;
1004                         pp1.pp_dport = is1->is_ps.is_us.us_dport;
1005                         pp2.pp_sport = is2->is_ps.is_us.us_sport;
1006                         pp2.pp_dport = is2->is_ps.is_us.us_dport;
1007                         rv = fr_match_ppairs(&pp1, &pp2);
1008                         break;
1009                 case    IPPROTO_GRE:
1010                         /* greinfo_t can be also interprted as port pair */
1011                         pp1.pp_sport = is1->is_ps.is_ug.gs_call[0];
1012                         pp1.pp_dport = is1->is_ps.is_ug.gs_call[1];
1013                         pp2.pp_sport = is2->is_ps.is_ug.gs_call[0];
1014                         pp2.pp_dport = is2->is_ps.is_ug.gs_call[1];
1015                         rv = fr_match_ppairs(&pp1, &pp2);
1016                         break;
1017                 case    IPPROTO_ICMP:
1018                 case    IPPROTO_ICMPV6:
1019                         if (bcmp(&is1->is_ps, &is2->is_ps, sizeof (icmpinfo_t)))
1020                                 rv = 1;
1021                         else
1022                                 rv = 0;
1023                         break;
1024                 default:
1025                         rv = 0;
1026         }
1027 
1028         return (rv);
1029 }
1030 
1031 /* ------------------------------------------------------------------------ */
1032 /* Function:    fr_matchstates                                              */
1033 /* Returns:     int - nonzero match, zero no match                          */
1034 /* Parameters   is1, is2 - states we want to match                          */
1035 /*                                                                          */
1036 /* The state entries are equal (identical match) if they belong to the same */
1037 /* session. Any time new state entry is being added the fr_addstate()       */
1038 /* function creates temporal state entry from the data it gets from IP and  */
1039 /* L4 header. The fr_matchstats() must be also aware of packet direction,   */
1040 /* which is also stored within the state entry. We should keep in mind the  */
1041 /* information about packet direction is spread accross L3 (addresses) and  */
1042 /* L4 (ports). There are three possible relationships betwee is1, is2:      */
1043 /*              - no match (match(is1, is2) == 0))                          */
1044 /*              - weak match same addresses (ports), but different          */
1045 /*                      directions (1)  (fr_match_xxxx(is1, is2) == 1)      */
1046 /*              - strong match same addresses (ports) and same directions   */
1047 /*                       (2) (fr_match_xxxx(is1, is2) == 2)                 */
1048 /*                                                                          */
1049 /* There are functions, which match match addresses (L3 header) in is1, is2 */
1050 /* and functions, which are used to compare ports (L4 header) data. We say  */
1051 /* the is1 and is2 are same (identical) if there is a match                 */
1052 /* (fr_match_l4_hdr(is1, is2) != 0) and matchlevels are same for entries    */
1053 /* (fr_match_l3_hdr(is1, is2) == fr_match_l4_hdr(is1, is2)) for is1, is2.   */
1054 /* Such requirement deals with case as follows:                             */
1055 /*      suppose there are two connections between hosts A, B. Connection 1: */
1056 /*                      a.a.a.a:12345 <=> b.b.b.b:54321                       */
1057 /*              Connection 2:                                               */
1058 /*                      a.a.a.a:54321 <=> b.b.b.b:12345                       */
1059 /* since we've introduced match levels into our fr_matchstates(), we are    */
1060 /* able to identify, which packets belong to connection A and which belong  */
1061 /* to connection B.     Assume there are two entries is1, is2. is1 has been */
1062 /* from con. 1 packet, which travelled from A to B:                         */
1063 /*                      a.a.a.a:12345 -> b.b.b.b:54321                           */
1064 /* while s2, has been created from packet which belongs to con. 2 and is    */
1065 /* also coming from A to B:                                                 */
1066 /*                      a.a.a.a:54321 -> b.b.b.b:12345                           */
1067 /* fr_match_l3_hdr(is1, is2) == 2 -> strong match, while                 */
1068 /* fr_match_l4_hdr(is1, is2) == 1 -> weak match. Since match levels are          */
1069 /* different the state entries are not identical -> no match as a final          */
1070 /* result.                                                                  */
1071 /* ------------------------------------------------------------------------ */
1072 static int fr_matchstates(is1, is2)
1073 ipstate_t *is1;
1074 ipstate_t *is2;
1075 {
1076         int     rv;
1077         int     amatch;
1078         int     pmatch;
1079 
1080         if (bcmp(&is1->is_pass, &is2->is_pass,
1081                 offsetof(struct ipstate, is_ps) -
1082                 offsetof(struct ipstate, is_pass)) == 0) {
1083 
1084                 pmatch = fr_match_l4_hdr(is1, is2);
1085                 amatch = fr_match_addresses(is1, is2);
1086                 /*
1087                  * If addresses match (amatch != 0), then 'match levels'
1088                  * must be same for matching entries. If amatch and pmatch
1089                  * have different values (different match levels), then
1090                  * is1 and is2 belong to different sessions.
1091                  */
1092                 rv = (amatch != 0) && (amatch == pmatch);
1093         }
1094         else
1095                 rv = 0;
1096 
1097         return (rv);
1098 }
1099 
1100 /* ------------------------------------------------------------------------ */
1101 /* Function:    fr_addstate                                                 */
1102 /* Returns:     ipstate_t* - NULL == failure, else pointer to new state     */
1103 /* Parameters:  fin(I)    - pointer to packet information                   */
1104 /*              stsave(O) - pointer to place to save pointer to created     */
1105 /*                          state structure.                                */
1106 /*              flags(I)  - flags to use when creating the structure        */
1107 /*                                                                          */
1108 /* Creates a new IP state structure from the packet information collected.  */
1109 /* Inserts it into the state table and appends to the bottom of the active  */
1110 /* list.  If the capacity of the table has reached the maximum allowed then */
1111 /* the call will fail and a flush is scheduled for the next timeout call.   */
1112 /* ------------------------------------------------------------------------ */
1113 ipstate_t *fr_addstate(fin, stsave, flags)
1114 fr_info_t *fin;
1115 ipstate_t **stsave;
1116 u_int flags;
1117 {
1118         ipstate_t *is, ips;
1119         struct icmp *ic;
1120         u_int pass, hv;
1121         frentry_t *fr;
1122         tcphdr_t *tcp;
1123         grehdr_t *gre;
1124         void *ifp;
1125         int out;
1126         ipf_stack_t *ifs = fin->fin_ifs;
1127 
1128         if (ifs->ifs_fr_state_lock ||
1129             (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)))
1130                 return NULL;
1131 
1132         if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN))
1133                 return NULL;
1134 
1135         /*
1136          * Trigger automatic call to fr_state_flush() if the
1137          * table has reached capacity specified by hi watermark.
1138          */
1139         if (ST_TAB_WATER_LEVEL(ifs) > ifs->ifs_state_flush_level_hi)
1140                 ifs->ifs_fr_state_doflush = 1;
1141 
1142         /*
1143          * If the max number of state entries has been reached, and there is no
1144          * limit on the state count for the rule, then do not continue.  In the
1145          * case where a limit exists, it's ok allow the entries to be created as
1146          * long as specified limit itself has not been reached. 
1147          *
1148          * Note that because the lock isn't held on fr, it is possible to exceed
1149          * the specified size of the table.  However, the cost of this is being
1150          * ignored here; as the number by which it can go over is a product of
1151          * the number of simultaneous threads that could be executing in here.
1152          * So, a limit of 100 won't result in 200, but could result in 101 or 102.
1153          *
1154          * Also note that, since the automatic flush should have been triggered
1155          * well before we reach the maximum number of state table entries, the
1156          * likelihood of reaching the max (and thus exceedng it) is minimal.
1157          */ 
1158         fr = fin->fin_fr;
1159         if (fr != NULL) {
1160                 if ((ifs->ifs_ips_num >= ifs->ifs_fr_statemax) &&
1161                     (fr->fr_statemax == 0)) {
1162                         ATOMIC_INCL(ifs->ifs_ips_stats.iss_max);
1163                         return NULL;
1164                 }
1165                 if ((fr->fr_statemax != 0) &&
1166                     (fr->fr_statecnt >= fr->fr_statemax)) {
1167                         ATOMIC_INCL(ifs->ifs_ips_stats.iss_maxref);
1168                         ifs->ifs_fr_state_doflush = 1;
1169                         return NULL;
1170                 }
1171         }
1172 
1173         ic = NULL;
1174         tcp = NULL;
1175         out = fin->fin_out;
1176         is = &ips;
1177         bzero((char *)is, sizeof(*is));
1178 
1179         if (fr == NULL) {
1180                 pass = ifs->ifs_fr_flags;
1181                 is->is_tag = FR_NOLOGTAG;
1182         } else {
1183                 pass = fr->fr_flags;
1184         }
1185 
1186         is->is_die = 1 + ifs->ifs_fr_ticks;
1187         /*
1188          * We want to check everything that is a property of this packet,
1189          * but we don't (automatically) care about it's fragment status as
1190          * this may change.
1191          */
1192         is->is_pass = pass;
1193         is->is_v = fin->fin_v;
1194         is->is_opt[0] = fin->fin_optmsk;
1195         is->is_optmsk[0] = 0xffffffff;
1196         /*
1197          * The reverse direction option mask will be set in fr_matchsrcdst(),
1198          * when we will see the first packet from the peer. We will leave it
1199          * as zero for now.
1200          */
1201         is->is_optmsk[1] = 0x0;
1202 
1203         if (is->is_v == 6) {
1204                 is->is_opt[0] &= ~0x8;
1205                 is->is_optmsk[0] &= ~0x8;
1206         }
1207         is->is_sec = fin->fin_secmsk;
1208         is->is_secmsk = 0xffff;
1209         is->is_auth = fin->fin_auth;
1210         is->is_authmsk = 0xffff;
1211 
1212         /*
1213          * Copy and calculate...
1214          */
1215         hv = (is->is_p = fin->fin_fi.fi_p);
1216         is->is_src = fin->fin_fi.fi_src;
1217         hv += is->is_saddr;
1218         is->is_dst = fin->fin_fi.fi_dst;
1219         hv += is->is_daddr;
1220 #ifdef  USE_INET6
1221         if (fin->fin_v == 6) {
1222                 /*
1223                  * For ICMPv6, we check to see if the destination address is
1224                  * a multicast address.  If it is, do not include it in the
1225                  * calculation of the hash because the correct reply will come
1226                  * back from a real address, not a multicast address.
1227                  */
1228                 if ((is->is_p == IPPROTO_ICMPV6) &&
1229                     IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
1230                         /*
1231                          * So you can do keep state with neighbour discovery.
1232                          *
1233                          * Here we could use the address from the neighbour
1234                          * solicit message to put in the state structure and
1235                          * we could use that without a wildcard flag too...
1236                          */
1237                         is->is_flags |= SI_W_DADDR;
1238                         hv -= is->is_daddr;
1239                 } else {
1240                         hv += is->is_dst.i6[1];
1241                         hv += is->is_dst.i6[2];
1242                         hv += is->is_dst.i6[3];
1243                 }
1244                 hv += is->is_src.i6[1];
1245                 hv += is->is_src.i6[2];
1246                 hv += is->is_src.i6[3];
1247         }
1248 #endif
1249         if ((fin->fin_v == 4) &&
1250             (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
1251                 if (fin->fin_out == 0) {
1252                         flags |= SI_W_DADDR|SI_CLONE;
1253                         hv -= is->is_daddr;
1254                 } else {
1255                         flags |= SI_W_SADDR|SI_CLONE;
1256                         hv -= is->is_saddr;
1257                 }
1258         }
1259 
1260         switch (is->is_p)
1261         {
1262 #ifdef  USE_INET6
1263         case IPPROTO_ICMPV6 :
1264                 ic = fin->fin_dp;
1265 
1266                 switch (ic->icmp_type)
1267                 {
1268                 case ICMP6_ECHO_REQUEST :
1269                         is->is_icmp.ici_type = ic->icmp_type;
1270                         hv += (is->is_icmp.ici_id = ic->icmp_id);
1271                         break;
1272                 case ICMP6_MEMBERSHIP_QUERY :
1273                 case ND_ROUTER_SOLICIT :
1274                 case ND_NEIGHBOR_SOLICIT :
1275                 case ICMP6_NI_QUERY :
1276                         is->is_icmp.ici_type = ic->icmp_type;
1277                         break;
1278                 default :
1279                         return NULL;
1280                 }
1281                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_icmp);
1282                 break;
1283 #endif
1284         case IPPROTO_ICMP :
1285                 ic = fin->fin_dp;
1286 
1287                 switch (ic->icmp_type)
1288                 {
1289                 case ICMP_ECHO :
1290                 case ICMP_ECHOREPLY :
1291                 case ICMP_TSTAMP :
1292                 case ICMP_IREQ :
1293                 case ICMP_MASKREQ :
1294                         is->is_icmp.ici_type = ic->icmp_type;
1295                         hv += (is->is_icmp.ici_id = ic->icmp_id);
1296                         break;
1297                 default :
1298                         return NULL;
1299                 }
1300                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_icmp);
1301                 break;
1302 
1303         case IPPROTO_GRE :
1304                 gre = fin->fin_dp;
1305 
1306                 is->is_gre.gs_flags = gre->gr_flags;
1307                 is->is_gre.gs_ptype = gre->gr_ptype;
1308                 if (GRE_REV(is->is_gre.gs_flags) == 1) {
1309                         is->is_call[0] = fin->fin_data[0];
1310                         is->is_call[1] = fin->fin_data[1];
1311                 }
1312                 break;
1313 
1314         case IPPROTO_TCP :
1315                 tcp = fin->fin_dp;
1316 
1317                 if (tcp->th_flags & TH_RST)
1318                         return NULL;
1319                 /*
1320                  * The endian of the ports doesn't matter, but the ack and
1321                  * sequence numbers do as we do mathematics on them later.
1322                  */
1323                 is->is_sport = htons(fin->fin_data[0]);
1324                 is->is_dport = htons(fin->fin_data[1]);
1325                 if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1326                         hv += is->is_sport;
1327                         hv += is->is_dport;
1328                 }
1329 
1330                 /*
1331                  * If this is a real packet then initialise fields in the
1332                  * state information structure from the TCP header information.
1333                  */
1334 
1335                 is->is_maxdwin = 1;
1336                 is->is_maxswin = ntohs(tcp->th_win);
1337                 if (is->is_maxswin == 0)
1338                         is->is_maxswin = 1;
1339 
1340                 if ((fin->fin_flx & FI_IGNORE) == 0) {
1341                         is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
1342                                       (TCP_OFF(tcp) << 2) +
1343                                       ((tcp->th_flags & TH_SYN) ? 1 : 0) +
1344                                       ((tcp->th_flags & TH_FIN) ? 1 : 0);
1345                         is->is_maxsend = is->is_send;
1346 
1347                         /*
1348                          * Window scale option is only present in
1349                          * SYN/SYN-ACK packet.
1350                          */
1351                         if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
1352                             TH_SYN &&
1353                             (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1354                                 if (fr_tcpoptions(fin, tcp,
1355                                         &is->is_tcp.ts_data[0]) == -1) {
1356                                         fin->fin_flx |= FI_BAD;
1357                                 }
1358                         }
1359 
1360                         if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
1361                                 fr_checknewisn(fin, is);
1362                                 fr_fixoutisn(fin, is);
1363                         }
1364 
1365                         if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1366                                 flags |= IS_TCPFSM;
1367                         else {
1368                                 is->is_maxdwin = is->is_maxswin * 2;
1369                                 is->is_dend = ntohl(tcp->th_ack);
1370                                 is->is_maxdend = ntohl(tcp->th_ack);
1371                                 is->is_maxdwin *= 2;
1372                         }
1373                 }
1374 
1375                 /*
1376                  * If we're creating state for a starting connection, start the
1377                  * timer on it as we'll never see an error if it fails to
1378                  * connect.
1379                  */
1380                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_tcp);
1381                 break;
1382 
1383         case IPPROTO_UDP :
1384                 tcp = fin->fin_dp;
1385 
1386                 is->is_sport = htons(fin->fin_data[0]);
1387                 is->is_dport = htons(fin->fin_data[1]);
1388                 if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1389                         hv += tcp->th_dport;
1390                         hv += tcp->th_sport;
1391                 }
1392                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_udp);
1393                 break;
1394 
1395         default :
1396                 break;
1397         }
1398         hv = DOUBLE_HASH(hv, ifs);
1399         is->is_hv = hv;
1400         is->is_rule = fr;
1401         is->is_flags = flags & IS_INHERITED;
1402 
1403         /*
1404          * Look for identical state.
1405          */
1406         for (is = ifs->ifs_ips_table[is->is_hv % ifs->ifs_fr_statesize];
1407              is != NULL;
1408              is = is->is_hnext) {
1409                 if (fr_matchstates(&ips, is) == 1)
1410                         break;
1411         }
1412 
1413         /*
1414          * we've found a matching state -> state already exists,
1415          * we are not going to add a duplicate record.
1416          */
1417         if (is != NULL)
1418                 return NULL;
1419 
1420         if (ifs->ifs_ips_stats.iss_bucketlen[hv] >= ifs->ifs_fr_state_maxbucket) {
1421                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_bucketfull);
1422                 return NULL;
1423         }
1424         KMALLOC(is, ipstate_t *);
1425         if (is == NULL) {
1426                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_nomem);
1427                 return NULL;
1428         }
1429         bcopy((char *)&ips, (char *)is, sizeof(*is));
1430         /*
1431          * Do not do the modulous here, it is done in fr_stinsert().
1432          */
1433         if (fr != NULL) {
1434                 (void) strncpy(is->is_group, fr->fr_group, FR_GROUPLEN);
1435                 if (fr->fr_age[0] != 0) {
1436                         is->is_tqehead[0] = 
1437                             fr_addtimeoutqueue(&ifs->ifs_ips_utqe,
1438                                                fr->fr_age[0], ifs);
1439                         is->is_sti.tqe_flags |= TQE_RULEBASED;
1440                 }
1441                 if (fr->fr_age[1] != 0) {
1442                         is->is_tqehead[1] = 
1443                             fr_addtimeoutqueue(&ifs->ifs_ips_utqe,
1444                                                fr->fr_age[1], ifs);
1445                         is->is_sti.tqe_flags |= TQE_RULEBASED;
1446                 }
1447                 is->is_tag = fr->fr_logtag;
1448 
1449                 is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1450                 is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1451                 is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1452 
1453                 if (((ifp = fr->fr_ifas[1]) != NULL) &&
1454                     (ifp != (void *)-1)) {
1455                         COPYIFNAME(ifp, is->is_ifname[(out << 1) + 1], fr->fr_v);
1456                 }
1457                 if (((ifp = fr->fr_ifas[2]) != NULL) &&
1458                     (ifp != (void *)-1)) {
1459                         COPYIFNAME(ifp, is->is_ifname[(1 - out) << 1], fr->fr_v);
1460                 }
1461                 if (((ifp = fr->fr_ifas[3]) != NULL) &&
1462                     (ifp != (void *)-1)) {
1463                         COPYIFNAME(ifp, is->is_ifname[((1 - out) << 1) + 1], fr->fr_v);
1464                 }
1465         }
1466 
1467         is->is_ifp[out << 1] = fin->fin_ifp;
1468         if (fin->fin_ifp != NULL) {
1469                 COPYIFNAME(fin->fin_ifp, is->is_ifname[out << 1], fin->fin_v);
1470         }
1471 
1472         is->is_ref = 1;
1473         is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1474         is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1475         is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1476         is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1477         if ((fin->fin_flx & FI_IGNORE) == 0) {
1478                 is->is_pkts[out] = 1;
1479                 is->is_bytes[out] = fin->fin_plen;
1480                 is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1481                 is->is_flx[out][0] &= ~FI_OOW;
1482         }
1483 
1484         if (pass & FR_STSTRICT)
1485                 is->is_flags |= IS_STRICT;
1486 
1487         if (pass & FR_STATESYNC)
1488                 is->is_flags |= IS_STATESYNC;
1489 
1490         if (flags & (SI_WILDP|SI_WILDA)) {
1491                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_wild);
1492         }
1493         is->is_rulen = fin->fin_rule;
1494 
1495 
1496         if (pass & FR_LOGFIRST)
1497                 is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1498 
1499         READ_ENTER(&ifs->ifs_ipf_state);
1500         is->is_me = stsave;
1501 
1502         fr_stinsert(is, fin->fin_rev, ifs);
1503 
1504         if (fin->fin_p == IPPROTO_TCP) {
1505                 /*
1506                 * If we're creating state for a starting connection, start the
1507                 * timer on it as we'll never see an error if it fails to
1508                 * connect.
1509                 */
1510                 (void) fr_tcp_age(&is->is_sti, fin, ifs->ifs_ips_tqtqb,
1511                                   is->is_flags);
1512                 MUTEX_EXIT(&is->is_lock);
1513 #ifdef  IPFILTER_SCAN
1514                 if ((is->is_flags & SI_CLONE) == 0)
1515                         (void) ipsc_attachis(is);
1516 #endif
1517         } else {
1518                 MUTEX_EXIT(&is->is_lock);
1519         }
1520 #ifdef  IPFILTER_SYNC
1521         if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1522                 is->is_sync = ipfsync_new(SMC_STATE, fin, is);
1523 #endif
1524         if (ifs->ifs_ipstate_logging)
1525                 ipstate_log(is, ISL_NEW, ifs);
1526 
1527         if (IFS_CFWLOG(ifs))
1528                 ipf_log_cfwlog(is, ISL_NEW, ifs);
1529 
1530         RWLOCK_EXIT(&ifs->ifs_ipf_state);
1531         fin->fin_rev = IP6_NEQ(&is->is_dst, &fin->fin_daddr);
1532         fin->fin_flx |= FI_STATE;
1533         if (fin->fin_flx & FI_FRAG)
1534                 (void) fr_newfrag(fin, pass ^ FR_KEEPSTATE);
1535 
1536         return is;
1537 }
1538 
1539 
1540 /* ------------------------------------------------------------------------ */
1541 /* Function:    fr_tcpoptions                                               */
1542 /* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1543 /* Parameters:  fin(I) - pointer to packet information                      */
1544 /*              tcp(I) - pointer to TCP packet header                       */
1545 /*              td(I)  - pointer to TCP data held as part of the state      */
1546 /*                                                                          */
1547 /* Look after the TCP header for any options and deal with those that are   */
1548 /* present.  Record details about those that we recogise.                   */
1549 /* ------------------------------------------------------------------------ */
1550 static int fr_tcpoptions(fin, tcp, td)
1551 fr_info_t *fin;
1552 tcphdr_t *tcp;
1553 tcpdata_t *td;
1554 {
1555         int off, mlen, ol, i, len, retval;
1556         char buf[64], *s, opt;
1557         mb_t *m = NULL;
1558 
1559         len = (TCP_OFF(tcp) << 2);
1560         if (fin->fin_dlen < len)
1561                 return 0;
1562         len -= sizeof(*tcp);
1563 
1564         off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1565 
1566         m = fin->fin_m;
1567         mlen = MSGDSIZE(m) - off;
1568         if (len > mlen) {
1569                 len = mlen;
1570                 retval = 0;
1571         } else {
1572                 retval = 1;
1573         }
1574 
1575         COPYDATA(m, off, len, buf);
1576 
1577         for (s = buf; len > 0; ) {
1578                 opt = *s;
1579                 if (opt == TCPOPT_EOL)
1580                         break;
1581                 else if (opt == TCPOPT_NOP)
1582                         ol = 1;
1583                 else {
1584                         if (len < 2)
1585                                 break;
1586                         ol = (int)*(s + 1);
1587                         if (ol < 2 || ol > len)
1588                                 break;
1589 
1590                         /*
1591                          * Extract the TCP options we are interested in out of
1592                          * the header and store them in the the tcpdata struct.
1593                          */
1594                         switch (opt)
1595                         {
1596                         case TCPOPT_WINDOW :
1597                                 if (ol == TCPOLEN_WINDOW) {
1598                                         i = (int)*(s + 2);
1599                                         if (i > TCP_WSCALE_MAX)
1600                                                 i = TCP_WSCALE_MAX;
1601                                         else if (i < 0)
1602                                                 i = 0;
1603                                         td->td_winscale = i;
1604                                         td->td_winflags |= TCP_WSCALE_SEEN |
1605                                                             TCP_WSCALE_FIRST;
1606                                 } else
1607                                         retval = -1;
1608                                 break;
1609                         case TCPOPT_MAXSEG :
1610                                 /*
1611                                  * So, if we wanted to set the TCP MAXSEG,
1612                                  * it should be done here...
1613                                  */
1614                                 if (ol == TCPOLEN_MAXSEG) {
1615                                         i = (int)*(s + 2);
1616                                         i <<= 8;
1617                                         i += (int)*(s + 3);
1618                                         td->td_maxseg = i;
1619                                 } else
1620                                         retval = -1;
1621                                 break;
1622                         case TCPOPT_SACK_PERMITTED :
1623                                 if (ol == TCPOLEN_SACK_PERMITTED)
1624                                         td->td_winflags |= TCP_SACK_PERMIT;
1625                                 else
1626                                         retval = -1;
1627                                 break;
1628                         }
1629                 }
1630                 len -= ol;
1631                 s += ol;
1632         }
1633         return retval;
1634 }
1635 
1636 
1637 /* ------------------------------------------------------------------------ */
1638 /* Function:    fr_tcpstate                                                 */
1639 /* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1640 /* Parameters:  fin(I)   - pointer to packet information                    */
1641 /*              tcp(I)   - pointer to TCP packet header                     */
1642 /*              is(I)  - pointer to master state structure                  */
1643 /*                                                                          */
1644 /* Check to see if a packet with TCP headers fits within the TCP window.    */
1645 /* Change timeout depending on whether new packet is a SYN-ACK returning    */
1646 /* for a SYN or a RST or FIN which indicate time to close up shop.          */
1647 /* ------------------------------------------------------------------------ */
1648 static int fr_tcpstate(fin, tcp, is)
1649 fr_info_t *fin;
1650 tcphdr_t *tcp;
1651 ipstate_t *is;
1652 {
1653         int source, ret = 0, flags;
1654         tcpdata_t  *fdata, *tdata;
1655         ipf_stack_t *ifs = fin->fin_ifs;
1656 
1657         source = !fin->fin_rev;
1658         if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) && 
1659             (ntohs(is->is_sport) != fin->fin_data[0]))
1660                 source = 0;
1661         fdata = &is->is_tcp.ts_data[!source];
1662         tdata = &is->is_tcp.ts_data[source];
1663 
1664         MUTEX_ENTER(&is->is_lock);
1665 
1666         /*
1667          * If a SYN packet is received for a connection that is in a half
1668          * closed state, then move its state entry to deletetq. In such case
1669          * the SYN packet will be consequently dropped. This allows new state
1670          * entry to be created with a retransmited SYN packet.
1671          */
1672         if ((tcp->th_flags & TH_OPENING) == TH_SYN) {
1673                 if ((is->is_state[source] > IPF_TCPS_ESTABLISHED) &&
1674                     (is->is_state[!source] > IPF_TCPS_ESTABLISHED)) {
1675                         is->is_state[source] = IPF_TCPS_CLOSED;
1676                         is->is_state[!source] = IPF_TCPS_CLOSED;
1677                         /*
1678                          * Do not update is->is_sti.tqe_die in case state entry
1679                          * is already present in deletetq. It prevents state
1680                          * entry ttl update by retransmitted SYN packets, which
1681                          * may arrive before timer tick kicks off. The SYN
1682                          * packet will be dropped again.
1683                          */
1684                         if (is->is_sti.tqe_ifq != &ifs->ifs_ips_deletetq)
1685                                 fr_movequeue(&is->is_sti, is->is_sti.tqe_ifq,
1686                                         &fin->fin_ifs->ifs_ips_deletetq,
1687                                         fin->fin_ifs);
1688 
1689                         MUTEX_EXIT(&is->is_lock);
1690                         return 0;
1691                 }
1692         }
1693 
1694         if (fr_tcpinwindow(fin, fdata, tdata, tcp, is->is_flags)) {
1695 #ifdef  IPFILTER_SCAN
1696                 if (is->is_flags & (IS_SC_CLIENT|IS_SC_SERVER)) {
1697                         ipsc_packet(fin, is);
1698                         if (FR_ISBLOCK(is->is_pass)) {
1699                                 MUTEX_EXIT(&is->is_lock);
1700                                 return 1;
1701                         }
1702                 }
1703 #endif
1704 
1705                 /*
1706                  * Nearing end of connection, start timeout.
1707                  */
1708                 ret = fr_tcp_age(&is->is_sti, fin, ifs->ifs_ips_tqtqb,
1709                                  is->is_flags);
1710                 if (ret == 0) {
1711                         MUTEX_EXIT(&is->is_lock);
1712                         return 0;
1713                 }
1714 
1715                 /*
1716                  * set s0's as appropriate.  Use syn-ack packet as it
1717                  * contains both pieces of required information.
1718                  */
1719                 /*
1720                  * Window scale option is only present in SYN/SYN-ACK packet.
1721                  * Compare with ~TH_FIN to mask out T/TCP setups.
1722                  */
1723                 flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
1724                 if (flags == (TH_SYN|TH_ACK)) {
1725                         is->is_s0[source] = ntohl(tcp->th_ack);
1726                         is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
1727                         if (TCP_OFF(tcp) > (sizeof (tcphdr_t) >> 2)) {
1728                                 (void) fr_tcpoptions(fin, tcp, fdata);
1729                         }
1730                         if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
1731                                 fr_checknewisn(fin, is);
1732                 } else if (flags == TH_SYN) {
1733                         is->is_s0[source] = ntohl(tcp->th_seq) + 1;
1734                         if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2)))
1735                                 (void) fr_tcpoptions(fin, tcp, fdata);
1736 
1737                         if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
1738                                 fr_checknewisn(fin, is);
1739 
1740                 }
1741                 ret = 1;
1742         } else
1743                 fin->fin_flx |= FI_OOW;
1744         MUTEX_EXIT(&is->is_lock);
1745         return ret;
1746 }
1747 
1748 
1749 /* ------------------------------------------------------------------------ */
1750 /* Function:    fr_checknewisn                                              */
1751 /* Returns:     Nil                                                         */
1752 /* Parameters:  fin(I)   - pointer to packet information                    */
1753 /*              is(I)  - pointer to master state structure                  */
1754 /*                                                                          */
1755 /* Check to see if this TCP connection is expecting and needs a new         */
1756 /* sequence number for a particular direction of the connection.            */
1757 /*                                                                          */
1758 /* NOTE: This does not actually change the sequence numbers, only gets new  */
1759 /* one ready.                                                               */
1760 /* ------------------------------------------------------------------------ */
1761 static void fr_checknewisn(fin, is)
1762 fr_info_t *fin;
1763 ipstate_t *is;
1764 {
1765         u_32_t sumd, old, new;
1766         tcphdr_t *tcp;
1767         int i;
1768 
1769         i = fin->fin_rev;
1770         tcp = fin->fin_dp;
1771 
1772         if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
1773             ((i == 1) && !(is->is_flags & IS_ISNACK))) {
1774                 old = ntohl(tcp->th_seq);
1775                 new = fr_newisn(fin);
1776                 is->is_isninc[i] = new - old;
1777                 CALC_SUMD(old, new, sumd);
1778                 is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
1779 
1780                 is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
1781         }
1782 }
1783 
1784 
1785 /* ------------------------------------------------------------------------ */
1786 /* Function:    fr_tcpinwindow                                              */
1787 /* Returns:     int - 1 == packet inside TCP "window", 0 == not inside.     */
1788 /* Parameters:  fin(I)   - pointer to packet information                    */
1789 /*              fdata(I) - pointer to tcp state informatio (forward)        */
1790 /*              tdata(I) - pointer to tcp state informatio (reverse)        */
1791 /*              tcp(I)   - pointer to TCP packet header                     */
1792 /*                                                                          */
1793 /* Given a packet has matched addresses and ports, check to see if it is    */
1794 /* within the TCP data window.  In a show of generosity, allow packets that */
1795 /* are within the window space behind the current sequence # as well.       */
1796 /* ------------------------------------------------------------------------ */
1797 int fr_tcpinwindow(fin, fdata, tdata, tcp, flags)
1798 fr_info_t *fin;
1799 tcpdata_t  *fdata, *tdata;
1800 tcphdr_t *tcp;
1801 int flags;
1802 {
1803         tcp_seq seq, ack, end;
1804         int ackskew, tcpflags;
1805         u_32_t win, maxwin;
1806         int dsize, inseq;
1807 
1808         /*
1809          * Find difference between last checked packet and this packet.
1810          */
1811         tcpflags = tcp->th_flags;
1812         seq = ntohl(tcp->th_seq);
1813         ack = ntohl(tcp->th_ack);
1814 
1815         if (tcpflags & TH_SYN)
1816                 win = ntohs(tcp->th_win);
1817         else
1818                 win = ntohs(tcp->th_win) << fdata->td_winscale;
1819 
1820         /*
1821          * win 0 means the receiving endpoint has closed the window, because it
1822          * has not enough memory to receive data from sender. In such case we
1823          * are pretending window size to be 1 to let TCP probe data through.
1824          * TCP probe data can be either 0 or 1 octet of data, the RFC does not
1825          * state this accurately, so we have to allow 1 octet (win = 1) even if
1826          * the window is closed (win == 0).
1827          */
1828         if (win == 0)
1829                 win = 1;
1830 
1831         dsize = fin->fin_dlen - (TCP_OFF(tcp) << 2) +
1832                 ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
1833 
1834         /*
1835          * if window scaling is present, the scaling is only allowed
1836          * for windows not in the first SYN packet. In that packet the
1837          * window is 65535 to specify the largest window possible
1838          * for receivers not implementing the window scale option.
1839          * Currently, we do not assume TTCP here. That means that
1840          * if we see a second packet from a host (after the initial
1841          * SYN), we can assume that the receiver of the SYN did
1842          * already send back the SYN/ACK (and thus that we know if
1843          * the receiver also does window scaling)
1844          */
1845         if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
1846                 fdata->td_winflags &= ~TCP_WSCALE_FIRST;
1847                 fdata->td_maxwin = win;
1848         }
1849 
1850         end = seq + dsize;
1851 
1852         if ((fdata->td_end == 0) &&
1853             (!(flags & IS_TCPFSM) ||
1854              ((tcpflags & TH_OPENING) == TH_OPENING))) {
1855                 /*
1856                  * Must be a (outgoing) SYN-ACK in reply to a SYN.
1857                  */
1858                 fdata->td_end = end - 1;
1859                 fdata->td_maxwin = 1;
1860                 fdata->td_maxend = end + win;
1861         }
1862 
1863         if (!(tcpflags & TH_ACK)) {  /* Pretend an ack was sent */
1864                 ack = tdata->td_end;
1865         } else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
1866                    (ack == 0)) {
1867                 /* gross hack to get around certain broken tcp stacks */
1868                 ack = tdata->td_end;
1869         }
1870 
1871         maxwin = tdata->td_maxwin;
1872         ackskew = tdata->td_end - ack;
1873 
1874         /*
1875          * Strict sequencing only allows in-order delivery.
1876          */
1877         if ((flags & IS_STRICT) != 0) {
1878                 if (seq != fdata->td_end) {
1879                         DTRACE_PROBE(strict_check);
1880                         return 0;
1881                 }
1882         }
1883 
1884 #define SEQ_GE(a,b)     ((int)((a) - (b)) >= 0)
1885 #define SEQ_GT(a,b)     ((int)((a) - (b)) > 0)
1886         inseq = 0;
1887         DTRACE_PROBE4(
1888                 dyn_params,
1889                 int, dsize,
1890                 int, ackskew,
1891                 int, maxwin,
1892                 int, win
1893         );
1894         if (
1895 #if defined(_KERNEL)
1896                 /* 
1897                  * end <-> s + n
1898                  * maxend <-> ack + win
1899                  * this is upperbound check
1900                  */
1901             (SEQ_GE(fdata->td_maxend, end)) &&
1902                 /*
1903                  * this is lowerbound check
1904                  */
1905             (SEQ_GE(seq, fdata->td_end - maxwin)) &&
1906 #endif
1907 /* XXX what about big packets */
1908 #define MAXACKWINDOW 66000
1909             (-ackskew <= (MAXACKWINDOW)) &&
1910             ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
1911                 inseq = 1;
1912         /*
1913          * Microsoft Windows will send the next packet to the right of the
1914          * window if SACK is in use.
1915          */
1916         } else if ((seq == fdata->td_maxend) && (ackskew == 0) &&
1917             (fdata->td_winflags & TCP_SACK_PERMIT) &&
1918             (tdata->td_winflags & TCP_SACK_PERMIT)) {
1919                 inseq = 1;
1920         /*
1921          * RST ACK with SEQ equal to 0 is sent by some OSes (i.e. Solaris) as a
1922          * response to initial SYN packet, when  there is no application
1923          * listeing to on a port, where the SYN packet has came to.
1924          */
1925         } else if ((seq == 0) && (tcpflags == (TH_RST|TH_ACK)) &&
1926                         (ackskew >= -1) && (ackskew <= 1)) {
1927                 inseq = 1;
1928         } else if (!(flags & IS_TCPFSM)) {
1929 
1930                 if (!(fdata->td_winflags &
1931                             (TCP_WSCALE_SEEN|TCP_WSCALE_FIRST))) {
1932                         /*
1933                          * No TCPFSM and no window scaling, so make some
1934                          * extra guesses.
1935                          */
1936                         if ((seq == fdata->td_maxend) && (ackskew == 0))
1937                                 inseq = 1;
1938                         else if (SEQ_GE(seq + maxwin, fdata->td_end - maxwin))
1939                                 inseq = 1;
1940                 }
1941         }
1942 
1943         if (inseq) {
1944                 /* if ackskew < 0 then this should be due to fragmented
1945                  * packets. There is no way to know the length of the
1946                  * total packet in advance.
1947                  * We do know the total length from the fragment cache though.
1948                  * Note however that there might be more sessions with
1949                  * exactly the same source and destination parameters in the
1950                  * state cache (and source and destination is the only stuff
1951                  * that is saved in the fragment cache). Note further that
1952                  * some TCP connections in the state cache are hashed with
1953                  * sport and dport as well which makes it not worthwhile to
1954                  * look for them.
1955                  * Thus, when ackskew is negative but still seems to belong
1956                  * to this session, we bump up the destinations end value.
1957                  */
1958                 if (ackskew < 0) {
1959                         DTRACE_PROBE2(end_update_td,
1960                                 int, tdata->td_end,
1961                                 int, ack
1962                         );
1963                         tdata->td_end = ack;
1964                 }
1965 
1966                 /* update max window seen */
1967                 if (fdata->td_maxwin < win) {
1968                         DTRACE_PROBE2(win_update_fd,
1969                                 int, fdata->td_maxwin,
1970                                 int, win
1971                         );
1972                         fdata->td_maxwin = win;
1973                 }
1974 
1975                 if (SEQ_GT(end, fdata->td_end)) {
1976                         DTRACE_PROBE2(end_update_fd,
1977                                 int, fdata->td_end,
1978                                 int, end
1979                         );
1980                         fdata->td_end = end;
1981                 }
1982 
1983                 if (SEQ_GE(ack + win, tdata->td_maxend)) {
1984                         DTRACE_PROBE2(max_end_update_td,
1985                                 int, tdata->td_maxend,
1986                                 int, ack + win
1987                         );
1988                         tdata->td_maxend = ack + win;
1989                 }
1990 
1991                 return 1;
1992         }
1993         fin->fin_flx |= FI_OOW;
1994 
1995 #if defined(_KERNEL)
1996         if (!(SEQ_GE(seq, fdata->td_end - maxwin)))
1997                 fin->fin_flx |= FI_NEG_OOW;
1998 #endif
1999 
2000         return 0;
2001 }
2002 
2003 
2004 /* ------------------------------------------------------------------------ */
2005 /* Function:    fr_stclone                                                  */
2006 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
2007 /*                           else pointer to new state structure            */
2008 /* Parameters:  fin(I) - pointer to packet information                      */
2009 /*              tcp(I) - pointer to TCP/UDP header                          */
2010 /*              is(I)  - pointer to master state structure                  */
2011 /*                                                                          */
2012 /* Create a "duplcate" state table entry from the master.                   */
2013 /* ------------------------------------------------------------------------ */
2014 static ipstate_t *fr_stclone(fin, tcp, is)
2015 fr_info_t *fin;
2016 tcphdr_t *tcp;
2017 ipstate_t *is;
2018 {
2019         ipstate_t *clone;
2020         u_32_t send;
2021         ipf_stack_t *ifs = fin->fin_ifs;
2022 
2023         /*
2024          * Trigger automatic call to fr_state_flush() if the
2025          * table has reached capacity specified by hi watermark.
2026          */
2027         if (ST_TAB_WATER_LEVEL(ifs) > ifs->ifs_state_flush_level_hi)
2028                 ifs->ifs_fr_state_doflush = 1;
2029 
2030         /*
2031          * If automatic flushing did not do its job, and the table
2032          * has filled up, don't try to create a new entry.  A NULL
2033          * return will indicate that the cloning has failed.
2034          */
2035         if (ifs->ifs_ips_num >= ifs->ifs_fr_statemax) {
2036                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_max);
2037                 return NULL;
2038         }
2039 
2040         KMALLOC(clone, ipstate_t *);
2041         if (clone == NULL)
2042                 return NULL;
2043         bcopy((char *)is, (char *)clone, sizeof(*clone));
2044 
2045         MUTEX_NUKE(&clone->is_lock);
2046 
2047         clone->is_die = ONE_DAY + ifs->ifs_fr_ticks;
2048         clone->is_state[0] = 0;
2049         clone->is_state[1] = 0;
2050         send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2051                 ((tcp->th_flags & TH_SYN) ? 1 : 0) +
2052                 ((tcp->th_flags & TH_FIN) ? 1 : 0);
2053 
2054         if (fin->fin_rev == 1) {
2055                 clone->is_dend = send;
2056                 clone->is_maxdend = send;
2057                 clone->is_send = 0;
2058                 clone->is_maxswin = 1;
2059                 clone->is_maxdwin = ntohs(tcp->th_win);
2060                 if (clone->is_maxdwin == 0)
2061                         clone->is_maxdwin = 1;
2062         } else {
2063                 clone->is_send = send;
2064                 clone->is_maxsend = send;
2065                 clone->is_dend = 0;
2066                 clone->is_maxdwin = 1;
2067                 clone->is_maxswin = ntohs(tcp->th_win);
2068                 if (clone->is_maxswin == 0)
2069                         clone->is_maxswin = 1;
2070         }
2071 
2072         clone->is_flags &= ~SI_CLONE;
2073         clone->is_flags |= SI_CLONED;
2074         fr_stinsert(clone, fin->fin_rev, ifs);
2075         clone->is_ref = 1;
2076         if (clone->is_p == IPPROTO_TCP) {
2077                 (void) fr_tcp_age(&clone->is_sti, fin, ifs->ifs_ips_tqtqb,
2078                                   clone->is_flags);
2079         }
2080         MUTEX_EXIT(&clone->is_lock);
2081 #ifdef  IPFILTER_SCAN
2082         (void) ipsc_attachis(is);
2083 #endif
2084 #ifdef  IPFILTER_SYNC
2085         if (is->is_flags & IS_STATESYNC)
2086                 clone->is_sync = ipfsync_new(SMC_STATE, fin, clone);
2087 #endif
2088         return clone;
2089 }
2090 
2091 
2092 /* ------------------------------------------------------------------------ */
2093 /* Function:    fr_matchsrcdst                                              */
2094 /* Returns:     Nil                                                         */
2095 /* Parameters:  fin(I) - pointer to packet information                      */
2096 /*              is(I)  - pointer to state structure                         */
2097 /*              src(I) - pointer to source address                          */
2098 /*              dst(I) - pointer to destination address                     */
2099 /*              tcp(I) - pointer to TCP/UDP header                          */
2100 /*                                                                          */
2101 /* Match a state table entry against an IP packet.  The logic below is that */
2102 /* ret gets set to one if the match succeeds, else remains 0.  If it is     */
2103 /* still 0 after the test. no match.                                        */
2104 /* ------------------------------------------------------------------------ */
2105 static ipstate_t *fr_matchsrcdst(fin, is, src, dst, tcp, cmask)
2106 fr_info_t *fin;
2107 ipstate_t *is;
2108 i6addr_t *src, *dst;
2109 tcphdr_t *tcp;
2110 u_32_t cmask;
2111 {
2112         int ret = 0, rev, out, flags, flx = 0, idx;
2113         u_short sp, dp;
2114         u_32_t cflx;
2115         void *ifp;
2116         ipf_stack_t *ifs = fin->fin_ifs;
2117 
2118         rev = IP6_NEQ(&is->is_dst, dst);
2119         ifp = fin->fin_ifp;
2120         out = fin->fin_out;
2121         flags = is->is_flags;
2122         sp = 0;
2123         dp = 0;
2124 
2125         if (tcp != NULL) {
2126                 sp = htons(fin->fin_sport);
2127                 dp = ntohs(fin->fin_dport);
2128         }
2129         if (!rev) {
2130                 if (tcp != NULL) {
2131                         if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
2132                                 rev = 1;
2133                         else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
2134                                 rev = 1;
2135                 }
2136         }
2137 
2138         idx = (out << 1) + rev;
2139 
2140         /*
2141          * If the interface for this 'direction' is set, make sure it matches.
2142          * An interface name that is not set matches any, as does a name of *.
2143          */
2144         if ((is->is_ifp[idx] == NULL &&
2145             (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) ||
2146             is->is_ifp[idx] == ifp)
2147                 ret = 1;
2148 
2149         if (ret == 0) {
2150                 DTRACE_PROBE(no_match_on_iface);
2151                 return NULL;
2152         }
2153         ret = 0;
2154 
2155         /*
2156          * Match addresses and ports.
2157          */
2158         if (rev == 0) {
2159                 if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
2160                     (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
2161                         if (tcp) {
2162                                 if ((sp == is->is_sport || flags & SI_W_SPORT)&&
2163                                     (dp == is->is_dport || flags & SI_W_DPORT))
2164                                         ret = 1;
2165                         } else {
2166                                 ret = 1;
2167                         }
2168                 }
2169         } else {
2170                 if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
2171                     (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
2172                         if (tcp) {
2173                                 if ((dp == is->is_sport || flags & SI_W_SPORT)&&
2174                                     (sp == is->is_dport || flags & SI_W_DPORT))
2175                                         ret = 1;
2176                         } else {
2177                                 ret = 1;
2178                         }
2179                 }
2180         }
2181 
2182         if (ret == 0) {
2183                 DTRACE_PROBE(no_match_on_addrs);
2184                 return NULL;
2185         }
2186         /*
2187          * Whether or not this should be here, is questionable, but the aim
2188          * is to get this out of the main line.
2189          */
2190         if (tcp == NULL)
2191                 flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
2192 
2193         /*
2194          * Only one of the source or destination address can be flaged as a
2195          * wildcard.  Fill in the missing address, if set.
2196          * For IPv6, if the address being copied in is multicast, then
2197          * don't reset the wild flag - multicast causes it to be set in the
2198          * first place!
2199          */
2200         if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
2201                 fr_ip_t *fi = &fin->fin_fi;
2202 
2203                 if ((flags & SI_W_SADDR) != 0) {
2204                         if (rev == 0) {
2205 #ifdef USE_INET6
2206                                 if (is->is_v == 6 &&
2207                                     IN6_IS_ADDR_MULTICAST(&fi->fi_src.in6))
2208                                         /*EMPTY*/;
2209                                 else
2210 #endif
2211                                 {
2212                                         is->is_src = fi->fi_src;
2213                                         is->is_flags &= ~SI_W_SADDR;
2214                                 }
2215                         } else {
2216 #ifdef USE_INET6
2217                                 if (is->is_v == 6 &&
2218                                     IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
2219                                         /*EMPTY*/;
2220                                 else
2221 #endif
2222                                 {
2223                                         is->is_src = fi->fi_dst;
2224                                         is->is_flags &= ~SI_W_SADDR;
2225                                 }
2226                         }
2227                 } else if ((flags & SI_W_DADDR) != 0) {
2228                         if (rev == 0) {
2229 #ifdef USE_INET6
2230                                 if (is->is_v == 6 &&
2231                                     IN6_IS_ADDR_MULTICAST(&fi->fi_dst.in6))
2232                                         /*EMPTY*/;
2233                                 else
2234 #endif
2235                                 {
2236                                         is->is_dst = fi->fi_dst;
2237                                         is->is_flags &= ~SI_W_DADDR;
2238                                 }
2239                         } else {
2240 #ifdef USE_INET6
2241                                 if (is->is_v == 6 &&
2242                                     IN6_IS_ADDR_MULTICAST(&fi->fi_src.in6))
2243                                         /*EMPTY*/;
2244                                 else
2245 #endif
2246                                 {
2247                                         is->is_dst = fi->fi_src;
2248                                         is->is_flags &= ~SI_W_DADDR;
2249                                 }
2250                         }
2251                 }
2252                 if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
2253                         ATOMIC_DECL(ifs->ifs_ips_stats.iss_wild);
2254                 }
2255         }
2256 
2257         flx = fin->fin_flx & cmask;
2258         cflx = is->is_flx[out][rev];
2259 
2260         /*
2261          * Match up any flags set from IP options.
2262          */
2263         if ((cflx && (flx != (cflx & cmask))) ||
2264             ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
2265             ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
2266             ((fin->fin_auth & is->is_authmsk) != is->is_auth)) {
2267                 DTRACE_PROBE4(no_match_on_flags,
2268                     int, (cflx && (flx != (cflx & cmask))),
2269                     int,
2270                     ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]),
2271                     int, ((fin->fin_secmsk & is->is_secmsk) != is->is_sec),
2272                     int, ((fin->fin_auth & is->is_authmsk) != is->is_auth)
2273                 );
2274                 return NULL;
2275         }
2276         /*
2277          * Only one of the source or destination port can be flagged as a
2278          * wildcard.  When filling it in, fill in a copy of the matched entry
2279          * if it has the cloning flag set.
2280          */
2281         if ((fin->fin_flx & FI_IGNORE) != 0) {
2282                 fin->fin_rev = rev;
2283                 return is;
2284         }
2285 
2286         if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
2287                 if ((flags & SI_CLONE) != 0) {
2288                         ipstate_t *clone;
2289 
2290                         clone = fr_stclone(fin, tcp, is);
2291                         if (clone == NULL)
2292                                 return NULL;
2293                         is = clone;
2294                 } else {
2295                         ATOMIC_DECL(ifs->ifs_ips_stats.iss_wild);
2296                 }
2297 
2298                 if ((flags & SI_W_SPORT) != 0) {
2299                         if (rev == 0) {
2300                                 is->is_sport = sp;
2301                                 is->is_send = ntohl(tcp->th_seq);
2302                         } else {
2303                                 is->is_sport = dp;
2304                                 is->is_send = ntohl(tcp->th_ack);
2305                         }
2306                         is->is_maxsend = is->is_send + 1;
2307                 } else if ((flags & SI_W_DPORT) != 0) {
2308                         if (rev == 0) {
2309                                 is->is_dport = dp;
2310                                 is->is_dend = ntohl(tcp->th_ack);
2311                         } else {
2312                                 is->is_dport = sp;
2313                                 is->is_dend = ntohl(tcp->th_seq);
2314                         }
2315                         is->is_maxdend = is->is_dend + 1;
2316                 }
2317                 is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
2318                 if ((flags & SI_CLONED) && ifs->ifs_ipstate_logging)
2319                         ipstate_log(is, ISL_CLONE, ifs);
2320                 if ((flags & SI_CLONED) && IFS_CFWLOG(ifs))
2321                         ipf_log_cfwlog(is, ISL_CLONE, ifs);
2322         }
2323 
2324         ret = -1;
2325 
2326         if (is->is_flx[out][rev] == 0) {
2327                 is->is_flx[out][rev] = flx;
2328                 /*
2329                  * If we are dealing with the first packet coming in reverse
2330                  * direction (sent by peer), then we have to set options into
2331                  * state.
2332                  */
2333                 if (rev == 1 && is->is_optmsk[1] == 0x0) {
2334                         is->is_optmsk[1] = 0xffffffff;
2335                         is->is_opt[1] = fin->fin_optmsk;
2336                         DTRACE_PROBE(set_rev_opts);
2337                 }
2338                 if (is->is_v == 6) {
2339                         is->is_opt[rev] &= ~0x8;
2340                         is->is_optmsk[rev] &= ~0x8;
2341                 }
2342         }
2343 
2344         /*
2345          * Check if the interface name for this "direction" is set and if not,
2346          * fill it in.
2347          */
2348         if (is->is_ifp[idx] == NULL &&
2349             (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
2350                 is->is_ifp[idx] = ifp;
2351                 COPYIFNAME(ifp, is->is_ifname[idx], fin->fin_v);
2352         }
2353         fin->fin_rev = rev;
2354         return is;
2355 }
2356 
2357 
2358 /* ------------------------------------------------------------------------ */
2359 /* Function:    fr_checkicmpmatchingstate                                   */
2360 /* Returns:     Nil                                                         */
2361 /* Parameters:  fin(I) - pointer to packet information                      */
2362 /*                                                                          */
2363 /* If we've got an ICMP error message, using the information stored in the  */
2364 /* ICMP packet, look for a matching state table entry.                      */
2365 /*                                                                          */
2366 /* If we return NULL then no lock on ipf_state is held.                     */
2367 /* If we return non-null then a read-lock on ipf_state is held.             */
2368 /* ------------------------------------------------------------------------ */
2369 static ipstate_t *fr_checkicmpmatchingstate(fin)
2370 fr_info_t *fin;
2371 {
2372         ipstate_t *is, **isp;
2373         u_short sport, dport;
2374         u_char  pr;
2375         int backward, i, oi;
2376         i6addr_t dst, src;
2377         struct icmp *ic;
2378         u_short savelen;
2379         icmphdr_t *icmp;
2380         fr_info_t ofin;
2381         tcphdr_t *tcp;
2382         int len;
2383         ip_t *oip;
2384         u_int hv;
2385         ipf_stack_t *ifs = fin->fin_ifs;
2386 
2387         /*
2388          * Does it at least have the return (basic) IP header ?
2389          * Is it an actual recognised ICMP error type?
2390          * Only a basic IP header (no options) should be with
2391          * an ICMP error header.
2392          */
2393         if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
2394             (fin->fin_plen < ICMPERR_MINPKTLEN) ||
2395             !(fin->fin_flx & FI_ICMPERR))
2396                 return NULL;
2397         ic = fin->fin_dp;
2398 
2399         oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
2400         /*
2401          * Check if the at least the old IP header (with options) and
2402          * 8 bytes of payload is present.
2403          */
2404         if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2))
2405                 return NULL;
2406 
2407         /*
2408          * Sanity Checks.
2409          */
2410         len = fin->fin_dlen - ICMPERR_ICMPHLEN;
2411         if ((len <= 0) || ((IP_HL(oip) << 2) > len))
2412                 return NULL;
2413 
2414         /*
2415          * Is the buffer big enough for all of it ?  It's the size of the IP
2416          * header claimed in the encapsulated part which is of concern.  It
2417          * may be too big to be in this buffer but not so big that it's
2418          * outside the ICMP packet, leading to TCP deref's causing problems.
2419          * This is possible because we don't know how big oip_hl is when we
2420          * do the pullup early in fr_check() and thus can't guarantee it is
2421          * all here now.
2422          */
2423 #ifdef  _KERNEL
2424         {
2425         mb_t *m;
2426 
2427         m = fin->fin_m;
2428 # if defined(MENTAT)
2429         if ((char *)oip + len > (char *)m->b_wptr)
2430                 return NULL;
2431 # else
2432         if ((char *)oip + len > (char *)fin->fin_ip + m->m_len)
2433                 return NULL;
2434 # endif
2435         }
2436 #endif
2437         bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
2438 
2439         /*
2440          * in the IPv4 case we must zero the i6addr union otherwise
2441          * the IP6_EQ and IP6_NEQ macros produce the wrong results because
2442          * of the 'junk' in the unused part of the union
2443          */
2444         bzero((char *)&src, sizeof(src));
2445         bzero((char *)&dst, sizeof(dst));
2446 
2447         /*
2448          * we make an fin entry to be able to feed it to
2449          * matchsrcdst note that not all fields are encessary
2450          * but this is the cleanest way. Note further we fill
2451          * in fin_mp such that if someone uses it we'll get
2452          * a kernel panic. fr_matchsrcdst does not use this.
2453          *
2454          * watch out here, as ip is in host order and oip in network
2455          * order. Any change we make must be undone afterwards, like
2456          * oip->ip_off - it is still in network byte order so fix it.
2457          */
2458         savelen = oip->ip_len;
2459         oip->ip_len = len;
2460         oip->ip_off = ntohs(oip->ip_off);
2461 
2462         ofin.fin_flx = FI_NOCKSUM;
2463         ofin.fin_v = 4;
2464         ofin.fin_ip = oip;
2465         ofin.fin_m = NULL;      /* if dereferenced, panic XXX */
2466         ofin.fin_mp = NULL;     /* if dereferenced, panic XXX */
2467         ofin.fin_plen = fin->fin_dlen - ICMPERR_ICMPHLEN;
2468         (void) fr_makefrip(IP_HL(oip) << 2, oip, &ofin);
2469         ofin.fin_ifp = fin->fin_ifp;
2470         ofin.fin_out = !fin->fin_out;
2471         /*
2472          * Reset the short and bad flag here because in fr_matchsrcdst()
2473          * the flags for the current packet (fin_flx) are compared against
2474          * those for the existing session.
2475          */
2476         ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2477 
2478         /*
2479          * Put old values of ip_len and ip_off back as we don't know
2480          * if we have to forward the packet (or process it again.
2481          */
2482         oip->ip_len = savelen;
2483         oip->ip_off = htons(oip->ip_off);
2484 
2485         switch (oip->ip_p)
2486         {
2487         case IPPROTO_ICMP :
2488                 /*
2489                  * an ICMP error can only be generated as a result of an
2490                  * ICMP query, not as the response on an ICMP error
2491                  *
2492                  * XXX theoretically ICMP_ECHOREP and the other reply's are
2493                  * ICMP query's as well, but adding them here seems strange XXX
2494                  */
2495                 if ((ofin.fin_flx & FI_ICMPERR) != 0)
2496                         return NULL;
2497 
2498                 /*
2499                  * perform a lookup of the ICMP packet in the state table
2500                  */
2501                 icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2502                 hv = (pr = oip->ip_p);
2503                 src.in4 = oip->ip_src;
2504                 hv += src.in4.s_addr;
2505                 dst.in4 = oip->ip_dst;
2506                 hv += dst.in4.s_addr;
2507                 hv += icmp->icmp_id;
2508                 hv = DOUBLE_HASH(hv, ifs);
2509 
2510                 READ_ENTER(&ifs->ifs_ipf_state);
2511                 for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
2512                         isp = &is->is_hnext;
2513                         if ((is->is_p != pr) || (is->is_v != 4))
2514                                 continue;
2515                         if (is->is_pass & FR_NOICMPERR)
2516                                 continue;
2517                         is = fr_matchsrcdst(&ofin, is, &src, &dst,
2518                                             NULL, FI_ICMPCMP);
2519                         if (is != NULL) {
2520                                 if ((is->is_pass & FR_NOICMPERR) != 0) {
2521                                         RWLOCK_EXIT(&ifs->ifs_ipf_state);
2522                                         return NULL;
2523                                 }
2524                                 /*
2525                                  * i  : the index of this packet (the icmp
2526                                  *      unreachable)
2527                                  * oi : the index of the original packet found
2528                                  *      in the icmp header (i.e. the packet
2529                                  *      causing this icmp)
2530                                  * backward : original packet was backward
2531                                  *      compared to the state
2532                                  */
2533                                 backward = IP6_NEQ(&is->is_src, &src);
2534                                 fin->fin_rev = !backward;
2535                                 i = (!backward << 1) + fin->fin_out;
2536                                 oi = (backward << 1) + ofin.fin_out;
2537                                 if (is->is_icmppkts[i] > is->is_pkts[oi])
2538                                         continue;
2539                                 ifs->ifs_ips_stats.iss_hits++;
2540                                 is->is_icmppkts[i]++;
2541                                 return is;
2542                         }
2543                 }
2544                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
2545                 return NULL;
2546         case IPPROTO_TCP :
2547         case IPPROTO_UDP :
2548                 break;
2549         default :
2550                 return NULL;
2551         }
2552 
2553         tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2554         dport = tcp->th_dport;
2555         sport = tcp->th_sport;
2556 
2557         hv = (pr = oip->ip_p);
2558         src.in4 = oip->ip_src;
2559         hv += src.in4.s_addr;
2560         dst.in4 = oip->ip_dst;
2561         hv += dst.in4.s_addr;
2562         hv += dport;
2563         hv += sport;
2564         hv = DOUBLE_HASH(hv, ifs);
2565 
2566         READ_ENTER(&ifs->ifs_ipf_state);
2567         for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
2568                 isp = &is->is_hnext;
2569                 /*
2570                  * Only allow this icmp though if the
2571                  * encapsulated packet was allowed through the
2572                  * other way around. Note that the minimal amount
2573                  * of info present does not allow for checking against
2574                  * tcp internals such as seq and ack numbers.   Only the
2575                  * ports are known to be present and can be even if the
2576                  * short flag is set.
2577                  */
2578                 if ((is->is_p == pr) && (is->is_v == 4) &&
2579                     (is = fr_matchsrcdst(&ofin, is, &src, &dst,
2580                                          tcp, FI_ICMPCMP))) {
2581                         /*
2582                          * i  : the index of this packet (the icmp unreachable)
2583                          * oi : the index of the original packet found in the
2584                          *      icmp header (i.e. the packet causing this icmp)
2585                          * backward : original packet was backward compared to
2586                          *            the state
2587                          */
2588                         backward = IP6_NEQ(&is->is_src, &src);
2589                         fin->fin_rev = !backward;
2590                         i = (!backward << 1) + fin->fin_out;
2591                         oi = (backward << 1) + ofin.fin_out;
2592 
2593                         if (((is->is_pass & FR_NOICMPERR) != 0) ||
2594                             (is->is_icmppkts[i] > is->is_pkts[oi]))
2595                                 break;
2596                         ifs->ifs_ips_stats.iss_hits++;
2597                         is->is_icmppkts[i]++;
2598                         /*
2599                          * we deliberately do not touch the timeouts
2600                          * for the accompanying state table entry.
2601                          * It remains to be seen if that is correct. XXX
2602                          */
2603                         return is;
2604                 }
2605         }
2606         RWLOCK_EXIT(&ifs->ifs_ipf_state);
2607         return NULL;
2608 }
2609 
2610 
2611 /* ------------------------------------------------------------------------ */
2612 /* Function:    fr_ipsmove                                                  */
2613 /* Returns:     Nil                                                         */
2614 /* Parameters:  is(I) - pointer to state table entry                        */
2615 /*              hv(I) - new hash value for state table entry                */
2616 /* Write Locks: ipf_state                                                   */
2617 /*                                                                          */
2618 /* Move a state entry from one position in the hash table to another.       */
2619 /* ------------------------------------------------------------------------ */
2620 static void fr_ipsmove(is, hv, ifs)
2621 ipstate_t *is;
2622 u_int hv;
2623 ipf_stack_t *ifs;
2624 {
2625         ipstate_t **isp;
2626         u_int hvm;
2627 
2628         ASSERT(rw_read_locked(&ifs->ifs_ipf_state.ipf_lk) == 0);
2629 
2630         hvm = is->is_hv;
2631         /*
2632          * Remove the hash from the old location...
2633          */
2634         isp = is->is_phnext;
2635         if (is->is_hnext)
2636                 is->is_hnext->is_phnext = isp;
2637         *isp = is->is_hnext;
2638         if (ifs->ifs_ips_table[hvm] == NULL)
2639                 ifs->ifs_ips_stats.iss_inuse--;
2640         ifs->ifs_ips_stats.iss_bucketlen[hvm]--;
2641 
2642         /*
2643          * ...and put the hash in the new one.
2644          */
2645         hvm = DOUBLE_HASH(hv, ifs);
2646         is->is_hv = hvm;
2647         isp = &ifs->ifs_ips_table[hvm];
2648         if (*isp)
2649                 (*isp)->is_phnext = &is->is_hnext;
2650         else
2651                 ifs->ifs_ips_stats.iss_inuse++;
2652         ifs->ifs_ips_stats.iss_bucketlen[hvm]++;
2653         is->is_phnext = isp;
2654         is->is_hnext = *isp;
2655         *isp = is;
2656 }
2657 
2658 
2659 /* ------------------------------------------------------------------------ */
2660 /* Function:    fr_stlookup                                                 */
2661 /* Returns:     ipstate_t* - NULL == no matching state found,               */
2662 /*                           else pointer to state information is returned  */
2663 /* Parameters:  fin(I) - pointer to packet information                      */
2664 /*              tcp(I) - pointer to TCP/UDP header.                         */
2665 /*                                                                          */
2666 /* Search the state table for a matching entry to the packet described by   */
2667 /* the contents of *fin.                                                    */
2668 /*                                                                          */
2669 /* If we return NULL then no lock on ipf_state is held.                     */
2670 /* If we return non-null then a read-lock on ipf_state is held.             */
2671 /* ------------------------------------------------------------------------ */
2672 ipstate_t *fr_stlookup(fin, tcp, ifqp)
2673 fr_info_t *fin;
2674 tcphdr_t *tcp;
2675 ipftq_t **ifqp;
2676 {
2677         u_int hv, hvm, pr, v, tryagain;
2678         ipstate_t *is, **isp;
2679         u_short dport, sport;
2680         i6addr_t src, dst;
2681         struct icmp *ic;
2682         ipftq_t *ifq;
2683         int oow;
2684         ipf_stack_t *ifs = fin->fin_ifs;
2685 
2686         is = NULL;
2687         ifq = NULL;
2688         tcp = fin->fin_dp;
2689         ic = (struct icmp *)tcp;
2690         hv = (pr = fin->fin_fi.fi_p);
2691         src = fin->fin_fi.fi_src;
2692         dst = fin->fin_fi.fi_dst;
2693         hv += src.in4.s_addr;
2694         hv += dst.in4.s_addr;
2695 
2696         v = fin->fin_fi.fi_v;
2697 #ifdef  USE_INET6
2698         if (v == 6) {
2699                 hv  += fin->fin_fi.fi_src.i6[1];
2700                 hv  += fin->fin_fi.fi_src.i6[2];
2701                 hv  += fin->fin_fi.fi_src.i6[3];
2702 
2703                 if ((fin->fin_p == IPPROTO_ICMPV6) &&
2704                     IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
2705                         hv -= dst.in4.s_addr;
2706                 } else {
2707                         hv += fin->fin_fi.fi_dst.i6[1];
2708                         hv += fin->fin_fi.fi_dst.i6[2];
2709                         hv += fin->fin_fi.fi_dst.i6[3];
2710                 }
2711         }
2712 #endif
2713         if ((v == 4) &&
2714             (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
2715                 if (fin->fin_out == 0) {
2716                         hv -= src.in4.s_addr;
2717                 } else {
2718                         hv -= dst.in4.s_addr;
2719                 }
2720         }
2721 
2722         /*
2723          * Search the hash table for matching packet header info.
2724          */
2725         switch (pr)
2726         {
2727 #ifdef  USE_INET6
2728         case IPPROTO_ICMPV6 :
2729                 tryagain = 0;
2730                 if (v == 6) {
2731                         if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
2732                             (ic->icmp_type == ICMP6_ECHO_REPLY)) {
2733                                 hv += ic->icmp_id;
2734                         }
2735                 }
2736                 READ_ENTER(&ifs->ifs_ipf_state);
2737 icmp6again:
2738                 hvm = DOUBLE_HASH(hv, ifs);
2739                 for (isp = &ifs->ifs_ips_table[hvm]; ((is = *isp) != NULL); ) {
2740                         isp = &is->is_hnext;
2741                         if ((is->is_p != pr) || (is->is_v != v))
2742                                 continue;
2743                         is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2744                         if (is != NULL &&
2745                             fr_matchicmpqueryreply(v, &is->is_icmp,
2746                                                    ic, fin->fin_rev)) {
2747                                 if (fin->fin_rev)
2748                                         ifq = &ifs->ifs_ips_icmpacktq;
2749                                 else
2750                                         ifq = &ifs->ifs_ips_icmptq;
2751                                 break;
2752                         }
2753                 }
2754 
2755                 if (is != NULL) {
2756                         if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
2757                                 hv += fin->fin_fi.fi_src.i6[0];
2758                                 hv += fin->fin_fi.fi_src.i6[1];
2759                                 hv += fin->fin_fi.fi_src.i6[2];
2760                                 hv += fin->fin_fi.fi_src.i6[3];
2761                                 fr_ipsmove(is, hv, ifs);
2762                                 MUTEX_DOWNGRADE(&ifs->ifs_ipf_state);
2763                         }
2764                         break;
2765                 }
2766                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
2767 
2768                 /*
2769                  * No matching icmp state entry. Perhaps this is a
2770                  * response to another state entry.
2771                  *
2772                  * XXX With some ICMP6 packets, the "other" address is already
2773                  * in the packet, after the ICMP6 header, and this could be
2774                  * used in place of the multicast address.  However, taking
2775                  * advantage of this requires some significant code changes
2776                  * to handle the specific types where that is the case.
2777                  */
2778                 if ((ifs->ifs_ips_stats.iss_wild != 0) && (v == 6) && (tryagain == 0) &&
2779                     !IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_src.in6)) {
2780                         hv -= fin->fin_fi.fi_src.i6[0];
2781                         hv -= fin->fin_fi.fi_src.i6[1];
2782                         hv -= fin->fin_fi.fi_src.i6[2];
2783                         hv -= fin->fin_fi.fi_src.i6[3];
2784                         tryagain = 1;
2785                         WRITE_ENTER(&ifs->ifs_ipf_state);
2786                         goto icmp6again;
2787                 }
2788 
2789                 is = fr_checkicmp6matchingstate(fin);
2790                 if (is != NULL)
2791                         return is;
2792                 break;
2793 #endif
2794 
2795         case IPPROTO_ICMP :
2796                 if (v == 4) {
2797                         hv += ic->icmp_id;
2798                 }
2799                 hv = DOUBLE_HASH(hv, ifs);
2800                 READ_ENTER(&ifs->ifs_ipf_state);
2801                 for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
2802                         isp = &is->is_hnext;
2803                         if ((is->is_p != pr) || (is->is_v != v))
2804                                 continue;
2805                         is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2806                         if (is != NULL &&
2807                             fr_matchicmpqueryreply(v, &is->is_icmp,
2808                                                    ic, fin->fin_rev)) {
2809                                 if (fin->fin_rev)
2810                                         ifq = &ifs->ifs_ips_icmpacktq;
2811                                 else
2812                                         ifq = &ifs->ifs_ips_icmptq;
2813                                 break;
2814                         }
2815                 }
2816                 if (is == NULL) {
2817                         RWLOCK_EXIT(&ifs->ifs_ipf_state);
2818                 }
2819                 break;
2820 
2821         case IPPROTO_TCP :
2822         case IPPROTO_UDP :
2823                 ifqp = NULL;
2824                 sport = htons(fin->fin_data[0]);
2825                 hv += sport;
2826                 dport = htons(fin->fin_data[1]);
2827                 hv += dport;
2828                 oow = 0;
2829                 tryagain = 0;
2830                 READ_ENTER(&ifs->ifs_ipf_state);
2831 retry_tcpudp:
2832                 hvm = DOUBLE_HASH(hv, ifs);
2833                 for (isp = &ifs->ifs_ips_table[hvm]; ((is = *isp) != NULL); ) {
2834                         isp = &is->is_hnext;
2835                         if ((is->is_p != pr) || (is->is_v != v))
2836                                 continue;
2837                         fin->fin_flx &= ~FI_OOW;
2838                         is = fr_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
2839                         if (is != NULL) {
2840                                 if (pr == IPPROTO_TCP) {
2841                                         if (!fr_tcpstate(fin, tcp, is)) {
2842                                                 oow |= fin->fin_flx & FI_OOW;
2843                                                 continue;
2844                                         }
2845                                 }
2846                                 break;
2847                         }
2848                 }
2849                 if (is != NULL) {
2850                         if (tryagain &&
2851                             !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
2852                                 hv += dport;
2853                                 hv += sport;
2854                                 fr_ipsmove(is, hv, ifs);
2855                                 MUTEX_DOWNGRADE(&ifs->ifs_ipf_state);
2856                         }
2857                         break;
2858                 }
2859                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
2860 
2861                 if (ifs->ifs_ips_stats.iss_wild) {
2862                         if (tryagain == 0) {
2863                                 hv -= dport;
2864                                 hv -= sport;
2865                         } else if (tryagain == 1) {
2866                                 hv = fin->fin_fi.fi_p;
2867                                 /*
2868                                  * If we try to pretend this is a reply to a
2869                                  * multicast/broadcast packet then we need to
2870                                  * exclude part of the address from the hash
2871                                  * calculation.
2872                                  */
2873                                 if (fin->fin_out == 0) {
2874                                         hv += src.in4.s_addr;
2875                                 } else {
2876                                         hv += dst.in4.s_addr;
2877                                 }
2878                                 hv += dport;
2879                                 hv += sport;
2880                         }
2881                         tryagain++;
2882                         if (tryagain <= 2) {
2883                                 WRITE_ENTER(&ifs->ifs_ipf_state);
2884                                 goto retry_tcpudp;
2885                         }
2886                 }
2887                 fin->fin_flx |= oow;
2888                 break;
2889 
2890 #if 0
2891         case IPPROTO_GRE :
2892                 gre = fin->fin_dp;
2893                 if (GRE_REV(gre->gr_flags) == 1) {
2894                         hv += gre->gr_call;
2895                 }
2896                 /* FALLTHROUGH */
2897 #endif
2898         default :
2899                 ifqp = NULL;
2900                 hvm = DOUBLE_HASH(hv, ifs);
2901                 READ_ENTER(&ifs->ifs_ipf_state);
2902                 for (isp = &ifs->ifs_ips_table[hvm]; ((is = *isp) != NULL); ) {
2903                         isp = &is->is_hnext;
2904                         if ((is->is_p != pr) || (is->is_v != v))
2905                                 continue;
2906                         is = fr_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
2907                         if (is != NULL) {
2908                                 ifq = &ifs->ifs_ips_iptq;
2909                                 break;
2910                         }
2911                 }
2912                 if (is == NULL) {
2913                         RWLOCK_EXIT(&ifs->ifs_ipf_state);
2914                 }
2915                 break;
2916         }
2917 
2918         if ((is != NULL) && ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
2919             (is->is_tqehead[fin->fin_rev] != NULL))
2920                 ifq = is->is_tqehead[fin->fin_rev];
2921         if (ifq != NULL && ifqp != NULL)
2922                 *ifqp = ifq;
2923         return is;
2924 }
2925 
2926 
2927 /* ------------------------------------------------------------------------ */
2928 /* Function:    fr_updatestate                                              */
2929 /* Returns:     Nil                                                         */
2930 /* Parameters:  fin(I) - pointer to packet information                      */
2931 /*              is(I)  - pointer to state table entry                       */
2932 /* Read Locks:  ipf_state                                                   */
2933 /*                                                                          */
2934 /* Updates packet and byte counters for a newly received packet.  Seeds the */
2935 /* fragment cache with a new entry as required.                             */
2936 /* ------------------------------------------------------------------------ */
2937 void fr_updatestate(fin, is, ifq)
2938 fr_info_t *fin;
2939 ipstate_t *is;
2940 ipftq_t *ifq;
2941 {
2942         ipftqent_t *tqe;
2943         int i, pass;
2944         ipf_stack_t *ifs = fin->fin_ifs;
2945 
2946         i = (fin->fin_rev << 1) + fin->fin_out;
2947 
2948         /*
2949          * For TCP packets, ifq == NULL.  For all others, check if this new
2950          * queue is different to the last one it was on and move it if so.
2951          */
2952         tqe = &is->is_sti;
2953         MUTEX_ENTER(&is->is_lock);
2954         if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
2955                 ifq = is->is_tqehead[fin->fin_rev];
2956 
2957         if (ifq != NULL)
2958                 fr_movequeue(tqe, tqe->tqe_ifq, ifq, ifs);
2959 
2960         is->is_pkts[i]++;
2961         fin->fin_pktnum = is->is_pkts[i] + is->is_icmppkts[i];
2962         is->is_bytes[i] += fin->fin_plen;
2963         MUTEX_EXIT(&is->is_lock);
2964 
2965 #ifdef  IPFILTER_SYNC
2966         if (is->is_flags & IS_STATESYNC)
2967                 ipfsync_update(SMC_STATE, fin, is->is_sync);
2968 #endif
2969 
2970         ATOMIC_INCL(ifs->ifs_ips_stats.iss_hits);
2971 
2972         fin->fin_fr = is->is_rule;
2973 
2974         /*
2975          * If this packet is a fragment and the rule says to track fragments,
2976          * then create a new fragment cache entry.
2977          */
2978         pass = is->is_pass;
2979         if ((fin->fin_flx & FI_FRAG) && FR_ISPASS(pass))
2980                 (void) fr_newfrag(fin, pass ^ FR_KEEPSTATE);
2981 }
2982 
2983 
2984 /* ------------------------------------------------------------------------ */
2985 /* Function:    fr_checkstate                                               */
2986 /* Returns:     frentry_t* - NULL == search failed,                         */
2987 /*                           else pointer to rule for matching state        */
2988 /* Parameters:  ifp(I)   - pointer to interface                             */
2989 /*              passp(I) - pointer to filtering result flags                */
2990 /*                                                                          */
2991 /* Check if a packet is associated with an entry in the state table.        */
2992 /* ------------------------------------------------------------------------ */
2993 frentry_t *fr_checkstate(fin, passp)
2994 fr_info_t *fin;
2995 u_32_t *passp;
2996 {
2997         ipstate_t *is;
2998         frentry_t *fr;
2999         tcphdr_t *tcp;
3000         ipftq_t *ifq;
3001         u_int pass;
3002         ipf_stack_t *ifs = fin->fin_ifs;
3003 
3004         if (ifs->ifs_fr_state_lock || (ifs->ifs_ips_list == NULL) ||
3005             (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)))
3006                 return NULL;
3007 
3008         is = NULL;
3009         if ((fin->fin_flx & FI_TCPUDP) ||
3010             (fin->fin_fi.fi_p == IPPROTO_ICMP)
3011 #ifdef  USE_INET6
3012             || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
3013 #endif
3014             )
3015                 tcp = fin->fin_dp;
3016         else
3017                 tcp = NULL;
3018 
3019         /*
3020          * Search the hash table for matching packet header info.
3021          */
3022         ifq = NULL;
3023         is = fr_stlookup(fin, tcp, &ifq);
3024         switch (fin->fin_p)
3025         {
3026 #ifdef  USE_INET6
3027         case IPPROTO_ICMPV6 :
3028                 if (is != NULL)
3029                         break;
3030                 if (fin->fin_v == 6) {
3031                         is = fr_checkicmp6matchingstate(fin);
3032                         if (is != NULL)
3033                                 goto matched;
3034                 }
3035                 break;
3036 #endif
3037         case IPPROTO_ICMP :
3038                 if (is != NULL)
3039                         break;
3040                 /*
3041                  * No matching icmp state entry. Perhaps this is a
3042                  * response to another state entry.
3043                  */
3044                 is = fr_checkicmpmatchingstate(fin);
3045                 if (is != NULL)
3046                         goto matched;
3047                 break;
3048         case IPPROTO_TCP :
3049                 if (is == NULL)
3050                         break;
3051 
3052                 if (is->is_pass & FR_NEWISN) {
3053                         if (fin->fin_out == 0)
3054                                 fr_fixinisn(fin, is);
3055                         else if (fin->fin_out == 1)
3056                                 fr_fixoutisn(fin, is);
3057                 }
3058                 break;
3059         default :
3060                 if (fin->fin_rev)
3061                         ifq = &ifs->ifs_ips_udpacktq;
3062                 else
3063                         ifq = &ifs->ifs_ips_udptq;
3064                 break;
3065         }
3066         if (is == NULL) {
3067                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_miss);
3068                 return NULL;
3069         }
3070 
3071 matched:
3072         fr = is->is_rule;
3073         if (fr != NULL) {
3074                 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
3075                         if (fin->fin_nattag == NULL) {
3076                                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
3077                                 return NULL;
3078                         }
3079                         if (fr_matchtag(&fr->fr_nattag, fin->fin_nattag) != 0) {
3080                                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
3081                                 return NULL;
3082                         }
3083                 }
3084                 (void) strncpy(fin->fin_group, fr->fr_group, FR_GROUPLEN);
3085                 fin->fin_icode = fr->fr_icode;
3086         }
3087 
3088         fin->fin_rule = is->is_rulen;
3089         pass = is->is_pass;
3090         fr_updatestate(fin, is, ifq);
3091 
3092         RWLOCK_EXIT(&ifs->ifs_ipf_state);
3093         fin->fin_flx |= FI_STATE;
3094         if ((pass & FR_LOGFIRST) != 0)
3095                 pass &= ~(FR_LOGFIRST|FR_LOG);
3096         *passp = pass;
3097         return fr;
3098 }
3099 
3100 
3101 /* ------------------------------------------------------------------------ */
3102 /* Function:    fr_fixoutisn                                                */
3103 /* Returns:     Nil                                                         */
3104 /* Parameters:  fin(I)   - pointer to packet information                    */
3105 /*              is(I)  - pointer to master state structure                  */
3106 /*                                                                          */
3107 /* Called only for outbound packets, adjusts the sequence number and the    */
3108 /* TCP checksum to match that change.                                       */
3109 /* ------------------------------------------------------------------------ */
3110 static void fr_fixoutisn(fin, is)
3111 fr_info_t *fin;
3112 ipstate_t *is;
3113 {
3114         tcphdr_t *tcp;
3115         int rev;
3116         u_32_t seq;
3117 
3118         tcp = fin->fin_dp;
3119         rev = fin->fin_rev;
3120         if ((is->is_flags & IS_ISNSYN) != 0) {
3121                 if (rev == 0) {
3122                         seq = ntohl(tcp->th_seq);
3123                         seq += is->is_isninc[0];
3124                         tcp->th_seq = htonl(seq);
3125                         fix_outcksum(&tcp->th_sum, is->is_sumd[0]);
3126                 }
3127         }
3128         if ((is->is_flags & IS_ISNACK) != 0) {
3129                 if (rev == 1) {
3130                         seq = ntohl(tcp->th_seq);
3131                         seq += is->is_isninc[1];
3132                         tcp->th_seq = htonl(seq);
3133                         fix_outcksum(&tcp->th_sum, is->is_sumd[1]);
3134                 }
3135         }
3136 }
3137 
3138 
3139 /* ------------------------------------------------------------------------ */
3140 /* Function:    fr_fixinisn                                                 */
3141 /* Returns:     Nil                                                         */
3142 /* Parameters:  fin(I)   - pointer to packet information                    */
3143 /*              is(I)  - pointer to master state structure                  */
3144 /*                                                                          */
3145 /* Called only for inbound packets, adjusts the acknowledge number and the  */
3146 /* TCP checksum to match that change.                                       */
3147 /* ------------------------------------------------------------------------ */
3148 static void fr_fixinisn(fin, is)
3149 fr_info_t *fin;
3150 ipstate_t *is;
3151 {
3152         tcphdr_t *tcp;
3153         int rev;
3154         u_32_t ack;
3155 
3156         tcp = fin->fin_dp;
3157         rev = fin->fin_rev;
3158         if ((is->is_flags & IS_ISNSYN) != 0) {
3159                 if (rev == 1) {
3160                         ack = ntohl(tcp->th_ack);
3161                         ack -= is->is_isninc[0];
3162                         tcp->th_ack = htonl(ack);
3163                         fix_incksum(&tcp->th_sum, is->is_sumd[0]);
3164                 }
3165         }
3166         if ((is->is_flags & IS_ISNACK) != 0) {
3167                 if (rev == 0) {
3168                         ack = ntohl(tcp->th_ack);
3169                         ack -= is->is_isninc[1];
3170                         tcp->th_ack = htonl(ack);
3171                         fix_incksum(&tcp->th_sum, is->is_sumd[1]);
3172                 }
3173         }
3174 }
3175 
3176 
3177 /* ------------------------------------------------------------------------ */
3178 /* Function:    fr_statesync                                                */
3179 /* Returns:     Nil                                                         */
3180 /* Parameters:  action(I) - type of synchronisation to do                   */
3181 /*              v(I)      - IP version being sync'd (v4 or v6)              */
3182 /*              ifp(I)    - interface identifier associated with action     */
3183 /*              name(I)   - name associated with ifp parameter              */
3184 /*                                                                          */
3185 /* Walk through all state entries and if an interface pointer match is      */
3186 /* found then look it up again, based on its name in case the pointer has   */
3187 /* changed since last time.                                                 */
3188 /*                                                                          */
3189 /* If ifp is passed in as being non-null then we are only doing updates for */
3190 /* existing, matching, uses of it.                                          */
3191 /* ------------------------------------------------------------------------ */
3192 void fr_statesync(action, v, ifp, name, ifs)
3193 int action, v;
3194 void *ifp;
3195 char *name;
3196 ipf_stack_t *ifs;
3197 {
3198         ipstate_t *is;
3199         int i;
3200 
3201         if (ifs->ifs_fr_running <= 0)
3202                 return;
3203 
3204         WRITE_ENTER(&ifs->ifs_ipf_state);
3205 
3206         if (ifs->ifs_fr_running <= 0) {
3207                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
3208                 return;
3209         }
3210 
3211         switch (action)
3212         {
3213         case IPFSYNC_RESYNC :
3214                 for (is = ifs->ifs_ips_list; is; is = is->is_next) {
3215                         if (v != 0 && is->is_v != v)
3216                                 continue;
3217                         /*
3218                          * Look up all the interface names in the state entry.
3219                          */
3220                         for (i = 0; i < 4; i++) {
3221                                 is->is_ifp[i] = fr_resolvenic(is->is_ifname[i],
3222                                                               is->is_v, ifs);
3223                         }
3224                 }
3225                 break;
3226         case IPFSYNC_NEWIFP :
3227                 for (is = ifs->ifs_ips_list; is; is = is->is_next) {
3228                         if (v != 0 && is->is_v != v)
3229                                 continue;
3230                         /*
3231                          * Look up all the interface names in the state entry.
3232                          */
3233                         for (i = 0; i < 4; i++) {
3234                                 if (!strncmp(is->is_ifname[i], name,
3235                                              sizeof(is->is_ifname[i])))
3236                                         is->is_ifp[i] = ifp;
3237                         }
3238                 }
3239                 break;
3240         case IPFSYNC_OLDIFP :
3241                 for (is = ifs->ifs_ips_list; is; is = is->is_next) {
3242                         if (v != 0 && is->is_v != v)
3243                                 continue;
3244                         /*
3245                          * Look up all the interface names in the state entry.
3246                          */
3247                         for (i = 0; i < 4; i++) {
3248                                 if (is->is_ifp[i] == ifp)
3249                                         is->is_ifp[i] = (void *)-1;
3250                         }
3251                 }
3252                 break;
3253         }
3254         RWLOCK_EXIT(&ifs->ifs_ipf_state);
3255 }
3256 
3257 
3258 #if SOLARIS2 >= 10
3259 /* ------------------------------------------------------------------------ */
3260 /* Function:    fr_stateifindexsync                                         */
3261 /* Returns:     void                                                        */
3262 /* Parameters:  ifp     - current network interface descriptor (ifindex)    */
3263 /*              newifp  - new interface descriptor (new ifindex)            */
3264 /*              ifs     - pointer to IPF stack                              */
3265 /*                                                                          */
3266 /* Write Locks: assumes ipf_mutex is locked                                 */
3267 /*                                                                          */
3268 /* Updates all interface indeces matching to ifp with new interface index   */
3269 /* value.                                                                   */
3270 /* ------------------------------------------------------------------------ */
3271 void fr_stateifindexsync(ifp, newifp, ifs)
3272 void *ifp;
3273 void *newifp;
3274 ipf_stack_t *ifs;
3275 {
3276         ipstate_t *is;
3277         int i;
3278 
3279         WRITE_ENTER(&ifs->ifs_ipf_state);
3280 
3281         for (is = ifs->ifs_ips_list; is != NULL; is = is->is_next) {
3282 
3283                 for (i = 0; i < 4; i++) {
3284                         if (is->is_ifp[i] == ifp)
3285                                 is->is_ifp[i] = newifp;
3286                 }
3287         }
3288 
3289         RWLOCK_EXIT(&ifs->ifs_ipf_state);
3290 }
3291 #endif
3292 
3293 /* ------------------------------------------------------------------------ */
3294 /* Function:    fr_delstate                                                 */
3295 /* Returns:     int - 0 = entry deleted, else ref count on entry            */
3296 /* Parameters:  is(I)  - pointer to state structure to delete               */
3297 /*              why(I) - if not 0, log reason why it was deleted            */
3298 /*              ifs    - ipf stack instance                                 */
3299 /* Write Locks: ipf_state/ipf_global                                        */
3300 /*                                                                          */
3301 /* Deletes a state entry from the enumerated list as well as the hash table */
3302 /* and timeout queue lists.  Make adjustments to hash table statistics and  */
3303 /* global counters as required.                                             */
3304 /* ------------------------------------------------------------------------ */
3305 int fr_delstate(is, why, ifs)
3306 ipstate_t *is;
3307 int why;
3308 ipf_stack_t *ifs;
3309 {
3310         int removed = 0;
3311 
3312         ASSERT(rw_write_held(&ifs->ifs_ipf_global.ipf_lk) == 0 ||
3313                 rw_write_held(&ifs->ifs_ipf_state.ipf_lk) == 0);
3314 
3315         /*
3316          * Start by removing the entry from the hash table of state entries
3317          * so it will not be "used" again.
3318          *
3319          * It will remain in the "list" of state entries until all references
3320          * have been accounted for.
3321          */
3322         if (is->is_phnext != NULL) {
3323                 removed = 1;
3324                 *is->is_phnext = is->is_hnext;
3325                 if (is->is_hnext != NULL)
3326                         is->is_hnext->is_phnext = is->is_phnext;
3327                 if (ifs->ifs_ips_table[is->is_hv] == NULL)
3328                         ifs->ifs_ips_stats.iss_inuse--;
3329                 ifs->ifs_ips_stats.iss_bucketlen[is->is_hv]--;
3330 
3331                 is->is_phnext = NULL;
3332                 is->is_hnext = NULL;
3333         }
3334 
3335         /*
3336          * Because ifs->ifs_ips_stats.iss_wild is a count of entries in the state
3337          * table that have wildcard flags set, only decerement it once
3338          * and do it here.
3339          */
3340         if (is->is_flags & (SI_WILDP|SI_WILDA)) {
3341                 if (!(is->is_flags & SI_CLONED)) {
3342                         ATOMIC_DECL(ifs->ifs_ips_stats.iss_wild);
3343                 }
3344                 is->is_flags &= ~(SI_WILDP|SI_WILDA);
3345         }
3346 
3347         /*
3348          * Next, remove it from the timeout queue it is in.
3349          */
3350         fr_deletequeueentry(&is->is_sti);
3351 
3352         is->is_me = NULL;
3353 
3354         /*
3355          * If it is still in use by something else, do not go any further,
3356          * but note that at this point it is now an orphan.
3357          */
3358         MUTEX_ENTER(&is->is_lock);
3359         if (is->is_ref > 1) {
3360                 is->is_ref--;
3361                 MUTEX_EXIT(&is->is_lock);
3362                 if (removed)
3363                         ifs->ifs_ips_stats.iss_orphans++;
3364                 return (is->is_ref);
3365         }
3366         MUTEX_EXIT(&is->is_lock);
3367 
3368         is->is_ref = 0;
3369 
3370         /*
3371          * If entry has already been removed from table,
3372          * it means we're simply cleaning up an orphan.
3373          */
3374         if (!removed)
3375                 ifs->ifs_ips_stats.iss_orphans--;
3376 
3377         if (is->is_tqehead[0] != NULL)
3378                 (void) fr_deletetimeoutqueue(is->is_tqehead[0]);
3379 
3380         if (is->is_tqehead[1] != NULL)
3381                 (void) fr_deletetimeoutqueue(is->is_tqehead[1]);
3382 
3383 #ifdef  IPFILTER_SYNC
3384         if (is->is_sync)
3385                 ipfsync_del(is->is_sync);
3386 #endif
3387 #ifdef  IPFILTER_SCAN
3388         (void) ipsc_detachis(is);
3389 #endif
3390 
3391         /*
3392          * Now remove it from master list of state table entries.
3393          */
3394         if (is->is_pnext != NULL) {
3395                 *is->is_pnext = is->is_next;
3396                 if (is->is_next != NULL) {
3397                         is->is_next->is_pnext = is->is_pnext;
3398                         is->is_next = NULL;
3399                 }
3400                 is->is_pnext = NULL;
3401         }
3402  
3403         if (ifs->ifs_ipstate_logging != 0 && why != 0)
3404                 ipstate_log(is, why, ifs);
3405 #if 0
3406         /*
3407          * For now, ipf_log_cfwlog() copes with all "why" values.
3408          * strictly speaking, though, they all map to one event, which for
3409          * now is not supported.
3410          */
3411         if (why != 0 && IFS_CFWLOG(ifs))
3412                 ipf_log_cfwlog(is, why, ifs);
3413 #endif
3414         if (is->is_rule != NULL) {
3415                 is->is_rule->fr_statecnt--;
3416                 (void)fr_derefrule(&is->is_rule, ifs);
3417         }
3418 
3419         MUTEX_DESTROY(&is->is_lock);
3420         KFREE(is);
3421         ifs->ifs_ips_num--;
3422 
3423         return (0);
3424 }
3425 
3426 
3427 /* ------------------------------------------------------------------------ */
3428 /* Function:    fr_timeoutstate                                             */
3429 /* Returns:     Nil                                                         */
3430 /* Parameters:  ifs - ipf stack instance                                    */
3431 /*                                                                          */
3432 /* Slowly expire held state for thingslike UDP and ICMP.  The algorithm     */
3433 /* used here is to keep the queue sorted with the oldest things at the top  */
3434 /* and the youngest at the bottom.  So if the top one doesn't need to be    */
3435 /* expired then neither will any under it.                                  */
3436 /* ------------------------------------------------------------------------ */
3437 void fr_timeoutstate(ifs)
3438 ipf_stack_t *ifs;
3439 {
3440         ipftq_t *ifq, *ifqnext;
3441         ipftqent_t *tqe, *tqn;
3442         ipstate_t *is;
3443         SPL_INT(s);
3444 
3445         SPL_NET(s);
3446         WRITE_ENTER(&ifs->ifs_ipf_state);
3447         for (ifq = ifs->ifs_ips_tqtqb; ifq != NULL; ifq = ifq->ifq_next)
3448                 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3449                         if (tqe->tqe_die > ifs->ifs_fr_ticks)
3450                                 break;
3451                         tqn = tqe->tqe_next;
3452                         is = tqe->tqe_parent;
3453                         (void) fr_delstate(is, ISL_EXPIRE, ifs);
3454                 }
3455 
3456         for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifq->ifq_next) {
3457                 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3458                         if (tqe->tqe_die > ifs->ifs_fr_ticks)
3459                                 break;
3460                         tqn = tqe->tqe_next;
3461                         is = tqe->tqe_parent;
3462                         (void) fr_delstate(is, ISL_EXPIRE, ifs);
3463                 }
3464         }
3465 
3466         for (ifq = ifs->ifs_ips_utqe; ifq != NULL; ifq = ifqnext) {
3467                 ifqnext = ifq->ifq_next;
3468 
3469                 if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
3470                     (ifq->ifq_ref == 0)) {
3471                         fr_freetimeoutqueue(ifq, ifs);
3472                 }
3473         }
3474 
3475         if (ifs->ifs_fr_state_doflush) {
3476                 (void) fr_state_flush(FLUSH_TABLE_EXTRA, 0, ifs);
3477                 ifs->ifs_fr_state_doflush = 0;
3478         }
3479         RWLOCK_EXIT(&ifs->ifs_ipf_state);
3480         SPL_X(s);
3481 }
3482 
3483 
3484 /* ---------------------------------------------------------------------- */
3485 /* Function:    fr_state_flush                                            */
3486 /* Returns:     int - 0 == success, -1 == failure                         */
3487 /* Parameters:  flush_option - how to flush the active State table        */
3488 /*              proto    - IP version to flush (4, 6, or both)            */
3489 /*              ifs      - ipf stack instance                             */
3490 /* Write Locks: ipf_state                                                 */
3491 /*                                                                        */
3492 /* Flush state tables.  Three possible flush options currently defined:   */
3493 /*                                                                        */
3494 /* FLUSH_TABLE_ALL      : Flush all state table entries                   */
3495 /*                                                                        */
3496 /* FLUSH_TABLE_CLOSING  : Flush entries with TCP connections which        */
3497 /*                        have started to close on both ends using        */
3498 /*                        ipf_flushclosing().                             */
3499 /*                                                                        */
3500 /* FLUSH_TABLE_EXTRA    : First, flush entries which are "almost" closed. */
3501 /*                        Then, if needed, flush entries with TCP         */
3502 /*                        connections which have been idle for a long     */
3503 /*                        time with ipf_extraflush().                     */
3504 /* ---------------------------------------------------------------------- */
3505 static int fr_state_flush(flush_option, proto, ifs)
3506 int flush_option, proto;
3507 ipf_stack_t *ifs;
3508 {
3509         ipstate_t *is, *isn;
3510         int removed;
3511         SPL_INT(s);
3512 
3513         removed = 0;
3514 
3515         SPL_NET(s);
3516         switch (flush_option)
3517         {
3518         case FLUSH_TABLE_ALL:
3519                 isn = ifs->ifs_ips_list;
3520                 while ((is = isn) != NULL) {
3521                         isn = is->is_next;
3522                         if ((proto != 0) && (is->is_v != proto))
3523                                 continue;
3524                         if (fr_delstate(is, ISL_FLUSH, ifs) == 0)
3525                                 removed++;
3526                 }
3527                 break;
3528 
3529         case FLUSH_TABLE_CLOSING:
3530                 removed = ipf_flushclosing(STATE_FLUSH,
3531                                            IPF_TCPS_CLOSE_WAIT,
3532                                            ifs->ifs_ips_tqtqb,
3533                                            ifs->ifs_ips_utqe,
3534                                            ifs);
3535                 break;
3536 
3537         case FLUSH_TABLE_EXTRA:
3538                 removed = ipf_flushclosing(STATE_FLUSH,
3539                                            IPF_TCPS_FIN_WAIT_2,
3540                                            ifs->ifs_ips_tqtqb,
3541                                            ifs->ifs_ips_utqe,
3542                                            ifs);
3543 
3544                 /*
3545                  * Be sure we haven't done this in the last 10 seconds.
3546                  */
3547                 if (ifs->ifs_fr_ticks - ifs->ifs_ips_last_force_flush <
3548                     IPF_TTLVAL(10))
3549                         break;
3550                 ifs->ifs_ips_last_force_flush = ifs->ifs_fr_ticks;
3551                 removed += ipf_extraflush(STATE_FLUSH,
3552                                           &ifs->ifs_ips_tqtqb[IPF_TCPS_ESTABLISHED],
3553                                           ifs->ifs_ips_utqe,
3554                                           ifs);
3555                 break;
3556 
3557         default: /* Flush Nothing */
3558                 break;
3559         }
3560 
3561         SPL_X(s);
3562         return (removed);
3563 }
3564 
3565 
3566 /* ------------------------------------------------------------------------ */
3567 /* Function:    fr_tcp_age                                                  */
3568 /* Returns:     int - 1 == state transition made, 0 == no change (rejected) */
3569 /* Parameters:  tq(I)    - pointer to timeout queue information             */
3570 /*              fin(I)   - pointer to packet information                    */
3571 /*              tqtab(I) - TCP timeout queue table this is in               */
3572 /*              flags(I) - flags from state/NAT entry                       */
3573 /*                                                                          */
3574 /* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:          */
3575 /*                                                                          */
3576 /* - (try to) base state transitions on real evidence only,                 */
3577 /*   i.e. packets that are sent and have been received by ipfilter;         */
3578 /*   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.       */
3579 /*                                                                          */
3580 /* - deal with half-closed connections correctly;                           */
3581 /*                                                                          */
3582 /* - store the state of the source in state[0] such that ipfstat            */
3583 /*   displays the state as source/dest instead of dest/source; the calls    */
3584 /*   to fr_tcp_age have been changed accordingly.                           */
3585 /*                                                                          */
3586 /* Internal Parameters:                                                     */
3587 /*                                                                          */
3588 /*    state[0] = state of source (host that initiated connection)           */
3589 /*    state[1] = state of dest   (host that accepted the connection)        */
3590 /*                                                                          */
3591 /*    dir == 0 : a packet from source to dest                               */
3592 /*    dir == 1 : a packet from dest to source                               */
3593 /*                                                                          */
3594 /* Locking: it is assumed that the parent of the tqe structure is locked.   */
3595 /* ------------------------------------------------------------------------ */
3596 int fr_tcp_age(tqe, fin, tqtab, flags)
3597 ipftqent_t *tqe;
3598 fr_info_t *fin;
3599 ipftq_t *tqtab;
3600 int flags;
3601 {
3602         int dlen, ostate, nstate, rval, dir;
3603         u_char tcpflags;
3604         tcphdr_t *tcp;
3605         ipf_stack_t *ifs = fin->fin_ifs;
3606 
3607         tcp = fin->fin_dp;
3608 
3609         rval = 0;
3610         dir = fin->fin_rev;
3611         tcpflags = tcp->th_flags;
3612         dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
3613 
3614         ostate = tqe->tqe_state[1 - dir];
3615         nstate = tqe->tqe_state[dir];
3616 
3617         DTRACE_PROBE4(
3618                 indata,
3619                 fr_info_t *, fin,
3620                 int, ostate,
3621                 int, nstate,
3622                 u_char, tcpflags
3623         );
3624 
3625         if (tcpflags & TH_RST) {
3626                 if (!(tcpflags & TH_PUSH) && !dlen)
3627                         nstate = IPF_TCPS_CLOSED;
3628                 else
3629                         nstate = IPF_TCPS_CLOSE_WAIT;
3630 
3631                 /*
3632                  * Once RST is received, we must advance peer's state to
3633                  * CLOSE_WAIT.
3634                  */
3635                 if (ostate <= IPF_TCPS_ESTABLISHED) {
3636                         tqe->tqe_state[1 - dir] = IPF_TCPS_CLOSE_WAIT;
3637                 }
3638                 rval = 1;
3639         } else {
3640 
3641                 switch (nstate)
3642                 {
3643                 case IPF_TCPS_LISTEN: /* 0 */
3644                         if ((tcpflags & TH_OPENING) == TH_OPENING) {
3645                                 /*
3646                                  * 'dir' received an S and sends SA in
3647                                  * response, CLOSED -> SYN_RECEIVED
3648                                  */
3649                                 nstate = IPF_TCPS_SYN_RECEIVED;
3650                                 rval = 1;
3651                         } else if ((tcpflags & TH_OPENING) == TH_SYN) {
3652                                 /* 'dir' sent S, CLOSED -> SYN_SENT */
3653                                 nstate = IPF_TCPS_SYN_SENT;
3654                                 rval = 1;
3655                         }
3656                         /*
3657                          * the next piece of code makes it possible to get
3658                          * already established connections into the state table
3659                          * after a restart or reload of the filter rules; this
3660                          * does not work when a strict 'flags S keep state' is
3661                          * used for tcp connections of course
3662                          */
3663                         if (((flags & IS_TCPFSM) == 0) &&
3664                             ((tcpflags & TH_ACKMASK) == TH_ACK)) {
3665                                 /*
3666                                  * we saw an A, guess 'dir' is in ESTABLISHED
3667                                  * mode
3668                                  */
3669                                 switch (ostate)
3670                                 {
3671                                 case IPF_TCPS_LISTEN :
3672                                 case IPF_TCPS_SYN_RECEIVED :
3673                                         nstate = IPF_TCPS_HALF_ESTAB;
3674                                         rval = 1;
3675                                         break;
3676                                 case IPF_TCPS_HALF_ESTAB :
3677                                 case IPF_TCPS_ESTABLISHED :
3678                                         nstate = IPF_TCPS_ESTABLISHED;
3679                                         rval = 1;
3680                                         break;
3681                                 default :
3682                                         break;
3683                                 }
3684                         }
3685                         /*
3686                          * TODO: besides regular ACK packets we can have other
3687                          * packets as well; it is yet to be determined how we
3688                          * should initialize the states in those cases
3689                          */
3690                         break;
3691 
3692                 case IPF_TCPS_SYN_SENT: /* 1 */
3693                         if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
3694                                 /*
3695                                  * A retransmitted SYN packet.  We do not reset
3696                                  * the timeout here to fr_tcptimeout because a
3697                                  * connection connect timeout does not renew
3698                                  * after every packet that is sent.  We need to
3699                                  * set rval so as to indicate the packet has
3700                                  * passed the check for its flags being valid
3701                                  * in the TCP FSM.  Setting rval to 2 has the
3702                                  * result of not resetting the timeout.
3703                                  */
3704                                 rval = 2;
3705                         } else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
3706                                    TH_ACK) {
3707                                 /*
3708                                  * we see an A from 'dir' which is in SYN_SENT
3709                                  * state: 'dir' sent an A in response to an SA
3710                                  * which it received, SYN_SENT -> ESTABLISHED
3711                                  */
3712                                 nstate = IPF_TCPS_ESTABLISHED;
3713                                 rval = 1;
3714                         } else if (tcpflags & TH_FIN) {
3715                                 /*
3716                                  * we see an F from 'dir' which is in SYN_SENT
3717                                  * state and wants to close its side of the
3718                                  * connection; SYN_SENT -> FIN_WAIT_1
3719                                  */
3720                                 nstate = IPF_TCPS_FIN_WAIT_1;
3721                                 rval = 1;
3722                         } else if ((tcpflags & TH_OPENING) == TH_OPENING) {
3723                                 /*
3724                                  * we see an SA from 'dir' which is already in
3725                                  * SYN_SENT state, this means we have a
3726                                  * simultaneous open; SYN_SENT -> SYN_RECEIVED
3727                                  */
3728                                 nstate = IPF_TCPS_SYN_RECEIVED;
3729                                 rval = 1;
3730                         }
3731                         break;
3732 
3733                 case IPF_TCPS_SYN_RECEIVED: /* 2 */
3734                         if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
3735                                 /*
3736                                  * we see an A from 'dir' which was in
3737                                  * SYN_RECEIVED state so it must now be in
3738                                  * established state, SYN_RECEIVED ->
3739                                  * ESTABLISHED
3740                                  */
3741                                 nstate = IPF_TCPS_ESTABLISHED;
3742                                 rval = 1;
3743                         } else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
3744                                    TH_OPENING) {
3745                                 /*
3746                                  * We see an SA from 'dir' which is already in
3747                                  * SYN_RECEIVED state.
3748                                  */
3749                                 rval = 2;
3750                         } else if (tcpflags & TH_FIN) {
3751                                 /*
3752                                  * we see an F from 'dir' which is in
3753                                  * SYN_RECEIVED state and wants to close its
3754                                  * side of the connection; SYN_RECEIVED ->
3755                                  * FIN_WAIT_1
3756                                  */
3757                                 nstate = IPF_TCPS_FIN_WAIT_1;
3758                                 rval = 1;
3759                         }
3760                         break;
3761 
3762                 case IPF_TCPS_HALF_ESTAB: /* 3 */
3763                         if (tcpflags & TH_FIN) {
3764                                 nstate = IPF_TCPS_FIN_WAIT_1;
3765                                 rval = 1;
3766                         } else if ((tcpflags & TH_ACKMASK) == TH_ACK) {
3767                                 /*
3768                                  * If we've picked up a connection in mid
3769                                  * flight, we could be looking at a follow on
3770                                  * packet from the same direction as the one
3771                                  * that created this state.  Recognise it but
3772                                  * do not advance the entire connection's
3773                                  * state.
3774                                  */
3775                                 switch (ostate)
3776                                 {
3777                                 case IPF_TCPS_LISTEN :
3778                                 case IPF_TCPS_SYN_SENT :
3779                                 case IPF_TCPS_SYN_RECEIVED :
3780                                         rval = 1;
3781                                         break;
3782                                 case IPF_TCPS_HALF_ESTAB :
3783                                 case IPF_TCPS_ESTABLISHED :
3784                                         nstate = IPF_TCPS_ESTABLISHED;
3785                                         rval = 1;
3786                                         break;
3787                                 default :
3788                                         break;
3789                                 }
3790                         }
3791                         break;
3792 
3793                 case IPF_TCPS_ESTABLISHED: /* 4 */
3794                         rval = 1;
3795                         if (tcpflags & TH_FIN) {
3796                                 /*
3797                                  * 'dir' closed its side of the connection;
3798                                  * this gives us a half-closed connection;
3799                                  * ESTABLISHED -> FIN_WAIT_1
3800                                  */
3801                                 if (ostate == IPF_TCPS_FIN_WAIT_1) {
3802                                         nstate = IPF_TCPS_CLOSING;
3803                                 } else {
3804                                         nstate = IPF_TCPS_FIN_WAIT_1;
3805                                 }
3806                         } else if (tcpflags & TH_ACK) {
3807                                 /*
3808                                  * an ACK, should we exclude other flags here?
3809                                  */
3810                                 if (ostate == IPF_TCPS_FIN_WAIT_1) {
3811                                         /*
3812                                          * We know the other side did an active
3813                                          * close, so we are ACKing the recvd
3814                                          * FIN packet (does the window matching
3815                                          * code guarantee this?) and go into
3816                                          * CLOSE_WAIT state; this gives us a
3817                                          * half-closed connection
3818                                          */
3819                                         nstate = IPF_TCPS_CLOSE_WAIT;
3820                                 } else if (ostate < IPF_TCPS_CLOSE_WAIT) {
3821                                         /*
3822                                          * still a fully established
3823                                          * connection reset timeout
3824                                          */
3825                                         nstate = IPF_TCPS_ESTABLISHED;
3826                                 }
3827                         }
3828                         break;
3829 
3830                 case IPF_TCPS_CLOSE_WAIT: /* 5 */
3831                         rval = 1;
3832                         if (tcpflags & TH_FIN) {
3833                                 /*
3834                                  * application closed and 'dir' sent a FIN,
3835                                  * we're now going into LAST_ACK state
3836                                  */
3837                                 nstate = IPF_TCPS_LAST_ACK;
3838                         } else {
3839                                 /*
3840                                  * we remain in CLOSE_WAIT because the other
3841                                  * side has closed already and we did not
3842                                  * close our side yet; reset timeout
3843                                  */
3844                                 nstate = IPF_TCPS_CLOSE_WAIT;
3845                         }
3846                         break;
3847 
3848                 case IPF_TCPS_FIN_WAIT_1: /* 6 */
3849                         rval = 1;
3850                         if ((tcpflags & TH_ACK) &&
3851                             ostate > IPF_TCPS_CLOSE_WAIT) {
3852                                 /*
3853                                  * if the other side is not active anymore
3854                                  * it has sent us a FIN packet that we are
3855                                  * ack'ing now with an ACK; this means both
3856                                  * sides have now closed the connection and
3857                                  * we go into LAST_ACK
3858                                  */
3859                                 /*
3860                                  * XXX: how do we know we really are ACKing
3861                                  * the FIN packet here? does the window code
3862                                  * guarantee that?
3863                                  */
3864                                 nstate = IPF_TCPS_LAST_ACK;
3865                         } else {
3866                                 /*
3867                                  * we closed our side of the connection
3868                                  * already but the other side is still active
3869                                  * (ESTABLISHED/CLOSE_WAIT); continue with
3870                                  * this half-closed connection
3871                                  */
3872                                 nstate = IPF_TCPS_FIN_WAIT_1;
3873                         }
3874                         break;
3875 
3876                 case IPF_TCPS_CLOSING: /* 7 */
3877                         if ((tcpflags & (TH_FIN|TH_ACK)) == TH_ACK) {
3878                                 nstate = IPF_TCPS_TIME_WAIT;
3879                         }
3880                         rval = 1;
3881                         break;
3882 
3883                 case IPF_TCPS_LAST_ACK: /* 8 */
3884                         /*
3885                          * We want to reset timer here to keep state in table.
3886                          * If we would allow the state to time out here, while
3887                          * there would still be packets being retransmitted, we
3888                          * would cut off line between the two peers preventing
3889                          * them to close connection properly. 
3890                          */
3891                         rval = 1;
3892                         break;
3893 
3894                 case IPF_TCPS_FIN_WAIT_2: /* 9 */
3895                         /* NOT USED */
3896                         break;
3897 
3898                 case IPF_TCPS_TIME_WAIT: /* 10 */
3899                         /* we're in 2MSL timeout now */
3900                         if (ostate == IPF_TCPS_LAST_ACK) {
3901                                 nstate = IPF_TCPS_CLOSED;
3902                                 rval = 1;
3903                         } else {
3904                                 rval = 2;
3905                         }
3906                         break;
3907 
3908                 case IPF_TCPS_CLOSED: /* 11 */
3909                         rval = 2;
3910                         break;
3911 
3912                 default :
3913 #if defined(_KERNEL)
3914                         ASSERT(nstate >= IPF_TCPS_LISTEN &&
3915                             nstate <= IPF_TCPS_CLOSED);
3916 #else
3917                         abort();
3918 #endif
3919                         break;
3920                 }
3921         }
3922 
3923         /*
3924          * If rval == 2 then do not update the queue position, but treat the
3925          * packet as being ok.
3926          */
3927         if (rval == 2) {
3928                 DTRACE_PROBE1(state_keeping_timer, int, nstate);
3929                 rval = 1;
3930         }
3931         else if (rval == 1) {
3932                 tqe->tqe_state[dir] = nstate;
3933                 /*
3934                  * The nstate can either advance to a new state, or remain
3935                  * unchanged, resetting the timer by moving to the bottom of
3936                  * the queue.
3937                  */
3938                 DTRACE_PROBE1(state_done, int, nstate);
3939 
3940                 if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
3941                         fr_movequeue(tqe, tqe->tqe_ifq, tqtab + nstate, ifs);
3942         }
3943 
3944         return rval;
3945 }
3946 
3947 /* ------------------------------------------------------------------------ */
3948 /* Function:    ipstate_log                                                 */
3949 /* Returns:     Nil                                                         */
3950 /* Parameters:  is(I)   - pointer to state structure                        */
3951 /*              type(I) - type of log entry to create                       */
3952 /*                                                                          */
3953 /* Creates a state table log entry using the state structure and type info. */
3954 /* passed in.  Log packet/byte counts, source/destination address and other */
3955 /* protocol specific information.                                           */
3956 /* ------------------------------------------------------------------------ */
3957 void ipstate_log(is, type, ifs)
3958 struct ipstate *is;
3959 u_int type;
3960 ipf_stack_t *ifs;
3961 {
3962 #ifdef  IPFILTER_LOG
3963         struct  ipslog  ipsl;
3964         size_t sizes[1];
3965         void *items[1];
3966         int types[1];
3967 
3968         /*
3969          * Copy information out of the ipstate_t structure and into the
3970          * structure used for logging.
3971          */
3972         ipsl.isl_type = type;
3973         ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
3974         ipsl.isl_bytes[0] = is->is_bytes[0];
3975         ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
3976         ipsl.isl_bytes[1] = is->is_bytes[1];
3977         ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
3978         ipsl.isl_bytes[2] = is->is_bytes[2];
3979         ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
3980         ipsl.isl_bytes[3] = is->is_bytes[3];
3981         ipsl.isl_src = is->is_src;
3982         ipsl.isl_dst = is->is_dst;
3983         ipsl.isl_p = is->is_p;
3984         ipsl.isl_v = is->is_v;
3985         ipsl.isl_flags = is->is_flags;
3986         ipsl.isl_tag = is->is_tag;
3987         ipsl.isl_rulen = is->is_rulen;
3988         (void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
3989 
3990         if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
3991                 ipsl.isl_sport = is->is_sport;
3992                 ipsl.isl_dport = is->is_dport;
3993                 if (ipsl.isl_p == IPPROTO_TCP) {
3994                         ipsl.isl_state[0] = is->is_state[0];
3995                         ipsl.isl_state[1] = is->is_state[1];
3996                 }
3997         } else if (ipsl.isl_p == IPPROTO_ICMP) {
3998                 ipsl.isl_itype = is->is_icmp.ici_type;
3999         } else if (ipsl.isl_p == IPPROTO_ICMPV6) {
4000                 ipsl.isl_itype = is->is_icmp.ici_type;
4001         } else {
4002                 ipsl.isl_ps.isl_filler[0] = 0;
4003                 ipsl.isl_ps.isl_filler[1] = 0;
4004         }
4005 
4006         items[0] = &ipsl;
4007         sizes[0] = sizeof(ipsl);
4008         types[0] = 0;
4009 
4010         if (ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1, ifs)) {
4011                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_logged);
4012         } else {
4013                 ATOMIC_INCL(ifs->ifs_ips_stats.iss_logfail);
4014         }
4015 #endif
4016 }
4017 
4018 
4019 #ifdef  USE_INET6
4020 /* ------------------------------------------------------------------------ */
4021 /* Function:    fr_checkicmp6matchingstate                                  */
4022 /* Returns:     ipstate_t* - NULL == no match found,                        */
4023 /*                           else  pointer to matching state entry          */
4024 /* Parameters:  fin(I) - pointer to packet information                      */
4025 /* Locks:       NULL == no locks, else Read Lock on ipf_state               */
4026 /*                                                                          */
4027 /* If we've got an ICMPv6 error message, using the information stored in    */
4028 /* the ICMPv6 packet, look for a matching state table entry.                */
4029 /* ------------------------------------------------------------------------ */
4030 static ipstate_t *fr_checkicmp6matchingstate(fin)
4031 fr_info_t *fin;
4032 {
4033         struct icmp6_hdr *ic6, *oic;
4034         int backward, i;
4035         ipstate_t *is, **isp;
4036         u_short sport, dport;
4037         i6addr_t dst, src;
4038         u_short savelen;
4039         icmpinfo_t *ic;
4040         fr_info_t ofin;
4041         tcphdr_t *tcp;
4042         ip6_t *oip6;
4043         u_char  pr;
4044         u_int hv;
4045         ipf_stack_t *ifs = fin->fin_ifs;
4046 
4047         /*
4048          * Does it at least have the return (basic) IP header ?
4049          * Is it an actual recognised ICMP error type?
4050          * Only a basic IP header (no options) should be with
4051          * an ICMP error header.
4052          */
4053         if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
4054             !(fin->fin_flx & FI_ICMPERR))
4055                 return NULL;
4056 
4057         ic6 = fin->fin_dp;
4058 
4059         oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
4060         if (fin->fin_plen < sizeof(*oip6))
4061                 return NULL;
4062 
4063         bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
4064         ofin.fin_v = 6;
4065         ofin.fin_ifp = fin->fin_ifp;
4066         ofin.fin_out = !fin->fin_out;
4067         ofin.fin_m = NULL;      /* if dereferenced, panic XXX */
4068         ofin.fin_mp = NULL;     /* if dereferenced, panic XXX */
4069 
4070         /*
4071          * We make a fin entry to be able to feed it to
4072          * matchsrcdst. Note that not all fields are necessary
4073          * but this is the cleanest way. Note further we fill
4074          * in fin_mp such that if someone uses it we'll get
4075          * a kernel panic. fr_matchsrcdst does not use this.
4076          *
4077          * watch out here, as ip is in host order and oip6 in network
4078          * order. Any change we make must be undone afterwards.
4079          */
4080         savelen = oip6->ip6_plen;
4081         oip6->ip6_plen = fin->fin_dlen - ICMPERR_ICMPHLEN;
4082         ofin.fin_flx = FI_NOCKSUM;
4083         ofin.fin_ip = (ip_t *)oip6;
4084         ofin.fin_plen = oip6->ip6_plen;
4085         (void) fr_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
4086         ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
4087         oip6->ip6_plen = savelen;
4088 
4089         if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
4090                 oic = (struct icmp6_hdr *)(oip6 + 1);
4091                 /*
4092                  * an ICMP error can only be generated as a result of an
4093                  * ICMP query, not as the response on an ICMP error
4094                  *
4095                  * XXX theoretically ICMP_ECHOREP and the other reply's are
4096                  * ICMP query's as well, but adding them here seems strange XXX
4097                  */
4098                  if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
4099                         return NULL;
4100 
4101                 /*
4102                  * perform a lookup of the ICMP packet in the state table
4103                  */
4104                 hv = (pr = oip6->ip6_nxt);
4105                 src.in6 = oip6->ip6_src;
4106                 hv += src.in4.s_addr;
4107                 dst.in6 = oip6->ip6_dst;
4108                 hv += dst.in4.s_addr;
4109                 hv += oic->icmp6_id;
4110                 hv += oic->icmp6_seq;
4111                 hv = DOUBLE_HASH(hv, ifs);
4112 
4113                 READ_ENTER(&ifs->ifs_ipf_state);
4114                 for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
4115                         ic = &is->is_icmp;
4116                         isp = &is->is_hnext;
4117                         if ((is->is_p == pr) &&
4118                             !(is->is_pass & FR_NOICMPERR) &&
4119                             (oic->icmp6_id == ic->ici_id) &&
4120                             (oic->icmp6_seq == ic->ici_seq) &&
4121                             (is = fr_matchsrcdst(&ofin, is, &src,
4122                                                  &dst, NULL, FI_ICMPCMP))) {
4123                                 /*
4124                                  * in the state table ICMP query's are stored
4125                                  * with the type of the corresponding ICMP
4126                                  * response. Correct here
4127                                  */
4128                                 if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
4129                                      (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
4130                                      (ic->ici_type - 1 == oic->icmp6_type )) {
4131                                         ifs->ifs_ips_stats.iss_hits++;
4132                                         backward = IP6_NEQ(&is->is_dst, &src);
4133                                         fin->fin_rev = !backward;
4134                                         i = (backward << 1) + fin->fin_out;
4135                                         is->is_icmppkts[i]++;
4136                                         return is;
4137                                 }
4138                         }
4139                 }
4140                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
4141                 return NULL;
4142         }
4143 
4144         hv = (pr = oip6->ip6_nxt);
4145         src.in6 = oip6->ip6_src;
4146         hv += src.i6[0];
4147         hv += src.i6[1];
4148         hv += src.i6[2];
4149         hv += src.i6[3];
4150         dst.in6 = oip6->ip6_dst;
4151         hv += dst.i6[0];
4152         hv += dst.i6[1];
4153         hv += dst.i6[2];
4154         hv += dst.i6[3];
4155 
4156         if ((oip6->ip6_nxt == IPPROTO_TCP) || (oip6->ip6_nxt == IPPROTO_UDP)) {
4157                 tcp = (tcphdr_t *)(oip6 + 1);
4158                 dport = tcp->th_dport;
4159                 sport = tcp->th_sport;
4160                 hv += dport;
4161                 hv += sport;
4162         } else
4163                 tcp = NULL;
4164         hv = DOUBLE_HASH(hv, ifs);
4165 
4166         READ_ENTER(&ifs->ifs_ipf_state);
4167         for (isp = &ifs->ifs_ips_table[hv]; ((is = *isp) != NULL); ) {
4168                 isp = &is->is_hnext;
4169                 /*
4170                  * Only allow this icmp though if the
4171                  * encapsulated packet was allowed through the
4172                  * other way around. Note that the minimal amount
4173                  * of info present does not allow for checking against
4174                  * tcp internals such as seq and ack numbers.
4175                  */
4176                 if ((is->is_p != pr) || (is->is_v != 6) ||
4177                     (is->is_pass & FR_NOICMPERR))
4178                         continue;
4179                 is = fr_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
4180                 if (is != NULL) {
4181                         ifs->ifs_ips_stats.iss_hits++;
4182                         backward = IP6_NEQ(&is->is_dst, &src);
4183                         fin->fin_rev = !backward;
4184                         i = (backward << 1) + fin->fin_out;
4185                         is->is_icmppkts[i]++;
4186                         /*
4187                          * we deliberately do not touch the timeouts
4188                          * for the accompanying state table entry.
4189                          * It remains to be seen if that is correct. XXX
4190                          */
4191                         return is;
4192                 }
4193         }
4194         RWLOCK_EXIT(&ifs->ifs_ipf_state);
4195         return NULL;
4196 }
4197 #endif
4198 
4199 
4200 /* ------------------------------------------------------------------------ */
4201 /* Function:    fr_sttab_init                                               */
4202 /* Returns:     Nil                                                         */
4203 /* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
4204 /*                                                                          */
4205 /* Initialise the array of timeout queues for TCP.                          */
4206 /* ------------------------------------------------------------------------ */
4207 void fr_sttab_init(tqp, ifs)
4208 ipftq_t *tqp;
4209 ipf_stack_t *ifs;
4210 {
4211         int i;
4212 
4213         for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
4214                 tqp[i].ifq_ttl = 0;
4215                 tqp[i].ifq_ref = 1;
4216                 tqp[i].ifq_head = NULL;
4217                 tqp[i].ifq_tail = &tqp[i].ifq_head;
4218                 tqp[i].ifq_next = tqp + i + 1;
4219                 MUTEX_INIT(&tqp[i].ifq_lock, "ipftq tcp tab");
4220         }
4221         tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
4222         tqp[IPF_TCPS_CLOSED].ifq_ttl = ifs->ifs_fr_tcpclosed;
4223         tqp[IPF_TCPS_LISTEN].ifq_ttl = ifs->ifs_fr_tcptimeout;
4224         tqp[IPF_TCPS_SYN_SENT].ifq_ttl = ifs->ifs_fr_tcptimeout;
4225         tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = ifs->ifs_fr_tcptimeout;
4226         tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = ifs->ifs_fr_tcpidletimeout;
4227         tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = ifs->ifs_fr_tcphalfclosed;
4228         tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = ifs->ifs_fr_tcphalfclosed;
4229         tqp[IPF_TCPS_CLOSING].ifq_ttl = ifs->ifs_fr_tcptimeout;
4230         tqp[IPF_TCPS_LAST_ACK].ifq_ttl = ifs->ifs_fr_tcplastack;
4231         tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = ifs->ifs_fr_tcpclosewait;
4232         tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = ifs->ifs_fr_tcptimeout;
4233         tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = ifs->ifs_fr_tcptimeout;
4234 }
4235 
4236 
4237 /* ------------------------------------------------------------------------ */
4238 /* Function:    fr_sttab_destroy                                            */
4239 /* Returns:     Nil                                                         */
4240 /* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
4241 /*                                                                          */
4242 /* Do whatever is necessary to "destroy" each of the entries in the array   */
4243 /* of timeout queues for TCP.                                               */
4244 /* ------------------------------------------------------------------------ */
4245 void fr_sttab_destroy(tqp)
4246 ipftq_t *tqp;
4247 {
4248         int i;
4249 
4250         for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
4251                 MUTEX_DESTROY(&tqp[i].ifq_lock);
4252 }
4253 
4254 
4255 /* ------------------------------------------------------------------------ */
4256 /* Function:    fr_statederef                                               */
4257 /* Returns:     Nil                                                         */
4258 /* Parameters:  isp(I) - pointer to pointer to state table entry            */
4259 /*              ifs - ipf stack instance                                    */
4260 /*                                                                          */
4261 /* Decrement the reference counter for this state table entry and free it   */
4262 /* if there are no more things using it.                                    */
4263 /*                                                                          */
4264 /* Internal parameters:                                                     */
4265 /*    state[0] = state of source (host that initiated connection)           */
4266 /*    state[1] = state of dest   (host that accepted the connection)        */
4267 /* ------------------------------------------------------------------------ */
4268 void fr_statederef(isp, ifs)
4269 ipstate_t **isp;
4270 ipf_stack_t *ifs;
4271 {
4272         ipstate_t *is;
4273 
4274         is = *isp;
4275         *isp = NULL;
4276 
4277         MUTEX_ENTER(&is->is_lock);
4278         if (is->is_ref > 1) {
4279                 is->is_ref--;
4280                 MUTEX_EXIT(&is->is_lock);
4281 #ifndef _KERNEL
4282                 if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
4283                    (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
4284                         (void) fr_delstate(is, ISL_ORPHAN, ifs);
4285                 }
4286 #endif
4287                 return;
4288         }
4289         MUTEX_EXIT(&is->is_lock);
4290 
4291         WRITE_ENTER(&ifs->ifs_ipf_state);
4292         (void) fr_delstate(is, ISL_EXPIRE, ifs);
4293         RWLOCK_EXIT(&ifs->ifs_ipf_state);
4294 }
4295 
4296 
4297 /* ------------------------------------------------------------------------ */
4298 /* Function:    fr_setstatequeue                                            */
4299 /* Returns:     Nil                                                         */
4300 /* Parameters:  is(I) - pointer to state structure                          */
4301 /*              rev(I) - forward(0) or reverse(1) direction                 */
4302 /* Locks:       ipf_state (read or write)                                   */
4303 /*                                                                          */
4304 /* Put the state entry on its default queue entry, using rev as a helped in */
4305 /* determining which queue it should be placed on.                          */
4306 /* ------------------------------------------------------------------------ */
4307 void fr_setstatequeue(is, rev, ifs)
4308 ipstate_t *is;
4309 int rev;
4310 ipf_stack_t *ifs;
4311 {
4312         ipftq_t *oifq, *nifq;
4313 
4314 
4315         if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
4316                 nifq = is->is_tqehead[rev];
4317         else
4318                 nifq = NULL;
4319 
4320         if (nifq == NULL) {
4321                 switch (is->is_p)
4322                 {
4323 #ifdef USE_INET6
4324                 case IPPROTO_ICMPV6 :
4325                         if (rev == 1)
4326                                 nifq = &ifs->ifs_ips_icmpacktq;
4327                         else
4328                                 nifq = &ifs->ifs_ips_icmptq;
4329                         break;
4330 #endif
4331                 case IPPROTO_ICMP :
4332                         if (rev == 1)
4333                                 nifq = &ifs->ifs_ips_icmpacktq;
4334                         else
4335                                 nifq = &ifs->ifs_ips_icmptq;
4336                         break;
4337                 case IPPROTO_TCP :
4338                         nifq = ifs->ifs_ips_tqtqb + is->is_state[rev];
4339                         break;
4340 
4341                 case IPPROTO_UDP :
4342                         if (rev == 1)
4343                                 nifq = &ifs->ifs_ips_udpacktq;
4344                         else
4345                                 nifq = &ifs->ifs_ips_udptq;
4346                         break;
4347 
4348                 default :
4349                         nifq = &ifs->ifs_ips_iptq;
4350                         break;
4351                 }
4352         }
4353 
4354         oifq = is->is_sti.tqe_ifq;
4355         /*
4356          * If it's currently on a timeout queue, move it from one queue to
4357          * another, else put it on the end of the newly determined queue.
4358          */
4359         if (oifq != NULL)
4360                 fr_movequeue(&is->is_sti, oifq, nifq, ifs);
4361         else
4362                 fr_queueappend(&is->is_sti, nifq, is, ifs);
4363         return;
4364 }
4365 
4366 
4367 /* ------------------------------------------------------------------------ */
4368 /* Function:    fr_stateiter                                                */
4369 /* Returns:     int - 0 == success, else error                              */
4370 /* Parameters:  token(I) - pointer to ipftoken structure                    */
4371 /*              itp(I)   - pointer to ipfgeniter structure                  */
4372 /*                                                                          */
4373 /* This function handles the SIOCGENITER ioctl for the state tables and     */
4374 /* walks through the list of entries in the state table list (ips_list.)    */
4375 /* ------------------------------------------------------------------------ */
4376 static int fr_stateiter(token, itp, ifs)
4377 ipftoken_t *token;
4378 ipfgeniter_t *itp;
4379 ipf_stack_t *ifs;
4380 {
4381         ipstate_t *is, *next, zero;
4382         int error, count;
4383         char *dst;
4384 
4385         if (itp->igi_data == NULL)
4386                 return EFAULT;
4387 
4388         if (itp->igi_nitems == 0)
4389                 return EINVAL;
4390 
4391         if (itp->igi_type != IPFGENITER_STATE)
4392                 return EINVAL;
4393 
4394         error = 0;
4395 
4396         READ_ENTER(&ifs->ifs_ipf_state);
4397 
4398         /*
4399          * Get "previous" entry from the token and find the next entry.
4400          */
4401         is = token->ipt_data;
4402         if (is == NULL) {
4403                 next = ifs->ifs_ips_list;
4404         } else {
4405                 next = is->is_next;
4406         }
4407 
4408         dst = itp->igi_data;
4409         for (count = itp->igi_nitems; count > 0; count--) {
4410                 /*
4411                  * If we found an entry, add a reference to it and update the token.
4412                  * Otherwise, zero out data to be returned and NULL out token.
4413                  */
4414                 if (next != NULL) {
4415                         MUTEX_ENTER(&next->is_lock);
4416                         next->is_ref++;
4417                         MUTEX_EXIT(&next->is_lock);
4418                         token->ipt_data = next;
4419                 } else {
4420                         bzero(&zero, sizeof(zero));
4421                         next = &zero;
4422                         token->ipt_data = NULL;
4423                 }
4424 
4425                 /*
4426                  * Safe to release lock now the we have a reference.
4427                  */
4428                 RWLOCK_EXIT(&ifs->ifs_ipf_state);
4429 
4430                 /*
4431                  * Copy out data and clean up references and tokens.
4432                  */
4433                 error = COPYOUT(next, dst, sizeof(*next));
4434                 if (error != 0)
4435                         error = EFAULT;
4436                 if (token->ipt_data == NULL) {
4437                         ipf_freetoken(token, ifs);
4438                         break;
4439                 } else {
4440                         if (is != NULL)
4441                                 fr_statederef(&is, ifs);
4442                         if (next->is_next == NULL) {
4443                                 ipf_freetoken(token, ifs);
4444                                 break;
4445                         }
4446                 }
4447 
4448                 if ((count == 1) || (error != 0))
4449                         break;
4450 
4451                 READ_ENTER(&ifs->ifs_ipf_state);
4452                 dst += sizeof(*next);
4453                 is = next;
4454                 next = is->is_next;
4455         }
4456 
4457         return error;
4458 }