]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/contrib/ipfilter/netinet/ip_state.c
Merge ACPICA 20170728.
[FreeBSD/FreeBSD.git] / sys / contrib / ipfilter / netinet / ip_state.c
1 /*      $FreeBSD$ */
2
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * Copyright 2008 Sun Microsystems.
9  *
10  * $Id$
11  */
12 #if defined(KERNEL) || defined(_KERNEL)
13 # undef KERNEL
14 # undef _KERNEL
15 # define        KERNEL  1
16 # define        _KERNEL 1
17 #endif
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/file.h>
22 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
23     (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
24 #include "opt_inet6.h"
25 #endif
26 #if !defined(_KERNEL) && !defined(__KERNEL__)
27 # include <stdio.h>
28 # include <stdlib.h>
29 # include <string.h>
30 # define _KERNEL
31 # ifdef __OpenBSD__
32 struct file;
33 # endif
34 # include <sys/uio.h>
35 # undef _KERNEL
36 #endif
37 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
38 # include <sys/filio.h>
39 # include <sys/fcntl.h>
40 #else
41 # include <sys/ioctl.h>
42 #endif
43 #include <sys/time.h>
44 #if !defined(linux)
45 # include <sys/protosw.h>
46 #endif
47 #include <sys/socket.h>
48 #if defined(_KERNEL)
49 # include <sys/systm.h>
50 # if !defined(__SVR4) && !defined(__svr4__)
51 #  include <sys/mbuf.h>
52 # endif
53 #endif
54 #if defined(__SVR4) || defined(__svr4__)
55 # include <sys/filio.h>
56 # include <sys/byteorder.h>
57 # ifdef _KERNEL
58 #  include <sys/dditypes.h>
59 # endif
60 # include <sys/stream.h>
61 # include <sys/kmem.h>
62 #endif
63
64 #include <net/if.h>
65 #ifdef sun
66 # include <net/af.h>
67 #endif
68 #include <netinet/in.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/ip.h>
71 #include <netinet/tcp.h>
72 #if !defined(__hpux) && !defined(linux)
73 # include <netinet/tcp_fsm.h>
74 #endif
75 #include <netinet/udp.h>
76 #include <netinet/ip_icmp.h>
77 #if !defined(_KERNEL)
78 # include "ipf.h"
79 #endif
80 #include "netinet/ip_compat.h"
81 #include "netinet/ip_fil.h"
82 #include "netinet/ip_nat.h"
83 #include "netinet/ip_frag.h"
84 #include "netinet/ip_state.h"
85 #include "netinet/ip_proxy.h"
86 #include "netinet/ip_lookup.h"
87 #include "netinet/ip_dstlist.h"
88 #include "netinet/ip_sync.h"
89 #ifdef  USE_INET6
90 #include <netinet/icmp6.h>
91 #endif
92 #if FREEBSD_GE_REV(300000)
93 # include <sys/malloc.h>
94 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
95 #  include <sys/libkern.h>
96 #  include <sys/systm.h>
97 # endif
98 #endif
99 /* END OF INCLUDES */
100
101
102 #if !defined(lint)
103 static const char sccsid[] = "@(#)ip_state.c    1.8 6/5/96 (C) 1993-2000 Darren Reed";
104 static const char rcsid[] = "@(#)$Id$";
105 #endif
106
107
108 static ipftuneable_t ipf_state_tuneables[] = {
109         { { (void *)offsetof(ipf_state_softc_t, ipf_state_max) },
110                 "state_max",            1,      0x7fffffff,
111                 stsizeof(ipf_state_softc_t, ipf_state_max),
112                 0,                      NULL,   NULL },
113         { { (void *)offsetof(ipf_state_softc_t, ipf_state_size) },
114                 "state_size",           1,      0x7fffffff,
115                 stsizeof(ipf_state_softc_t, ipf_state_size),
116                 0,                      NULL,   ipf_state_rehash },
117         { { (void *)offsetof(ipf_state_softc_t, ipf_state_lock) },
118                 "state_lock",           0,      1,
119                 stsizeof(ipf_state_softc_t, ipf_state_lock),
120                 IPFT_RDONLY,            NULL,   NULL },
121         { { (void *)offsetof(ipf_state_softc_t, ipf_state_maxbucket) },
122                 "state_maxbucket",      1,      0x7fffffff,
123                 stsizeof(ipf_state_softc_t, ipf_state_maxbucket),
124                 0,                      NULL,   NULL },
125         { { (void *)offsetof(ipf_state_softc_t, ipf_state_logging) },
126                 "state_logging",0,      1,
127                 stsizeof(ipf_state_softc_t, ipf_state_logging),
128                 0,                      NULL,   NULL },
129         { { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_high) },
130                 "state_wm_high",2,      100,
131                 stsizeof(ipf_state_softc_t, ipf_state_wm_high),
132                 0,                      NULL,   NULL },
133         { { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_low) },
134                 "state_wm_low", 1,      99,
135                 stsizeof(ipf_state_softc_t, ipf_state_wm_low),
136                 0,                      NULL,   NULL },
137         { { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_freq) },
138                 "state_wm_freq",2,      999999,
139                 stsizeof(ipf_state_softc_t, ipf_state_wm_freq),
140                 0,                      NULL,   NULL },
141         { { NULL },
142                 NULL,                   0,      0,
143                 0,
144                 0,      NULL, NULL }
145 };
146
147 #define SINCL(x)        ATOMIC_INCL(softs->x)
148 #define SBUMP(x)        (softs->x)++
149 #define SBUMPD(x, y)    do { (softs->x.y)++; DT(y); } while (0)
150 #define SBUMPDX(x, y, z)do { (softs->x.y)++; DT(z); } while (0)
151
152 #ifdef  USE_INET6
153 static ipstate_t *ipf_checkicmp6matchingstate __P((fr_info_t *));
154 #endif
155 static int ipf_allowstateicmp __P((fr_info_t *, ipstate_t *, i6addr_t *));
156 static ipstate_t *ipf_matchsrcdst __P((fr_info_t *, ipstate_t *, i6addr_t *,
157                                       i6addr_t *, tcphdr_t *, u_32_t));
158 static ipstate_t *ipf_checkicmpmatchingstate __P((fr_info_t *));
159 static int ipf_state_flush_entry __P((ipf_main_softc_t *, void *));
160 static ips_stat_t *ipf_state_stats __P((ipf_main_softc_t *));
161 static int ipf_state_del __P((ipf_main_softc_t *, ipstate_t *, int));
162 static int ipf_state_remove __P((ipf_main_softc_t *, caddr_t));
163 static int ipf_state_match __P((ipstate_t *is1, ipstate_t *is2));
164 static int ipf_state_matchaddresses __P((ipstate_t *is1, ipstate_t *is2));
165 static int ipf_state_matchipv4addrs __P((ipstate_t *is1, ipstate_t *is2));
166 static int ipf_state_matchipv6addrs __P((ipstate_t *is1, ipstate_t *is2));
167 static int ipf_state_matchisps __P((ipstate_t *is1, ipstate_t *is2));
168 static int ipf_state_matchports __P((udpinfo_t *is1, udpinfo_t *is2));
169 static int ipf_state_matcharray __P((ipstate_t *, int *, u_long));
170 static void ipf_ipsmove __P((ipf_state_softc_t *, ipstate_t *, u_int));
171 static int ipf_state_tcp __P((ipf_main_softc_t *, ipf_state_softc_t *,
172                               fr_info_t *, tcphdr_t *, ipstate_t *));
173 static int ipf_tcpoptions __P((ipf_state_softc_t *, fr_info_t *,
174                                tcphdr_t *, tcpdata_t *));
175 static ipstate_t *ipf_state_clone __P((fr_info_t *, tcphdr_t *, ipstate_t *));
176 static void ipf_fixinisn __P((fr_info_t *, ipstate_t *));
177 static void ipf_fixoutisn __P((fr_info_t *, ipstate_t *));
178 static void ipf_checknewisn __P((fr_info_t *, ipstate_t *));
179 static int ipf_state_iter __P((ipf_main_softc_t *, ipftoken_t *,
180                                ipfgeniter_t *, ipfobj_t *));
181 static int ipf_state_gettable __P((ipf_main_softc_t *, ipf_state_softc_t *,
182                                    char *));
183 static  int ipf_state_tcpinwindow __P((struct fr_info *, struct tcpdata *,
184                                        struct tcpdata *, tcphdr_t *, int));
185
186 static int ipf_state_getent __P((ipf_main_softc_t *, ipf_state_softc_t *,
187                                  caddr_t));
188 static int ipf_state_putent __P((ipf_main_softc_t *, ipf_state_softc_t *,
189                                  caddr_t));
190
191 #define ONE_DAY         IPF_TTLVAL(1 * 86400)   /* 1 day */
192 #define FIVE_DAYS       (5 * ONE_DAY)
193 #define DOUBLE_HASH(x)  (((x) + softs->ipf_state_seed[(x) % \
194                          softs->ipf_state_size]) % softs->ipf_state_size)
195
196
197 /* ------------------------------------------------------------------------ */
198 /* Function:    ipf_state_main_load                                         */
199 /* Returns:     int - 0 == success, -1 == failure                           */
200 /* Parameters:  Nil                                                         */
201 /*                                                                          */
202 /* A null-op function that exists as a placeholder so that the flow in      */
203 /* other functions is obvious.                                              */
204 /* ------------------------------------------------------------------------ */
205 int
206 ipf_state_main_load()
207 {
208         return 0;
209 }
210
211
212 /* ------------------------------------------------------------------------ */
213 /* Function:    ipf_state_main_unload                                       */
214 /* Returns:     int - 0 == success, -1 == failure                           */
215 /* Parameters:  Nil                                                         */
216 /*                                                                          */
217 /* A null-op function that exists as a placeholder so that the flow in      */
218 /* other functions is obvious.                                              */
219 /* ------------------------------------------------------------------------ */
220 int
221 ipf_state_main_unload()
222 {
223         return 0;
224 }
225
226
227 /* ------------------------------------------------------------------------ */
228 /* Function:    ipf_state_soft_create                                       */
229 /* Returns:     void *   - NULL = failure, else pointer to soft context     */
230 /* Parameters:  softc(I) - pointer to soft context main structure           */
231 /*                                                                          */
232 /* Create a new state soft context structure and populate it with the list  */
233 /* of tunables and other default settings.                                  */
234 /* ------------------------------------------------------------------------ */
235 void *
236 ipf_state_soft_create(softc)
237         ipf_main_softc_t *softc;
238 {
239         ipf_state_softc_t *softs;
240
241         KMALLOC(softs, ipf_state_softc_t *);
242         if (softs == NULL)
243                 return NULL;
244
245         bzero((char *)softs, sizeof(*softs));
246
247         softs->ipf_state_tune = ipf_tune_array_copy(softs,
248                                                     sizeof(ipf_state_tuneables),
249                                                     ipf_state_tuneables);
250         if (softs->ipf_state_tune == NULL) {
251                 ipf_state_soft_destroy(softc, softs);
252                 return NULL;
253         }
254         if (ipf_tune_array_link(softc, softs->ipf_state_tune) == -1) {
255                 ipf_state_soft_destroy(softc, softs);
256                 return NULL;
257         }
258
259 #ifdef  IPFILTER_LOG
260         softs->ipf_state_logging = 1;
261 #else
262         softs->ipf_state_logging = 0;
263 #endif
264         softs->ipf_state_size = IPSTATE_SIZE,
265         softs->ipf_state_maxbucket = 0;
266         softs->ipf_state_wm_freq = IPF_TTLVAL(10);
267         softs->ipf_state_max = IPSTATE_MAX;
268         softs->ipf_state_wm_last = 0;
269         softs->ipf_state_wm_high = 99;
270         softs->ipf_state_wm_low = 90;
271         softs->ipf_state_inited = 0;
272         softs->ipf_state_lock = 0;
273         softs->ipf_state_doflush = 0;
274
275         return softs;
276 }
277
278
279 /* ------------------------------------------------------------------------ */
280 /* Function:    ipf_state_soft_destroy                                      */
281 /* Returns:     Nil                                                         */
282 /* Parameters:  softc(I) - pointer to soft context main structure           */
283 /*              arg(I)   - pointer to local context to use                  */
284 /*                                                                          */
285 /* Undo only what we did in soft create: unlink and free the tunables and   */
286 /* free the soft context structure itself.                                  */
287 /* ------------------------------------------------------------------------ */
288 void
289 ipf_state_soft_destroy(softc, arg)
290         ipf_main_softc_t *softc;
291         void *arg;
292 {
293         ipf_state_softc_t *softs = arg;
294
295         if (softs->ipf_state_tune != NULL) {
296                 ipf_tune_array_unlink(softc, softs->ipf_state_tune);
297                 KFREES(softs->ipf_state_tune, sizeof(ipf_state_tuneables));
298                 softs->ipf_state_tune = NULL;
299         }
300
301         KFREE(softs);
302 }
303
304
305 /* ------------------------------------------------------------------------ */
306 /* Function:    ipf_state_soft_init                                         */
307 /* Returns:     int      - 0 == success, -1 == failure                      */
308 /* Parameters:  softc(I) - pointer to soft context main structure           */
309 /*              arg(I)   - pointer to local context to use                  */
310 /*                                                                          */
311 /* Initialise the state soft context structure so it is ready for use.      */
312 /* This involves:                                                           */
313 /* - allocating a hash table and zero'ing it out                            */
314 /* - building a secondary table of seeds for double hashing to make it more */
315 /*   difficult to attempt to attack the hash table itself (for DoS)         */
316 /* - initialise all of the timeout queues, including a table for TCP, some  */
317 /*   pairs of query/response for UDP and other IP protocols (typically the  */
318 /*   reply queue has a shorter timeout than the query)                      */
319 /* ------------------------------------------------------------------------ */
320 int
321 ipf_state_soft_init(softc, arg)
322         ipf_main_softc_t *softc;
323         void *arg;
324 {
325         ipf_state_softc_t *softs = arg;
326         int i;
327
328         KMALLOCS(softs->ipf_state_table,
329                  ipstate_t **, softs->ipf_state_size * sizeof(ipstate_t *));
330         if (softs->ipf_state_table == NULL)
331                 return -1;
332
333         bzero((char *)softs->ipf_state_table,
334               softs->ipf_state_size * sizeof(ipstate_t *));
335
336         KMALLOCS(softs->ipf_state_seed, u_long *,
337                  softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
338         if (softs->ipf_state_seed == NULL)
339                 return -2;
340
341         for (i = 0; i < softs->ipf_state_size; i++) {
342                 /*
343                  * XXX - ipf_state_seed[X] should be a random number of sorts.
344                  */
345 #if  FREEBSD_GE_REV(400000)
346                 softs->ipf_state_seed[i] = arc4random();
347 #else
348                 softs->ipf_state_seed[i] = ((u_long)softs->ipf_state_seed + i) *
349                                     softs->ipf_state_size;
350                 softs->ipf_state_seed[i] ^= 0xa5a55a5a;
351                 softs->ipf_state_seed[i] *= (u_long)softs->ipf_state_seed;
352                 softs->ipf_state_seed[i] ^= 0x5a5aa5a5;
353                 softs->ipf_state_seed[i] *= softs->ipf_state_max;
354 #endif
355         }
356
357         KMALLOCS(softs->ipf_state_stats.iss_bucketlen, u_int *,
358                  softs->ipf_state_size * sizeof(u_int));
359         if (softs->ipf_state_stats.iss_bucketlen == NULL)
360                 return -3;
361
362         bzero((char *)softs->ipf_state_stats.iss_bucketlen,
363               softs->ipf_state_size * sizeof(u_int));
364
365         if (softs->ipf_state_maxbucket == 0) {
366                 for (i = softs->ipf_state_size; i > 0; i >>= 1)
367                         softs->ipf_state_maxbucket++;
368                 softs->ipf_state_maxbucket *= 2;
369         }
370
371         ipf_sttab_init(softc, softs->ipf_state_tcptq);
372         softs->ipf_state_stats.iss_tcptab = softs->ipf_state_tcptq;
373         softs->ipf_state_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
374                                                 &softs->ipf_state_udptq;
375
376         IPFTQ_INIT(&softs->ipf_state_udptq, softc->ipf_udptimeout,
377                    "ipftq udp tab");
378         softs->ipf_state_udptq.ifq_next = &softs->ipf_state_udpacktq;
379
380         IPFTQ_INIT(&softs->ipf_state_udpacktq, softc->ipf_udpacktimeout,
381                    "ipftq udpack tab");
382         softs->ipf_state_udpacktq.ifq_next = &softs->ipf_state_icmptq;
383
384         IPFTQ_INIT(&softs->ipf_state_icmptq, softc->ipf_icmptimeout,
385                    "ipftq icmp tab");
386         softs->ipf_state_icmptq.ifq_next = &softs->ipf_state_icmpacktq;
387
388         IPFTQ_INIT(&softs->ipf_state_icmpacktq, softc->ipf_icmpacktimeout,
389                   "ipftq icmpack tab");
390         softs->ipf_state_icmpacktq.ifq_next = &softs->ipf_state_iptq;
391
392         IPFTQ_INIT(&softs->ipf_state_iptq, softc->ipf_iptimeout,
393                    "ipftq iptimeout tab");
394         softs->ipf_state_iptq.ifq_next = &softs->ipf_state_pending;
395
396         IPFTQ_INIT(&softs->ipf_state_pending, IPF_HZ_DIVIDE, "ipftq pending");
397         softs->ipf_state_pending.ifq_next = &softs->ipf_state_deletetq;
398
399         IPFTQ_INIT(&softs->ipf_state_deletetq, 1, "ipftq delete");
400         softs->ipf_state_deletetq.ifq_next = NULL;
401
402         MUTEX_INIT(&softs->ipf_stinsert, "ipf state insert mutex");
403
404
405         softs->ipf_state_wm_last = softc->ipf_ticks;
406         softs->ipf_state_inited = 1;
407
408         return 0;
409 }
410
411
412 /* ------------------------------------------------------------------------ */
413 /* Function:    ipf_state_soft_fini                                         */
414 /* Returns:     int      - 0 = success, -1 = failure                        */
415 /* Parameters:  softc(I) - pointer to soft context main structure           */
416 /*              arg(I)   - pointer to local context to use                  */
417 /*                                                                          */
418 /* Release and destroy any resources acquired or initialised so that        */
419 /* IPFilter can be unloaded or re-initialised.                              */
420 /* ------------------------------------------------------------------------ */
421 int
422 ipf_state_soft_fini(softc, arg)
423         ipf_main_softc_t *softc;
424         void *arg;
425 {
426         ipf_state_softc_t *softs = arg;
427         ipftq_t *ifq, *ifqnext;
428         ipstate_t *is;
429
430         while ((is = softs->ipf_state_list) != NULL)
431                 ipf_state_del(softc, is, ISL_UNLOAD);
432
433         /*
434          * Proxy timeout queues are not cleaned here because although they
435          * exist on the state list, appr_unload is called after
436          * ipf_state_unload and the proxies actually are responsible for them
437          * being created. Should the proxy timeouts have their own list?
438          * There's no real justification as this is the only complication.
439          */
440         for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
441                 ifqnext = ifq->ifq_next;
442
443                 if (ipf_deletetimeoutqueue(ifq) == 0)
444                         ipf_freetimeoutqueue(softc, ifq);
445         }
446
447         softs->ipf_state_stats.iss_inuse = 0;
448         softs->ipf_state_stats.iss_active = 0;
449
450         if (softs->ipf_state_inited == 1) {
451                 softs->ipf_state_inited = 0;
452                 ipf_sttab_destroy(softs->ipf_state_tcptq);
453                 MUTEX_DESTROY(&softs->ipf_state_udptq.ifq_lock);
454                 MUTEX_DESTROY(&softs->ipf_state_icmptq.ifq_lock);
455                 MUTEX_DESTROY(&softs->ipf_state_udpacktq.ifq_lock);
456                 MUTEX_DESTROY(&softs->ipf_state_icmpacktq.ifq_lock);
457                 MUTEX_DESTROY(&softs->ipf_state_iptq.ifq_lock);
458                 MUTEX_DESTROY(&softs->ipf_state_deletetq.ifq_lock);
459                 MUTEX_DESTROY(&softs->ipf_state_pending.ifq_lock);
460                 MUTEX_DESTROY(&softs->ipf_stinsert);
461         }
462
463         if (softs->ipf_state_table != NULL) {
464                 KFREES(softs->ipf_state_table,
465                        softs->ipf_state_size * sizeof(*softs->ipf_state_table));
466                 softs->ipf_state_table = NULL;
467         }
468
469         if (softs->ipf_state_seed != NULL) {
470                 KFREES(softs->ipf_state_seed,
471                        softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
472                 softs->ipf_state_seed = NULL;
473         }
474
475         if (softs->ipf_state_stats.iss_bucketlen != NULL) {
476                 KFREES(softs->ipf_state_stats.iss_bucketlen,
477                        softs->ipf_state_size * sizeof(u_int));
478                 softs->ipf_state_stats.iss_bucketlen = NULL;
479         }
480
481         return 0;
482 }
483
484
485 /* ------------------------------------------------------------------------ */
486 /* Function:    ipf_state_set_lock                                          */
487 /* Returns:     Nil                                                         */
488 /* Parameters:  arg(I) - pointer to local context to use                    */
489 /*              tmp(I) - new value for lock                                 */
490 /*                                                                          */
491 /* Stub function that allows for external manipulation of ipf_state_lock    */
492 /* ------------------------------------------------------------------------ */
493 void
494 ipf_state_setlock(arg, tmp)
495         void *arg;
496         int tmp;
497 {
498         ipf_state_softc_t *softs = arg;
499
500         softs->ipf_state_lock = tmp;
501 }
502
503
504 /* ------------------------------------------------------------------------ */
505 /* Function:    ipf_state_stats                                             */
506 /* Returns:     ips_state_t* - pointer to state stats structure             */
507 /* Parameters:  softc(I) - pointer to soft context main structure           */
508 /*                                                                          */
509 /* Put all the current numbers and pointers into a single struct and return */
510 /* a pointer to it.                                                         */
511 /* ------------------------------------------------------------------------ */
512 static ips_stat_t *
513 ipf_state_stats(softc)
514         ipf_main_softc_t *softc;
515 {
516         ipf_state_softc_t *softs = softc->ipf_state_soft;
517         ips_stat_t *issp = &softs->ipf_state_stats;
518
519         issp->iss_state_size = softs->ipf_state_size;
520         issp->iss_state_max = softs->ipf_state_max;
521         issp->iss_table = softs->ipf_state_table;
522         issp->iss_list = softs->ipf_state_list;
523         issp->iss_ticks = softc->ipf_ticks;
524
525 #ifdef IPFILTER_LOGGING
526         issp->iss_log_ok = ipf_log_logok(softc, IPF_LOGSTATE);
527         issp->iss_log_fail = ipf_log_failures(softc, IPF_LOGSTATE);
528 #else
529         issp->iss_log_ok = 0;
530         issp->iss_log_fail = 0;
531 #endif
532         return issp;
533 }
534
535 /* ------------------------------------------------------------------------ */
536 /* Function:    ipf_state_remove                                            */
537 /* Returns:     int - 0 == success, != 0 == failure                         */
538 /* Parameters:  softc(I) - pointer to soft context main structure           */
539 /*              data(I)  - pointer to state structure to delete from table  */
540 /*                                                                          */
541 /* Search for a state structure that matches the one passed, according to   */
542 /* the IP addresses and other protocol specific information.                */
543 /* ------------------------------------------------------------------------ */
544 static int
545 ipf_state_remove(softc, data)
546         ipf_main_softc_t *softc;
547         caddr_t data;
548 {
549         ipf_state_softc_t *softs = softc->ipf_state_soft;
550         ipstate_t *sp, st;
551         int error;
552
553         sp = &st;
554         error = ipf_inobj(softc, data, NULL, &st, IPFOBJ_IPSTATE);
555         if (error)
556                 return EFAULT;
557
558         WRITE_ENTER(&softc->ipf_state);
559         for (sp = softs->ipf_state_list; sp; sp = sp->is_next)
560                 if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
561                     !bcmp((caddr_t)&sp->is_src, (caddr_t)&st.is_src,
562                           sizeof(st.is_src)) &&
563                     !bcmp((caddr_t)&sp->is_dst, (caddr_t)&st.is_dst,
564                           sizeof(st.is_dst)) &&
565                     !bcmp((caddr_t)&sp->is_ps, (caddr_t)&st.is_ps,
566                           sizeof(st.is_ps))) {
567                         ipf_state_del(softc, sp, ISL_REMOVE);
568                         RWLOCK_EXIT(&softc->ipf_state);
569                         return 0;
570                 }
571         RWLOCK_EXIT(&softc->ipf_state);
572
573         IPFERROR(100001);
574         return ESRCH;
575 }
576
577
578 /* ------------------------------------------------------------------------ */
579 /* Function:    ipf_state_ioctl                                             */
580 /* Returns:     int - 0 == success, != 0 == failure                         */
581 /* Parameters:  softc(I) - pointer to soft context main structure           */
582 /*              data(I)  - pointer to ioctl data                            */
583 /*              cmd(I)   - ioctl command integer                            */
584 /*              mode(I)  - file mode bits used with open                    */
585 /*              uid(I)   - uid of process making the ioctl call             */
586 /*              ctx(I)   - pointer specific to context of the call          */
587 /*                                                                          */
588 /* Processes an ioctl call made to operate on the IP Filter state device.   */
589 /* ------------------------------------------------------------------------ */
590 int
591 ipf_state_ioctl(softc, data, cmd, mode, uid, ctx)
592         ipf_main_softc_t *softc;
593         caddr_t data;
594         ioctlcmd_t cmd;
595         int mode, uid;
596         void *ctx;
597 {
598         ipf_state_softc_t *softs = softc->ipf_state_soft;
599         int arg, ret, error = 0;
600         SPL_INT(s);
601
602         switch (cmd)
603         {
604         /*
605          * Delete an entry from the state table.
606          */
607         case SIOCDELST :
608                 error = ipf_state_remove(softc, data);
609                 break;
610
611         /*
612          * Flush the state table
613          */
614         case SIOCIPFFL :
615                 error = BCOPYIN(data, &arg, sizeof(arg));
616                 if (error != 0) {
617                         IPFERROR(100002);
618                         error = EFAULT;
619
620                 } else {
621                         WRITE_ENTER(&softc->ipf_state);
622                         ret = ipf_state_flush(softc, arg, 4);
623                         RWLOCK_EXIT(&softc->ipf_state);
624
625                         error = BCOPYOUT(&ret, data, sizeof(ret));
626                         if (error != 0) {
627                                 IPFERROR(100003);
628                                 error = EFAULT;
629                         }
630                 }
631                 break;
632
633 #ifdef  USE_INET6
634         case SIOCIPFL6 :
635                 error = BCOPYIN(data, &arg, sizeof(arg));
636                 if (error != 0) {
637                         IPFERROR(100004);
638                         error = EFAULT;
639
640                 } else {
641                         WRITE_ENTER(&softc->ipf_state);
642                         ret = ipf_state_flush(softc, arg, 6);
643                         RWLOCK_EXIT(&softc->ipf_state);
644
645                         error = BCOPYOUT(&ret, data, sizeof(ret));
646                         if (error != 0) {
647                                 IPFERROR(100005);
648                                 error = EFAULT;
649                         }
650                 }
651                 break;
652 #endif
653
654         case SIOCMATCHFLUSH :
655                 WRITE_ENTER(&softc->ipf_state);
656                 error = ipf_state_matchflush(softc, data);
657                 RWLOCK_EXIT(&softc->ipf_state);
658                 break;
659
660 #ifdef  IPFILTER_LOG
661         /*
662          * Flush the state log.
663          */
664         case SIOCIPFFB :
665                 if (!(mode & FWRITE)) {
666                         IPFERROR(100008);
667                         error = EPERM;
668                 } else {
669                         int tmp;
670
671                         tmp = ipf_log_clear(softc, IPL_LOGSTATE);
672                         error = BCOPYOUT(&tmp, data, sizeof(tmp));
673                         if (error != 0) {
674                                 IPFERROR(100009);
675                                 error = EFAULT;
676                         }
677                 }
678                 break;
679
680         /*
681          * Turn logging of state information on/off.
682          */
683         case SIOCSETLG :
684                 if (!(mode & FWRITE)) {
685                         IPFERROR(100010);
686                         error = EPERM;
687                 } else {
688                         error = BCOPYIN(data, &softs->ipf_state_logging,
689                                         sizeof(softs->ipf_state_logging));
690                         if (error != 0) {
691                                 IPFERROR(100011);
692                                 error = EFAULT;
693                         }
694                 }
695                 break;
696
697         /*
698          * Return the current state of logging.
699          */
700         case SIOCGETLG :
701                 error = BCOPYOUT(&softs->ipf_state_logging, data,
702                                  sizeof(softs->ipf_state_logging));
703                 if (error != 0) {
704                         IPFERROR(100012);
705                         error = EFAULT;
706                 }
707                 break;
708
709         /*
710          * Return the number of bytes currently waiting to be read.
711          */
712         case FIONREAD :
713                 arg = ipf_log_bytesused(softc, IPL_LOGSTATE);
714                 error = BCOPYOUT(&arg, data, sizeof(arg));
715                 if (error != 0) {
716                         IPFERROR(100013);
717                         error = EFAULT;
718                 }
719                 break;
720 #endif
721
722         /*
723          * Get the current state statistics.
724          */
725         case SIOCGETFS :
726                 error = ipf_outobj(softc, data, ipf_state_stats(softc),
727                                    IPFOBJ_STATESTAT);
728                 break;
729
730         /*
731          * Lock/Unlock the state table.  (Locking prevents any changes, which
732          * means no packets match).
733          */
734         case SIOCSTLCK :
735                 if (!(mode & FWRITE)) {
736                         IPFERROR(100014);
737                         error = EPERM;
738                 } else {
739                         error = ipf_lock(data, &softs->ipf_state_lock);
740                 }
741                 break;
742
743         /*
744          * Add an entry to the current state table.
745          */
746         case SIOCSTPUT :
747                 if (!softs->ipf_state_lock || !(mode &FWRITE)) {
748                         IPFERROR(100015);
749                         error = EACCES;
750                         break;
751                 }
752                 error = ipf_state_putent(softc, softs, data);
753                 break;
754
755         /*
756          * Get a state table entry.
757          */
758         case SIOCSTGET :
759                 if (!softs->ipf_state_lock) {
760                         IPFERROR(100016);
761                         error = EACCES;
762                         break;
763                 }
764                 error = ipf_state_getent(softc, softs, data);
765                 break;
766
767         /*
768          * Return a copy of the hash table bucket lengths
769          */
770         case SIOCSTAT1 :
771                 error = BCOPYOUT(softs->ipf_state_stats.iss_bucketlen, data,
772                                  softs->ipf_state_size * sizeof(u_int));
773                 if (error != 0) {
774                         IPFERROR(100017);
775                         error = EFAULT;
776                 }
777                 break;
778
779         case SIOCGENITER :
780             {
781                 ipftoken_t *token;
782                 ipfgeniter_t iter;
783                 ipfobj_t obj;
784
785                 error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
786                 if (error != 0)
787                         break;
788
789                 SPL_SCHED(s);
790                 token = ipf_token_find(softc, IPFGENITER_STATE, uid, ctx);
791                 if (token != NULL) {
792                         error = ipf_state_iter(softc, token, &iter, &obj);
793                         WRITE_ENTER(&softc->ipf_tokens);
794                         ipf_token_deref(softc, token);
795                         RWLOCK_EXIT(&softc->ipf_tokens);
796                 } else {
797                         IPFERROR(100018);
798                         error = ESRCH;
799                 }
800                 SPL_X(s);
801                 break;
802             }
803
804         case SIOCGTABL :
805                 error = ipf_state_gettable(softc, softs, data);
806                 break;
807
808         case SIOCIPFDELTOK :
809                 error = BCOPYIN(data, &arg, sizeof(arg));
810                 if (error != 0) {
811                         IPFERROR(100019);
812                         error = EFAULT;
813                 } else {
814                         SPL_SCHED(s);
815                         error = ipf_token_del(softc, arg, uid, ctx);
816                         SPL_X(s);
817                 }
818                 break;
819
820         case SIOCGTQTAB :
821                 error = ipf_outobj(softc, data, softs->ipf_state_tcptq,
822                                    IPFOBJ_STATETQTAB);
823                 break;
824
825         default :
826                 IPFERROR(100020);
827                 error = EINVAL;
828                 break;
829         }
830         return error;
831 }
832
833
834 /* ------------------------------------------------------------------------ */
835 /* Function:    ipf_state_getent                                            */
836 /* Returns:     int - 0 == success, != 0 == failure                         */
837 /* Parameters:  softc(I) - pointer to soft context main structure           */
838 /*              softs(I) - pointer to state context structure               */
839 /*              data(I)  - pointer to state structure to retrieve from table*/
840 /*                                                                          */
841 /* Copy out state information from the kernel to a user space process.  If  */
842 /* there is a filter rule associated with the state entry, copy that out    */
843 /* as well.  The entry to copy out is taken from the value of "ips_next" in */
844 /* the struct passed in and if not null and not found in the list of current*/
845 /* state entries, the retrieval fails.                                      */
846 /* ------------------------------------------------------------------------ */
847 static int
848 ipf_state_getent(softc, softs, data)
849         ipf_main_softc_t *softc;
850         ipf_state_softc_t *softs;
851         caddr_t data;
852 {
853         ipstate_t *is, *isn;
854         ipstate_save_t ips;
855         int error;
856
857         error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
858         if (error)
859                 return EFAULT;
860
861         READ_ENTER(&softc->ipf_state);
862         isn = ips.ips_next;
863         if (isn == NULL) {
864                 isn = softs->ipf_state_list;
865                 if (isn == NULL) {
866                         if (ips.ips_next == NULL) {
867                                 RWLOCK_EXIT(&softc->ipf_state);
868                                 IPFERROR(100021);
869                                 return ENOENT;
870                         }
871                         return 0;
872                 }
873         } else {
874                 /*
875                  * Make sure the pointer we're copying from exists in the
876                  * current list of entries.  Security precaution to prevent
877                  * copying of random kernel data.
878                  */
879                 for (is = softs->ipf_state_list; is; is = is->is_next)
880                         if (is == isn)
881                                 break;
882                 if (!is) {
883                         RWLOCK_EXIT(&softc->ipf_state);
884                         IPFERROR(100022);
885                         return ESRCH;
886                 }
887         }
888         ips.ips_next = isn->is_next;
889         bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
890         ips.ips_rule = isn->is_rule;
891         if (isn->is_rule != NULL)
892                 bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
893                       sizeof(ips.ips_fr));
894         RWLOCK_EXIT(&softc->ipf_state);
895         error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
896         return error;
897 }
898
899
900 /* ------------------------------------------------------------------------ */
901 /* Function:    ipf_state_putent                                            */
902 /* Returns:     int - 0 == success, != 0 == failure                         */
903 /* Parameters:  softc(I) - pointer to soft context main structure           */
904 /*              softs(I) - pointer to state context structure               */
905 /*              data(I)  - pointer to state information struct              */
906 /*                                                                          */
907 /* This function implements the SIOCSTPUT ioctl: insert a state entry into  */
908 /* the state table.  If the state info. includes a pointer to a filter rule */
909 /* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
910 /* output.                                                                  */
911 /* ------------------------------------------------------------------------ */
912 int
913 ipf_state_putent(softc, softs, data)
914         ipf_main_softc_t *softc;
915         ipf_state_softc_t *softs;
916         caddr_t data;
917 {
918         ipstate_t *is, *isn;
919         ipstate_save_t ips;
920         int error, out, i;
921         frentry_t *fr;
922         char *name;
923
924         error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
925         if (error != 0)
926                 return error;
927
928         KMALLOC(isn, ipstate_t *);
929         if (isn == NULL) {
930                 IPFERROR(100023);
931                 return ENOMEM;
932         }
933
934         bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
935         bzero((char *)isn, offsetof(struct ipstate, is_pkts));
936         isn->is_sti.tqe_pnext = NULL;
937         isn->is_sti.tqe_next = NULL;
938         isn->is_sti.tqe_ifq = NULL;
939         isn->is_sti.tqe_parent = isn;
940         isn->is_ifp[0] = NULL;
941         isn->is_ifp[1] = NULL;
942         isn->is_ifp[2] = NULL;
943         isn->is_ifp[3] = NULL;
944         isn->is_sync = NULL;
945         fr = ips.ips_rule;
946
947         if (fr == NULL) {
948                 int inserr;
949
950                 READ_ENTER(&softc->ipf_state);
951                 inserr = ipf_state_insert(softc, isn, 0);
952                 MUTEX_EXIT(&isn->is_lock);
953                 RWLOCK_EXIT(&softc->ipf_state);
954
955                 return inserr;
956         }
957
958         if (isn->is_flags & SI_NEWFR) {
959                 KMALLOC(fr, frentry_t *);
960                 if (fr == NULL) {
961                         KFREE(isn);
962                         IPFERROR(100024);
963                         return ENOMEM;
964                 }
965                 bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
966                 out = fr->fr_flags & FR_OUTQUE ? 1 : 0;
967                 isn->is_rule = fr;
968                 ips.ips_is.is_rule = fr;
969                 MUTEX_NUKE(&fr->fr_lock);
970                 MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
971
972                 /*
973                  * Look up all the interface names in the rule.
974                  */
975                 for (i = 0; i < 4; i++) {
976                         if (fr->fr_ifnames[i] == -1) {
977                                 fr->fr_ifas[i] = NULL;
978                                 continue;
979                         }
980                         name = fr->fr_names + fr->fr_ifnames[i];
981                         fr->fr_ifas[i] = ipf_resolvenic(softc, name,
982                                                         fr->fr_family);
983                 }
984
985                 for (i = 0; i < 4; i++) {
986                         name = isn->is_ifname[i];
987                         isn->is_ifp[i] = ipf_resolvenic(softc, name,
988                                                         isn->is_v);
989                 }
990
991                 fr->fr_ref = 0;
992                 fr->fr_dsize = 0;
993                 fr->fr_data = NULL;
994                 fr->fr_type = FR_T_NONE;
995
996                 (void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[0],
997                                 fr->fr_family);
998                 (void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[1],
999                                 fr->fr_family);
1000                 (void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_dif,
1001                                 fr->fr_family);
1002
1003                 /*
1004                  * send a copy back to userland of what we ended up
1005                  * to allow for verification.
1006                  */
1007                 error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
1008                 if (error != 0) {
1009                         KFREE(isn);
1010                         MUTEX_DESTROY(&fr->fr_lock);
1011                         KFREE(fr);
1012                         IPFERROR(100025);
1013                         return EFAULT;
1014                 }
1015                 READ_ENTER(&softc->ipf_state);
1016                 error = ipf_state_insert(softc, isn, 0);
1017                 MUTEX_EXIT(&isn->is_lock);
1018                 RWLOCK_EXIT(&softc->ipf_state);
1019
1020         } else {
1021                 READ_ENTER(&softc->ipf_state);
1022                 for (is = softs->ipf_state_list; is; is = is->is_next)
1023                         if (is->is_rule == fr) {
1024                                 error = ipf_state_insert(softc, isn, 0);
1025                                 MUTEX_EXIT(&isn->is_lock);
1026                                 break;
1027                         }
1028
1029                 if (is == NULL) {
1030                         KFREE(isn);
1031                         isn = NULL;
1032                 }
1033                 RWLOCK_EXIT(&softc->ipf_state);
1034
1035                 if (isn == NULL) {
1036                         IPFERROR(100033);
1037                         error = ESRCH;
1038                 }
1039         }
1040
1041         return error;
1042 }
1043
1044
1045 /* ------------------------------------------------------------------------ */
1046 /* Function:    ipf_state_insert                                            */
1047 /* Returns:     int    - 0 == success, -1 == failure                        */
1048 /* Parameters:  softc(I) - pointer to soft context main structure           */
1049 /* Parameters:  is(I)    - pointer to state structure                       */
1050 /*              rev(I) - flag indicating direction of packet                */
1051 /*                                                                          */
1052 /* Inserts a state structure into the hash table (for lookups) and the list */
1053 /* of state entries (for enumeration).  Resolves all of the interface names */
1054 /* to pointers and adjusts running stats for the hash table as appropriate. */
1055 /*                                                                          */
1056 /* This function can fail if the filter rule has had a population policy of */
1057 /* IP addresses used with stateful filtering assigned to it.                */
1058 /*                                                                          */
1059 /* Locking: it is assumed that some kind of lock on ipf_state is held.      */
1060 /*          Exits with is_lock initialised and held - *EVEN IF ERROR*.      */
1061 /* ------------------------------------------------------------------------ */
1062 int
1063 ipf_state_insert(softc, is, rev)
1064         ipf_main_softc_t *softc;
1065         ipstate_t *is;
1066         int rev;
1067 {
1068         ipf_state_softc_t *softs = softc->ipf_state_soft;
1069         frentry_t *fr;
1070         u_int hv;
1071         int i;
1072
1073         /*
1074          * Look up all the interface names in the state entry.
1075          */
1076         for (i = 0; i < 4; i++) {
1077                 if (is->is_ifp[i] != NULL)
1078                         continue;
1079                 is->is_ifp[i] = ipf_resolvenic(softc, is->is_ifname[i],
1080                                                is->is_v);
1081         }
1082
1083         /*
1084          * If we could trust is_hv, then the modulus would not be needed,
1085          * but when running with IPFILTER_SYNC, this stops bad values.
1086          */
1087         hv = is->is_hv % softs->ipf_state_size;
1088         /* TRACE is, hv */
1089         is->is_hv = hv;
1090
1091         /*
1092          * We need to get both of these locks...the first because it is
1093          * possible that once the insert is complete another packet might
1094          * come along, match the entry and want to update it.
1095          */
1096         MUTEX_INIT(&is->is_lock, "ipf state entry");
1097         MUTEX_ENTER(&is->is_lock);
1098         MUTEX_ENTER(&softs->ipf_stinsert);
1099
1100         fr = is->is_rule;
1101         if (fr != NULL) {
1102                 if ((fr->fr_srctrack.ht_max_nodes != 0) &&
1103                     (ipf_ht_node_add(softc, &fr->fr_srctrack,
1104                                      is->is_family, &is->is_src) == -1)) {
1105                         SBUMPD(ipf_state_stats, iss_max_track);
1106                         MUTEX_EXIT(&softs->ipf_stinsert);
1107                         return -1;
1108                 }
1109
1110                 MUTEX_ENTER(&fr->fr_lock);
1111                 fr->fr_ref++;
1112                 MUTEX_EXIT(&fr->fr_lock);
1113                 fr->fr_statecnt++;
1114         }
1115
1116         if (is->is_flags & (SI_WILDP|SI_WILDA)) {
1117                 DT(iss_wild_plus_one);
1118                 SINCL(ipf_state_stats.iss_wild);
1119         }
1120
1121         SBUMP(ipf_state_stats.iss_proto[is->is_p]);
1122         SBUMP(ipf_state_stats.iss_active_proto[is->is_p]);
1123
1124         /*
1125          * add into list table.
1126          */
1127         if (softs->ipf_state_list != NULL)
1128                 softs->ipf_state_list->is_pnext = &is->is_next;
1129         is->is_pnext = &softs->ipf_state_list;
1130         is->is_next = softs->ipf_state_list;
1131         softs->ipf_state_list = is;
1132
1133         if (softs->ipf_state_table[hv] != NULL)
1134                 softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
1135         else
1136                 softs->ipf_state_stats.iss_inuse++;
1137         is->is_phnext = softs->ipf_state_table + hv;
1138         is->is_hnext = softs->ipf_state_table[hv];
1139         softs->ipf_state_table[hv] = is;
1140         softs->ipf_state_stats.iss_bucketlen[hv]++;
1141         softs->ipf_state_stats.iss_active++;
1142         MUTEX_EXIT(&softs->ipf_stinsert);
1143
1144         ipf_state_setqueue(softc, is, rev);
1145
1146         return 0;
1147 }
1148
1149
1150 /* ------------------------------------------------------------------------ */
1151 /* Function:    ipf_state_matchipv4addrs                                    */
1152 /* Returns:     int - 2 addresses match (strong match), 1 reverse match,    */
1153 /*                    0 no match                                            */
1154 /* Parameters:  is1, is2 pointers to states we are checking                 */
1155 /*                                                                          */
1156 /* Function matches IPv4 addresses it returns strong match for ICMP proto   */
1157 /* even there is only reverse match                                         */
1158 /* ------------------------------------------------------------------------ */
1159 static int
1160 ipf_state_matchipv4addrs(is1, is2)
1161         ipstate_t *is1, *is2;
1162 {
1163         int     rv;
1164
1165         if (is1->is_saddr == is2->is_saddr && is1->is_daddr == is2->is_daddr)
1166                 rv = 2;
1167         else if (is1->is_saddr == is2->is_daddr &&
1168             is1->is_daddr == is2->is_saddr) {
1169                 /* force strong match for ICMP protocol */
1170                 rv = (is1->is_p == IPPROTO_ICMP) ? 2 : 1;
1171         }
1172         else
1173                 rv = 0;
1174
1175         return (rv);
1176 }
1177
1178
1179 /* ------------------------------------------------------------------------ */
1180 /* Function:    ipf_state_matchipv6addrs                                    */
1181 /* Returns:     int - 2 addresses match (strong match), 1 reverse match,    */
1182 /*                    0 no match                                            */
1183 /* Parameters:  is1, is2 pointers to states we are checking                 */
1184 /*                                                                          */
1185 /* Function matches IPv6 addresses it returns strong match for ICMP proto   */
1186 /* even there is only reverse match                                         */
1187 /* ------------------------------------------------------------------------ */
1188 static int
1189 ipf_state_matchipv6addrs(is1, is2)
1190         ipstate_t *is1, *is2;
1191 {
1192         int     rv;
1193
1194         if (IP6_EQ(&is1->is_src, &is2->is_src) &&
1195             IP6_EQ(&is1->is_dst, &is2->is_dst))
1196                 rv = 2;
1197         else if (IP6_EQ(&is1->is_src, &is2->is_dst) &&
1198             IP6_EQ(&is1->is_dst, &is2->is_src)) {
1199                 /* force strong match for ICMPv6 protocol */
1200                 rv = (is1->is_p == IPPROTO_ICMPV6) ? 2 : 1;
1201         }
1202         else
1203                 rv = 0;
1204
1205         return (rv);
1206 }
1207
1208
1209 /* ------------------------------------------------------------------------ */
1210 /* Function:    ipf_state_matchaddresses                                    */
1211 /* Returns:     int - 2 addresses match, 1 reverse match, zero no match     */
1212 /* Parameters:  is1, is2 pointers to states we are checking                 */
1213 /*                                                                          */
1214 /* function retruns true if two pairs of addresses belong to single         */
1215 /* connection. suppose there are two endpoints:                             */
1216 /*      endpoint1 1.1.1.1                                                   */
1217 /*      endpoint2 1.1.1.2                                                   */
1218 /*                                                                          */
1219 /* the state is established by packet flying from .1 to .2 so we see:       */
1220 /*      is1->src = 1.1.1.1                                                  */
1221 /*      is1->dst = 1.1.1.2                                                  */
1222 /* now endpoint 1.1.1.2 sends answer                                        */
1223 /* retreives is1 record created by first packat and compares it with is2    */
1224 /* temporal record, is2 is initialized as follows:                          */
1225 /*      is2->src = 1.1.1.2                                                  */
1226 /*      is2->dst = 1.1.1.1                                                  */
1227 /* in this case 1 will be returned                                          */
1228 /*                                                                          */
1229 /* the ipf_matchaddresses() assumes those two records to be same. of course */
1230 /* the ipf_matchaddresses() also assume records are same in case you pass   */
1231 /* identical arguments (i.e. ipf_matchaddress(is1, is1) would return 2      */
1232 /* ------------------------------------------------------------------------ */
1233 static int
1234 ipf_state_matchaddresses(is1, is2)
1235         ipstate_t *is1, *is2;
1236 {
1237         int     rv;
1238
1239         if (is1->is_v == 4) {
1240                 rv = ipf_state_matchipv4addrs(is1, is2);
1241         }
1242         else {
1243                 rv = ipf_state_matchipv6addrs(is1, is2);
1244         }
1245
1246         return (rv);
1247 }
1248
1249
1250 /* ------------------------------------------------------------------------ */
1251 /* Function:    ipf_matchports                                              */
1252 /* Returns:     int - 2 match, 1 rverse match, 0 no match                   */
1253 /* Parameters:  ppairs1, ppairs - src, dst ports we want to match           */
1254 /*                                                                          */
1255 /* performs the same match for isps members as for addresses                */
1256 /* ------------------------------------------------------------------------ */
1257 static int
1258 ipf_state_matchports(ppairs1, ppairs2)
1259         udpinfo_t *ppairs1, *ppairs2;
1260 {
1261         int     rv;
1262
1263         if (ppairs1->us_sport == ppairs2->us_sport &&
1264             ppairs1->us_dport == ppairs2->us_dport)
1265                 rv = 2;
1266         else if (ppairs1->us_sport == ppairs2->us_dport &&
1267                     ppairs1->us_dport == ppairs2->us_sport)
1268                 rv = 1;
1269         else
1270                 rv = 0;
1271
1272         return (rv);
1273 }
1274
1275
1276 /* ------------------------------------------------------------------------ */
1277 /* Function:    ipf_matchisps                                               */
1278 /* Returns:     int - nonzero if isps members match, 0 nomatch              */
1279 /* Parameters:  is1, is2 - states we want to match                          */
1280 /*                                                                          */
1281 /* performs the same match for isps members as for addresses                */
1282 /* ------------------------------------------------------------------------ */
1283 static int
1284 ipf_state_matchisps(is1, is2)
1285         ipstate_t *is1, *is2;
1286 {
1287         int     rv;
1288
1289         if (is1->is_p == is2->is_p) {
1290                 switch (is1->is_p)
1291                 {
1292                 case IPPROTO_TCP :
1293                 case IPPROTO_UDP :
1294                 case IPPROTO_GRE :
1295                         /* greinfo_t can be also interprted as port pair */
1296                         rv = ipf_state_matchports(&is1->is_ps.is_us,
1297                                                   &is2->is_ps.is_us);
1298                         break;
1299
1300                 case IPPROTO_ICMP :
1301                 case IPPROTO_ICMPV6 :
1302                         /* force strong match for ICMP datagram. */
1303                         if (bcmp(&is1->is_ps, &is2->is_ps,
1304                                  sizeof(icmpinfo_t)) == 0)  {
1305                                 rv = 2;
1306                         } else {
1307                                 rv = 0;
1308                         }
1309                         break;
1310
1311                 default:
1312                         rv = 0;
1313                 }
1314         } else {
1315                 rv = 0;
1316         }
1317
1318         return (rv);
1319 }
1320
1321
1322 /* ------------------------------------------------------------------------ */
1323 /* Function:    ipf_state_match                                             */
1324 /* Returns:     int - nonzero match, zero no match                          */
1325 /* Parameters:  is1, is2 - states we want to match                          */
1326 /*                                                                          */
1327 /* ------------------------------------------------------------------------ */
1328 static int
1329 ipf_state_match(is1, is2)
1330         ipstate_t *is1, *is2;
1331 {
1332         int     rv;
1333         int     amatch;
1334         int     pomatch;
1335
1336         if (bcmp(&is1->is_pass, &is2->is_pass,
1337                  offsetof(struct ipstate, is_authmsk) -
1338                  offsetof(struct ipstate, is_pass)) == 0) {
1339
1340                 pomatch = ipf_state_matchisps(is1, is2);
1341                 amatch = ipf_state_matchaddresses(is1, is2);
1342                 rv = (amatch != 0) && (amatch == pomatch);
1343         } else {
1344                 rv = 0;
1345         }
1346
1347         return (rv);
1348 }
1349
1350 /* ------------------------------------------------------------------------ */
1351 /* Function:    ipf_state_add                                               */
1352 /* Returns:     ipstate_t - 0 = success                                     */
1353 /* Parameters:  softc(I)  - pointer to soft context main structure          */
1354 /*              fin(I)    - pointer to packet information                   */
1355 /*              stsave(O) - pointer to place to save pointer to created     */
1356 /*                          state structure.                                */
1357 /*              flags(I)  - flags to use when creating the structure        */
1358 /*                                                                          */
1359 /* Creates a new IP state structure from the packet information collected.  */
1360 /* Inserts it into the state table and appends to the bottom of the active  */
1361 /* list.  If the capacity of the table has reached the maximum allowed then */
1362 /* the call will fail and a flush is scheduled for the next timeout call.   */
1363 /*                                                                          */
1364 /* NOTE: The use of stsave to point to nat_state will result in memory      */
1365 /*       corruption.  It should only be used to point to objects that will  */
1366 /*       either outlive this (not expired) or will deref the ip_state_t     */
1367 /*       when they are deleted.                                             */
1368 /* ------------------------------------------------------------------------ */
1369 int
1370 ipf_state_add(softc, fin, stsave, flags)
1371         ipf_main_softc_t *softc;
1372         fr_info_t *fin;
1373         ipstate_t **stsave;
1374         u_int flags;
1375 {
1376         ipf_state_softc_t *softs = softc->ipf_state_soft;
1377         ipstate_t *is, ips;
1378         struct icmp *ic;
1379         u_int pass, hv;
1380         frentry_t *fr;
1381         tcphdr_t *tcp;
1382         frdest_t *fdp;
1383         int out;
1384
1385         /*
1386          * If a packet that was created locally is trying to go out but we
1387          * do not match here here because of this lock, it is likely that
1388          * the policy will block it and return network unreachable back up
1389          * the stack. To mitigate this error, EAGAIN is returned instead,
1390          * telling the IP stack to try sending this packet again later.
1391          */
1392         if (softs->ipf_state_lock) {
1393                 SBUMPD(ipf_state_stats, iss_add_locked);
1394                 fin->fin_error = EAGAIN;
1395                 return -1;
1396         }
1397
1398         if (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)) {
1399                 SBUMPD(ipf_state_stats, iss_add_bad);
1400                 return -1;
1401         }
1402
1403         if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN)) {
1404                 SBUMPD(ipf_state_stats, iss_add_oow);
1405                 return -1;
1406         }
1407
1408         if ((softs->ipf_state_stats.iss_active * 100 / softs->ipf_state_max) >
1409             softs->ipf_state_wm_high) {
1410                 softs->ipf_state_doflush = 1;
1411         }
1412
1413         /*
1414          * If a "keep state" rule has reached the maximum number of references
1415          * to it, then schedule an automatic flush in case we can clear out
1416          * some "dead old wood".  Note that because the lock isn't held on
1417          * fr it is possible that we could overflow.  The cost of overflowing
1418          * is being ignored here as the number by which it can overflow is
1419          * a product of the number of simultaneous threads that could be
1420          * executing in here, so a limit of 100 won't result in 200, but could
1421          * result in 101 or 102.
1422          */
1423         fr = fin->fin_fr;
1424         if (fr != NULL) {
1425                 if ((softs->ipf_state_stats.iss_active >=
1426                      softs->ipf_state_max) && (fr->fr_statemax == 0)) {
1427                         SBUMPD(ipf_state_stats, iss_max);
1428                         return 1;
1429                 }
1430                 if ((fr->fr_statemax != 0) &&
1431                     (fr->fr_statecnt >= fr->fr_statemax)) {
1432                         SBUMPD(ipf_state_stats, iss_max_ref);
1433                         return 2;
1434                 }
1435         }
1436
1437         is = &ips;
1438         if (fr == NULL) {
1439                 pass = softc->ipf_flags;
1440                 is->is_tag = FR_NOLOGTAG;
1441         } else {
1442                 pass = fr->fr_flags;
1443         }
1444
1445         ic = NULL;
1446         tcp = NULL;
1447         out = fin->fin_out;
1448         bzero((char *)is, sizeof(*is));
1449         is->is_die = 1 + softc->ipf_ticks;
1450         /*
1451          * We want to check everything that is a property of this packet,
1452          * but we don't (automatically) care about it's fragment status as
1453          * this may change.
1454          */
1455         is->is_pass = pass;
1456         is->is_v = fin->fin_v;
1457         is->is_sec = fin->fin_secmsk;
1458         is->is_secmsk = 0xffff;
1459         is->is_auth = fin->fin_auth;
1460         is->is_authmsk = 0xffff;
1461         is->is_family = fin->fin_family;
1462         is->is_opt[0] = fin->fin_optmsk;
1463         is->is_optmsk[0] = 0xffffffff;
1464         if (is->is_v == 6) {
1465                 is->is_opt[0] &= ~0x8;
1466                 is->is_optmsk[0] &= ~0x8;
1467         }
1468
1469         /*
1470          * Copy and calculate...
1471          */
1472         hv = (is->is_p = fin->fin_fi.fi_p);
1473         is->is_src = fin->fin_fi.fi_src;
1474         hv += is->is_saddr;
1475         is->is_dst = fin->fin_fi.fi_dst;
1476         hv += is->is_daddr;
1477 #ifdef  USE_INET6
1478         if (fin->fin_v == 6) {
1479                 /*
1480                  * For ICMPv6, we check to see if the destination address is
1481                  * a multicast address.  If it is, do not include it in the
1482                  * calculation of the hash because the correct reply will come
1483                  * back from a real address, not a multicast address.
1484                  */
1485                 if ((is->is_p == IPPROTO_ICMPV6) &&
1486                     IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
1487                         /*
1488                          * So you can do keep state with neighbour discovery.
1489                          *
1490                          * Here we could use the address from the neighbour
1491                          * solicit message to put in the state structure and
1492                          * we could use that without a wildcard flag too...
1493                          */
1494                         flags |= SI_W_DADDR;
1495                         hv -= is->is_daddr;
1496                 } else {
1497                         hv += is->is_dst.i6[1];
1498                         hv += is->is_dst.i6[2];
1499                         hv += is->is_dst.i6[3];
1500                 }
1501                 hv += is->is_src.i6[1];
1502                 hv += is->is_src.i6[2];
1503                 hv += is->is_src.i6[3];
1504         }
1505 #endif
1506         if ((fin->fin_v == 4) &&
1507             (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
1508                 flags |= SI_W_DADDR;
1509                 hv -= is->is_daddr;
1510         }
1511
1512         switch (is->is_p)
1513         {
1514 #ifdef  USE_INET6
1515         case IPPROTO_ICMPV6 :
1516                 ic = fin->fin_dp;
1517
1518                 switch (ic->icmp_type)
1519                 {
1520                 case ICMP6_ECHO_REQUEST :
1521                         hv += (is->is_icmp.ici_id = ic->icmp_id);
1522                         /*FALLTHROUGH*/
1523                 case ICMP6_MEMBERSHIP_QUERY :
1524                 case ND_ROUTER_SOLICIT :
1525                 case ND_NEIGHBOR_SOLICIT :
1526                 case ICMP6_NI_QUERY :
1527                         is->is_icmp.ici_type = ic->icmp_type;
1528                         break;
1529                 default :
1530                         SBUMPD(ipf_state_stats, iss_icmp6_notquery);
1531                         return -2;
1532                 }
1533                 break;
1534 #endif
1535         case IPPROTO_ICMP :
1536                 ic = fin->fin_dp;
1537
1538                 switch (ic->icmp_type)
1539                 {
1540                 case ICMP_ECHO :
1541                 case ICMP_TSTAMP :
1542                 case ICMP_IREQ :
1543                 case ICMP_MASKREQ :
1544                         is->is_icmp.ici_type = ic->icmp_type;
1545                         hv += (is->is_icmp.ici_id = ic->icmp_id);
1546                         break;
1547                 default :
1548                         SBUMPD(ipf_state_stats, iss_icmp_notquery);
1549                         return -3;
1550                 }
1551                 break;
1552
1553 #if 0
1554         case IPPROTO_GRE :
1555                 gre = fin->fin_dp;
1556
1557                 is->is_gre.gs_flags = gre->gr_flags;
1558                 is->is_gre.gs_ptype = gre->gr_ptype;
1559                 if (GRE_REV(is->is_gre.gs_flags) == 1) {
1560                         is->is_call[0] = fin->fin_data[0];
1561                         is->is_call[1] = fin->fin_data[1];
1562                 }
1563                 break;
1564 #endif
1565
1566         case IPPROTO_TCP :
1567                 tcp = fin->fin_dp;
1568
1569                 if (tcp->th_flags & TH_RST) {
1570                         SBUMPD(ipf_state_stats, iss_tcp_rstadd);
1571                         return -4;
1572                 }
1573
1574                 /* TRACE is, flags, hv */
1575
1576                 /*
1577                  * The endian of the ports doesn't matter, but the ack and
1578                  * sequence numbers do as we do mathematics on them later.
1579                  */
1580                 is->is_sport = htons(fin->fin_data[0]);
1581                 is->is_dport = htons(fin->fin_data[1]);
1582                 if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1583                         hv += is->is_sport;
1584                         hv += is->is_dport;
1585                 }
1586
1587                 /* TRACE is, flags, hv */
1588
1589                 /*
1590                  * If this is a real packet then initialise fields in the
1591                  * state information structure from the TCP header information.
1592                  */
1593
1594                 is->is_maxdwin = 1;
1595                 is->is_maxswin = ntohs(tcp->th_win);
1596                 if (is->is_maxswin == 0)
1597                         is->is_maxswin = 1;
1598
1599                 if ((fin->fin_flx & FI_IGNORE) == 0) {
1600                         is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
1601                                       (TCP_OFF(tcp) << 2) +
1602                                       ((tcp->th_flags & TH_SYN) ? 1 : 0) +
1603                                       ((tcp->th_flags & TH_FIN) ? 1 : 0);
1604                         is->is_maxsend = is->is_send;
1605
1606                         /*
1607                          * Window scale option is only present in
1608                          * SYN/SYN-ACK packet.
1609                          */
1610                         if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
1611                             TH_SYN &&
1612                             (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1613                                 if (ipf_tcpoptions(softs, fin, tcp,
1614                                               &is->is_tcp.ts_data[0]) == -1) {
1615                                         fin->fin_flx |= FI_BAD;
1616                                         DT1(ipf_fi_bad_tcpoptions_th_fin_ack_ecnall, fr_info_t *, fin);
1617                                 }
1618                         }
1619
1620                         if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
1621                                 ipf_checknewisn(fin, is);
1622                                 ipf_fixoutisn(fin, is);
1623                         }
1624
1625                         if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1626                                 flags |= IS_TCPFSM;
1627                         else {
1628                                 is->is_maxdwin = is->is_maxswin * 2;
1629                                 is->is_dend = ntohl(tcp->th_ack);
1630                                 is->is_maxdend = ntohl(tcp->th_ack);
1631                                 is->is_maxdwin *= 2;
1632                         }
1633                 }
1634
1635                 /*
1636                  * If we're creating state for a starting connection, start
1637                  * the timer on it as we'll never see an error if it fails
1638                  * to connect.
1639                  */
1640                 break;
1641
1642         case IPPROTO_UDP :
1643                 tcp = fin->fin_dp;
1644
1645                 is->is_sport = htons(fin->fin_data[0]);
1646                 is->is_dport = htons(fin->fin_data[1]);
1647                 if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1648                         hv += tcp->th_dport;
1649                         hv += tcp->th_sport;
1650                 }
1651                 break;
1652
1653         default :
1654                 break;
1655         }
1656         hv = DOUBLE_HASH(hv);
1657         is->is_hv = hv;
1658
1659         /*
1660          * Look for identical state.
1661          */
1662         for (is = softs->ipf_state_table[hv % softs->ipf_state_size];
1663              is != NULL; is = is->is_hnext) {
1664                 if (ipf_state_match(&ips, is) == 1)
1665                         break;
1666         }
1667         if (is != NULL) {
1668                 SBUMPD(ipf_state_stats, iss_add_dup);
1669                 return 3;
1670         }
1671
1672         if (softs->ipf_state_stats.iss_bucketlen[hv] >=
1673             softs->ipf_state_maxbucket) {
1674                 SBUMPD(ipf_state_stats, iss_bucket_full);
1675                 return 4;
1676         }
1677
1678         /*
1679          * No existing state; create new
1680          */
1681         KMALLOC(is, ipstate_t *);
1682         if (is == NULL) {
1683                 SBUMPD(ipf_state_stats, iss_nomem);
1684                 return 5;
1685         }
1686         bcopy((char *)&ips, (char *)is, sizeof(*is));
1687         is->is_flags = flags & IS_INHERITED;
1688         is->is_rulen = fin->fin_rule;
1689         is->is_rule = fr;
1690
1691         /*
1692          * Do not do the modulus here, it is done in ipf_state_insert().
1693          */
1694         if (fr != NULL) {
1695                 ipftq_t *tq;
1696
1697                 (void) strncpy(is->is_group, FR_NAME(fr, fr_group),
1698                                FR_GROUPLEN);
1699                 if (fr->fr_age[0] != 0) {
1700                         tq = ipf_addtimeoutqueue(softc,
1701                                                  &softs->ipf_state_usertq,
1702                                                  fr->fr_age[0]);
1703                         is->is_tqehead[0] = tq;
1704                         is->is_sti.tqe_flags |= TQE_RULEBASED;
1705                 }
1706                 if (fr->fr_age[1] != 0) {
1707                         tq = ipf_addtimeoutqueue(softc,
1708                                                  &softs->ipf_state_usertq,
1709                                                  fr->fr_age[1]);
1710                         is->is_tqehead[1] = tq;
1711                         is->is_sti.tqe_flags |= TQE_RULEBASED;
1712                 }
1713
1714                 is->is_tag = fr->fr_logtag;
1715         }
1716
1717         /*
1718          * It may seem strange to set is_ref to 2, but if stsave is not NULL
1719          * then a copy of the pointer is being stored somewhere else and in
1720          * the end, it will expect to be able to do something with it.
1721          */
1722         is->is_me = stsave;
1723         if (stsave != NULL) {
1724                 *stsave = is;
1725                 is->is_ref = 2;
1726         } else {
1727                 is->is_ref = 1;
1728         }
1729         is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1730         is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1731         is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1732         is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1733         if ((fin->fin_flx & FI_IGNORE) == 0) {
1734                 is->is_pkts[out] = 1;
1735                 fin->fin_pktnum = 1;
1736                 is->is_bytes[out] = fin->fin_plen;
1737                 is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1738                 is->is_flx[out][0] &= ~FI_OOW;
1739         }
1740
1741         if (pass & FR_STLOOSE)
1742                 is->is_flags |= IS_LOOSE;
1743
1744         if (pass & FR_STSTRICT)
1745                 is->is_flags |= IS_STRICT;
1746
1747         if (pass & FR_STATESYNC)
1748                 is->is_flags |= IS_STATESYNC;
1749
1750         if (pass & FR_LOGFIRST)
1751                 is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1752
1753         READ_ENTER(&softc->ipf_state);
1754
1755         if (ipf_state_insert(softc, is, fin->fin_rev) == -1) {
1756                 RWLOCK_EXIT(&softc->ipf_state);
1757                 /*
1758                  * This is a bit more manual than it should be but
1759                  * ipf_state_del cannot be called.
1760                  */
1761                 MUTEX_EXIT(&is->is_lock);
1762                 MUTEX_DESTROY(&is->is_lock);
1763                 if (is->is_tqehead[0] != NULL) {
1764                         if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
1765                                 ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
1766                         is->is_tqehead[0] = NULL;
1767                 }
1768                 if (is->is_tqehead[1] != NULL) {
1769                         if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
1770                                 ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
1771                         is->is_tqehead[1] = NULL;
1772                 }
1773                 KFREE(is);
1774                 return -1;
1775         }
1776
1777         /*
1778          * Filling in the interface name is after the insert so that an
1779          * event (such as add/delete) of an interface that is referenced
1780          * by this rule will see this state entry.
1781          */
1782         if (fr != NULL) {
1783                 /*
1784                  * The name '-' is special for network interfaces and causes
1785                  * a NULL name to be present, always, allowing packets to
1786                  * match it, regardless of their interface.
1787                  */
1788                 if ((fin->fin_ifp == NULL) ||
1789                     (fr->fr_ifnames[out << 1] != -1 &&
1790                      fr->fr_names[fr->fr_ifnames[out << 1] + 0] == '-' &&
1791                      fr->fr_names[fr->fr_ifnames[out << 1] + 1] == '\0')) {
1792                         is->is_ifp[out << 1] = fr->fr_ifas[0];
1793                         strncpy(is->is_ifname[out << 1],
1794                                 fr->fr_names + fr->fr_ifnames[0],
1795                                 sizeof(fr->fr_ifnames[0]));
1796                 } else {
1797                         is->is_ifp[out << 1] = fin->fin_ifp;
1798                         COPYIFNAME(fin->fin_v, fin->fin_ifp,
1799                                    is->is_ifname[out << 1]);
1800                 }
1801
1802                 is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1803                 if (fr->fr_ifnames[1] != -1) {
1804                         strncpy(is->is_ifname[(out << 1) + 1],
1805                                 fr->fr_names + fr->fr_ifnames[1],
1806                                 sizeof(fr->fr_ifnames[1]));
1807                 }
1808
1809                 is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1810                 if (fr->fr_ifnames[2] != -1) {
1811                         strncpy(is->is_ifname[((1 - out) << 1)],
1812                                 fr->fr_names + fr->fr_ifnames[2],
1813                                 sizeof(fr->fr_ifnames[2]));
1814                 }
1815
1816                 is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1817                 if (fr->fr_ifnames[3] != -1) {
1818                         strncpy(is->is_ifname[((1 - out) << 1) + 1],
1819                                 fr->fr_names + fr->fr_ifnames[3],
1820                                 sizeof(fr->fr_ifnames[3]));
1821                 }
1822         } else {
1823                 if (fin->fin_ifp != NULL) {
1824                         is->is_ifp[out << 1] = fin->fin_ifp;
1825                         COPYIFNAME(fin->fin_v, fin->fin_ifp,
1826                                    is->is_ifname[out << 1]);
1827                 }
1828         }
1829
1830         if (fin->fin_p == IPPROTO_TCP) {
1831                 /*
1832                 * If we're creating state for a starting connection, start the
1833                 * timer on it as we'll never see an error if it fails to
1834                 * connect.
1835                 */
1836                 (void) ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
1837                                    is->is_flags, 2);
1838         }
1839         MUTEX_EXIT(&is->is_lock);
1840         if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1841                 is->is_sync = ipf_sync_new(softc, SMC_STATE, fin, is);
1842         if (softs->ipf_state_logging)
1843                 ipf_state_log(softc, is, ISL_NEW);
1844
1845         RWLOCK_EXIT(&softc->ipf_state);
1846
1847         fin->fin_flx |= FI_STATE;
1848         if (fin->fin_flx & FI_FRAG)
1849                 (void) ipf_frag_new(softc, fin, pass);
1850
1851         fdp = &fr->fr_tifs[0];
1852         if (fdp->fd_type == FRD_DSTLIST) {
1853                 ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1854                                         &is->is_tifs[0]);
1855         } else {
1856                 bcopy(fdp, &is->is_tifs[0], sizeof(*fdp));
1857         }
1858
1859         fdp = &fr->fr_tifs[1];
1860         if (fdp->fd_type == FRD_DSTLIST) {
1861                 ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1862                                         &is->is_tifs[1]);
1863         } else {
1864                 bcopy(fdp, &is->is_tifs[1], sizeof(*fdp));
1865         }
1866         fin->fin_tif = &is->is_tifs[fin->fin_rev];
1867
1868         fdp = &fr->fr_dif;
1869         if (fdp->fd_type == FRD_DSTLIST) {
1870                 ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1871                                         &is->is_dif);
1872         } else {
1873                 bcopy(fdp, &is->is_dif, sizeof(*fdp));
1874         }
1875         fin->fin_dif = &is->is_dif;
1876
1877         return 0;
1878 }
1879
1880
1881 /* ------------------------------------------------------------------------ */
1882 /* Function:    ipf_tcpoptions                                              */
1883 /* Returns:     int - 1 == packet matches state entry, 0 == it does not,    */
1884 /*                   -1 == packet has bad TCP options data                  */
1885 /* Parameters:  softs(I) - pointer to state context structure               */
1886 /*              fin(I) - pointer to packet information                      */
1887 /*              tcp(I) - pointer to TCP packet header                       */
1888 /*              td(I)  - pointer to TCP data held as part of the state      */
1889 /*                                                                          */
1890 /* Look after the TCP header for any options and deal with those that are   */
1891 /* present.  Record details about those that we recogise.                   */
1892 /* ------------------------------------------------------------------------ */
1893 static int
1894 ipf_tcpoptions(softs, fin, tcp, td)
1895         ipf_state_softc_t *softs;
1896         fr_info_t *fin;
1897         tcphdr_t *tcp;
1898         tcpdata_t *td;
1899 {
1900         int off, mlen, ol, i, len, retval;
1901         char buf[64], *s, opt;
1902         mb_t *m = NULL;
1903
1904         len = (TCP_OFF(tcp) << 2);
1905         if (fin->fin_dlen < len) {
1906                 SBUMPD(ipf_state_stats, iss_tcp_toosmall);
1907                 return 0;
1908         }
1909         len -= sizeof(*tcp);
1910
1911         off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1912
1913         m = fin->fin_m;
1914         mlen = MSGDSIZE(m) - off;
1915         if (len > mlen) {
1916                 len = mlen;
1917                 retval = 0;
1918         } else {
1919                 retval = 1;
1920         }
1921
1922         COPYDATA(m, off, len, buf);
1923
1924         for (s = buf; len > 0; ) {
1925                 opt = *s;
1926                 if (opt == TCPOPT_EOL)
1927                         break;
1928                 else if (opt == TCPOPT_NOP)
1929                         ol = 1;
1930                 else {
1931                         if (len < 2)
1932                                 break;
1933                         ol = (int)*(s + 1);
1934                         if (ol < 2 || ol > len)
1935                                 break;
1936
1937                         /*
1938                          * Extract the TCP options we are interested in out of
1939                          * the header and store them in the the tcpdata struct.
1940                          */
1941                         switch (opt)
1942                         {
1943                         case TCPOPT_WINDOW :
1944                                 if (ol == TCPOLEN_WINDOW) {
1945                                         i = (int)*(s + 2);
1946                                         if (i > TCP_WSCALE_MAX)
1947                                                 i = TCP_WSCALE_MAX;
1948                                         else if (i < 0)
1949                                                 i = 0;
1950                                         td->td_winscale = i;
1951                                         td->td_winflags |= TCP_WSCALE_SEEN|
1952                                                            TCP_WSCALE_FIRST;
1953                                 } else
1954                                         retval = -1;
1955                                 break;
1956                         case TCPOPT_MAXSEG :
1957                                 /*
1958                                  * So, if we wanted to set the TCP MAXSEG,
1959                                  * it should be done here...
1960                                  */
1961                                 if (ol == TCPOLEN_MAXSEG) {
1962                                         i = (int)*(s + 2);
1963                                         i <<= 8;
1964                                         i += (int)*(s + 3);
1965                                         td->td_maxseg = i;
1966                                 } else
1967                                         retval = -1;
1968                                 break;
1969                         case TCPOPT_SACK_PERMITTED :
1970                                 if (ol == TCPOLEN_SACK_PERMITTED)
1971                                         td->td_winflags |= TCP_SACK_PERMIT;
1972                                 else
1973                                         retval = -1;
1974                                 break;
1975                         }
1976                 }
1977                 len -= ol;
1978                 s += ol;
1979         }
1980         if (retval == -1) {
1981                 SBUMPD(ipf_state_stats, iss_tcp_badopt);
1982         }
1983         return retval;
1984 }
1985
1986
1987 /* ------------------------------------------------------------------------ */
1988 /* Function:    ipf_state_tcp                                               */
1989 /* Returns:     int - 1 == packet matches state entry, 0 == it does not     */
1990 /* Parameters:  softc(I)  - pointer to soft context main structure          */
1991 /*              softs(I) - pointer to state context structure               */
1992 /*              fin(I)   - pointer to packet information                    */
1993 /*              tcp(I)   - pointer to TCP packet header                     */
1994 /*              is(I)  - pointer to master state structure                  */
1995 /*                                                                          */
1996 /* Check to see if a packet with TCP headers fits within the TCP window.    */
1997 /* Change timeout depending on whether new packet is a SYN-ACK returning    */
1998 /* for a SYN or a RST or FIN which indicate time to close up shop.          */
1999 /* ------------------------------------------------------------------------ */
2000 static int
2001 ipf_state_tcp(softc, softs, fin, tcp, is)
2002         ipf_main_softc_t *softc;
2003         ipf_state_softc_t *softs;
2004         fr_info_t *fin;
2005         tcphdr_t *tcp;
2006         ipstate_t *is;
2007 {
2008         tcpdata_t  *fdata, *tdata;
2009         int source, ret, flags;
2010
2011         source = !fin->fin_rev;
2012         if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) &&
2013             (ntohs(is->is_sport) != fin->fin_data[0]))
2014                 source = 0;
2015         fdata = &is->is_tcp.ts_data[!source];
2016         tdata = &is->is_tcp.ts_data[source];
2017
2018         MUTEX_ENTER(&is->is_lock);
2019
2020         /*
2021          * If a SYN packet is received for a connection that is on the way out
2022          * but hasn't yet departed then advance this session along the way.
2023          */
2024         if ((tcp->th_flags & TH_OPENING) == TH_SYN) {
2025                 if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
2026                     (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
2027                         is->is_state[!source] = IPF_TCPS_CLOSED;
2028                         ipf_movequeue(softc->ipf_ticks, &is->is_sti,
2029                                       is->is_sti.tqe_ifq,
2030                                       &softs->ipf_state_deletetq);
2031                         MUTEX_EXIT(&is->is_lock);
2032                         DT1(iss_tcp_closing, ipstate_t *, is);
2033                         SBUMP(ipf_state_stats.iss_tcp_closing);
2034                         return 0;
2035                 }
2036         }
2037
2038         if (is->is_flags & IS_LOOSE)
2039                 ret = 1;
2040         else
2041                 ret = ipf_state_tcpinwindow(fin, fdata, tdata, tcp,
2042                                             is->is_flags);
2043         if (ret > 0) {
2044                 /*
2045                  * Nearing end of connection, start timeout.
2046                  */
2047                 ret = ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
2048                                   is->is_flags, ret);
2049                 if (ret == 0) {
2050                         MUTEX_EXIT(&is->is_lock);
2051                         DT2(iss_tcp_fsm, fr_info_t *, fin, ipstate_t *, is);
2052                         SBUMP(ipf_state_stats.iss_tcp_fsm);
2053                         return 0;
2054                 }
2055
2056                 if (softs->ipf_state_logging > 4)
2057                         ipf_state_log(softc, is, ISL_STATECHANGE);
2058
2059                 /*
2060                  * set s0's as appropriate.  Use syn-ack packet as it
2061                  * contains both pieces of required information.
2062                  */
2063                 /*
2064                  * Window scale option is only present in SYN/SYN-ACK packet.
2065                  * Compare with ~TH_FIN to mask out T/TCP setups.
2066                  */
2067                 flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
2068                 if (flags == (TH_SYN|TH_ACK)) {
2069                         is->is_s0[source] = ntohl(tcp->th_ack);
2070                         is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
2071                         if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2072                                 if (ipf_tcpoptions(softs, fin, tcp,
2073                                                    fdata) == -1) {
2074                                         fin->fin_flx |= FI_BAD;
2075                                         DT1(ipf_fi_bad_winscale_syn_ack, fr_info_t *, fin);
2076                                 }
2077                         }
2078                         if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2079                                 ipf_checknewisn(fin, is);
2080                 } else if (flags == TH_SYN) {
2081                         is->is_s0[source] = ntohl(tcp->th_seq) + 1;
2082                         if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2083                                 if (ipf_tcpoptions(softs, fin, tcp,
2084                                                    fdata) == -1) {
2085                                         fin->fin_flx |= FI_BAD;
2086                                         DT1(ipf_fi_bad_winscale_syn, fr_info_t *, fin);
2087                                 }
2088                         }
2089
2090                         if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2091                                 ipf_checknewisn(fin, is);
2092
2093                 }
2094                 ret = 1;
2095         } else {
2096                 DT2(iss_tcp_oow, fr_info_t *, fin, ipstate_t *, is);
2097                 SBUMP(ipf_state_stats.iss_tcp_oow);
2098                 ret = 0;
2099         }
2100         MUTEX_EXIT(&is->is_lock);
2101         return ret;
2102 }
2103
2104
2105 /* ------------------------------------------------------------------------ */
2106 /* Function:    ipf_checknewisn                                             */
2107 /* Returns:     Nil                                                         */
2108 /* Parameters:  fin(I)   - pointer to packet information                    */
2109 /*              is(I)  - pointer to master state structure                  */
2110 /*                                                                          */
2111 /* Check to see if this TCP connection is expecting and needs a new         */
2112 /* sequence number for a particular direction of the connection.            */
2113 /*                                                                          */
2114 /* NOTE: This does not actually change the sequence numbers, only gets new  */
2115 /* one ready.                                                               */
2116 /* ------------------------------------------------------------------------ */
2117 static void
2118 ipf_checknewisn(fin, is)
2119         fr_info_t *fin;
2120         ipstate_t *is;
2121 {
2122         u_32_t sumd, old, new;
2123         tcphdr_t *tcp;
2124         int i;
2125
2126         i = fin->fin_rev;
2127         tcp = fin->fin_dp;
2128
2129         if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
2130             ((i == 1) && !(is->is_flags & IS_ISNACK))) {
2131                 old = ntohl(tcp->th_seq);
2132                 new = ipf_newisn(fin);
2133                 is->is_isninc[i] = new - old;
2134                 CALC_SUMD(old, new, sumd);
2135                 is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
2136
2137                 is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
2138         }
2139 }
2140
2141
2142 /* ------------------------------------------------------------------------ */
2143 /* Function:    ipf_state_tcpinwindow                                       */
2144 /* Returns:     int - 1 == packet inside TCP "window", 0 == not inside.     */
2145 /* Parameters:  fin(I)   - pointer to packet information                    */
2146 /*              fdata(I) - pointer to tcp state informatio (forward)        */
2147 /*              tdata(I) - pointer to tcp state informatio (reverse)        */
2148 /*              tcp(I)   - pointer to TCP packet header                     */
2149 /*                                                                          */
2150 /* Given a packet has matched addresses and ports, check to see if it is    */
2151 /* within the TCP data window.  In a show of generosity, allow packets that */
2152 /* are within the window space behind the current sequence # as well.       */
2153 /* ------------------------------------------------------------------------ */
2154 static int
2155 ipf_state_tcpinwindow(fin, fdata, tdata, tcp, flags)
2156         fr_info_t *fin;
2157         tcpdata_t  *fdata, *tdata;
2158         tcphdr_t *tcp;
2159         int flags;
2160 {
2161         ipf_main_softc_t *softc = fin->fin_main_soft;
2162         ipf_state_softc_t *softs = softc->ipf_state_soft;
2163         tcp_seq seq, ack, end;
2164         int ackskew, tcpflags;
2165         u_32_t win, maxwin;
2166         int dsize, inseq;
2167
2168         /*
2169          * Find difference between last checked packet and this packet.
2170          */
2171         tcpflags = tcp->th_flags;
2172         seq = ntohl(tcp->th_seq);
2173         ack = ntohl(tcp->th_ack);
2174         if (tcpflags & TH_SYN)
2175                 win = ntohs(tcp->th_win);
2176         else
2177                 win = ntohs(tcp->th_win) << fdata->td_winscale;
2178
2179         /*
2180          * A window of 0 produces undesirable behaviour from this function.
2181          */
2182         if (win == 0)
2183                 win = 1;
2184
2185         dsize = fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2186                 ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
2187
2188         /*
2189          * if window scaling is present, the scaling is only allowed
2190          * for windows not in the first SYN packet. In that packet the
2191          * window is 65535 to specify the largest window possible
2192          * for receivers not implementing the window scale option.
2193          * Currently, we do not assume TTCP here. That means that
2194          * if we see a second packet from a host (after the initial
2195          * SYN), we can assume that the receiver of the SYN did
2196          * already send back the SYN/ACK (and thus that we know if
2197          * the receiver also does window scaling)
2198          */
2199         if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
2200                 fdata->td_winflags &= ~TCP_WSCALE_FIRST;
2201                 fdata->td_maxwin = win;
2202         }
2203
2204         end = seq + dsize;
2205
2206         if ((fdata->td_end == 0) &&
2207             (!(flags & IS_TCPFSM) ||
2208              ((tcpflags & TH_OPENING) == TH_OPENING))) {
2209                 /*
2210                  * Must be a (outgoing) SYN-ACK in reply to a SYN.
2211                  */
2212                 fdata->td_end = end - 1;
2213                 fdata->td_maxwin = 1;
2214                 fdata->td_maxend = end + win;
2215         }
2216
2217         if (!(tcpflags & TH_ACK)) {  /* Pretend an ack was sent */
2218                 ack = tdata->td_end;
2219         } else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
2220                    (ack == 0)) {
2221                 /* gross hack to get around certain broken tcp stacks */
2222                 ack = tdata->td_end;
2223         }
2224
2225         maxwin = tdata->td_maxwin;
2226         ackskew = tdata->td_end - ack;
2227
2228         /*
2229          * Strict sequencing only allows in-order delivery.
2230          */
2231         if ((flags & IS_STRICT) != 0) {
2232                 if (seq != fdata->td_end) {
2233                         DT2(iss_tcp_struct, tcpdata_t *, fdata, int, seq);
2234                         SBUMP(ipf_state_stats.iss_tcp_strict);
2235                         fin->fin_flx |= FI_OOW;
2236                         return 0;
2237                 }
2238         }
2239
2240 #define SEQ_GE(a,b)     ((int)((a) - (b)) >= 0)
2241 #define SEQ_GT(a,b)     ((int)((a) - (b)) > 0)
2242         inseq = 0;
2243         if ((SEQ_GE(fdata->td_maxend, end)) &&
2244             (SEQ_GE(seq, fdata->td_end - maxwin)) &&
2245 /* XXX what about big packets */
2246 #define MAXACKWINDOW 66000
2247             (-ackskew <= (MAXACKWINDOW)) &&
2248             ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
2249                 inseq = 1;
2250         /*
2251          * Microsoft Windows will send the next packet to the right of the
2252          * window if SACK is in use.
2253          */
2254         } else if ((seq == fdata->td_maxend) && (ackskew == 0) &&
2255             (fdata->td_winflags & TCP_SACK_PERMIT) &&
2256             (tdata->td_winflags & TCP_SACK_PERMIT)) {
2257                 DT2(iss_sinsack, tcpdata_t *, fdata, int, seq);
2258                 SBUMP(ipf_state_stats.iss_winsack);
2259                 inseq = 1;
2260         /*
2261          * Sometimes a TCP RST will be generated with only the ACK field
2262          * set to non-zero.
2263          */
2264         } else if ((seq == 0) && (tcpflags == (TH_RST|TH_ACK)) &&
2265                    (ackskew >= -1) && (ackskew <= 1)) {
2266                 inseq = 1;
2267         } else if (!(flags & IS_TCPFSM)) {
2268                 int i;
2269
2270                 i = (fin->fin_rev << 1) + fin->fin_out;
2271
2272 #if 0
2273                 if (is_pkts[i]0 == 0) {
2274                         /*
2275                          * Picking up a connection in the middle, the "next"
2276                          * packet seen from a direction that is new should be
2277                          * accepted, even if it appears out of sequence.
2278                          */
2279                         inseq = 1;
2280                 } else
2281 #endif
2282                 if (!(fdata->td_winflags &
2283                             (TCP_WSCALE_SEEN|TCP_WSCALE_FIRST))) {
2284                         /*
2285                          * No TCPFSM and no window scaling, so make some
2286                          * extra guesses.
2287                          */
2288                         if ((seq == fdata->td_maxend) && (ackskew == 0))
2289                                 inseq = 1;
2290                         else if (SEQ_GE(seq + maxwin, fdata->td_end - maxwin))
2291                                 inseq = 1;
2292                 }
2293         }
2294
2295         /* TRACE(inseq, fdata, tdata, seq, end, ack, ackskew, win, maxwin) */
2296
2297         if (inseq) {
2298                 /* if ackskew < 0 then this should be due to fragmented
2299                  * packets. There is no way to know the length of the
2300                  * total packet in advance.
2301                  * We do know the total length from the fragment cache though.
2302                  * Note however that there might be more sessions with
2303                  * exactly the same source and destination parameters in the
2304                  * state cache (and source and destination is the only stuff
2305                  * that is saved in the fragment cache). Note further that
2306                  * some TCP connections in the state cache are hashed with
2307                  * sport and dport as well which makes it not worthwhile to
2308                  * look for them.
2309                  * Thus, when ackskew is negative but still seems to belong
2310                  * to this session, we bump up the destinations end value.
2311                  */
2312                 if (ackskew < 0)
2313                         tdata->td_end = ack;
2314
2315                 /* update max window seen */
2316                 if (fdata->td_maxwin < win)
2317                         fdata->td_maxwin = win;
2318                 if (SEQ_GT(end, fdata->td_end))
2319                         fdata->td_end = end;
2320                 if (SEQ_GE(ack + win, tdata->td_maxend))
2321                         tdata->td_maxend = ack + win;
2322                 return 1;
2323         }
2324         SBUMP(ipf_state_stats.iss_oow);
2325         fin->fin_flx |= FI_OOW;
2326         return 0;
2327 }
2328
2329
2330 /* ------------------------------------------------------------------------ */
2331 /* Function:    ipf_state_clone                                             */
2332 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
2333 /*                           else pointer to new state structure            */
2334 /* Parameters:  fin(I) - pointer to packet information                      */
2335 /*              tcp(I) - pointer to TCP/UDP header                          */
2336 /*              is(I)  - pointer to master state structure                  */
2337 /*                                                                          */
2338 /* Create a "duplcate" state table entry from the master.                   */
2339 /* ------------------------------------------------------------------------ */
2340 static ipstate_t *
2341 ipf_state_clone(fin, tcp, is)
2342         fr_info_t *fin;
2343         tcphdr_t *tcp;
2344         ipstate_t *is;
2345 {
2346         ipf_main_softc_t *softc = fin->fin_main_soft;
2347         ipf_state_softc_t *softs = softc->ipf_state_soft;
2348         ipstate_t *clone;
2349         u_32_t send;
2350
2351         if (softs->ipf_state_stats.iss_active == softs->ipf_state_max) {
2352                 SBUMPD(ipf_state_stats, iss_max);
2353                 softs->ipf_state_doflush = 1;
2354                 return NULL;
2355         }
2356         KMALLOC(clone, ipstate_t *);
2357         if (clone == NULL) {
2358                 SBUMPD(ipf_state_stats, iss_clone_nomem);
2359                 return NULL;
2360         }
2361         bcopy((char *)is, (char *)clone, sizeof(*clone));
2362
2363         MUTEX_NUKE(&clone->is_lock);
2364         /*
2365          * It has not yet been placed on any timeout queue, so make sure
2366          * all of that data is zero'd out.
2367          */
2368         clone->is_sti.tqe_pnext = NULL;
2369         clone->is_sti.tqe_next = NULL;
2370         clone->is_sti.tqe_ifq = NULL;
2371         clone->is_sti.tqe_parent = clone;
2372
2373         clone->is_die = ONE_DAY + softc->ipf_ticks;
2374         clone->is_state[0] = 0;
2375         clone->is_state[1] = 0;
2376         send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2377                 ((tcp->th_flags & TH_SYN) ? 1 : 0) +
2378                 ((tcp->th_flags & TH_FIN) ? 1 : 0);
2379
2380         if (fin->fin_rev == 1) {
2381                 clone->is_dend = send;
2382                 clone->is_maxdend = send;
2383                 clone->is_send = 0;
2384                 clone->is_maxswin = 1;
2385                 clone->is_maxdwin = ntohs(tcp->th_win);
2386                 if (clone->is_maxdwin == 0)
2387                         clone->is_maxdwin = 1;
2388         } else {
2389                 clone->is_send = send;
2390                 clone->is_maxsend = send;
2391                 clone->is_dend = 0;
2392                 clone->is_maxdwin = 1;
2393                 clone->is_maxswin = ntohs(tcp->th_win);
2394                 if (clone->is_maxswin == 0)
2395                         clone->is_maxswin = 1;
2396         }
2397
2398         clone->is_flags &= ~SI_CLONE;
2399         clone->is_flags |= SI_CLONED;
2400         if (ipf_state_insert(softc, clone, fin->fin_rev) == -1) {
2401                 KFREE(clone);
2402                 return NULL;
2403         }
2404
2405         clone->is_ref = 1;
2406         if (clone->is_p == IPPROTO_TCP) {
2407                 (void) ipf_tcp_age(&clone->is_sti, fin, softs->ipf_state_tcptq,
2408                                    clone->is_flags, 2);
2409         }
2410         MUTEX_EXIT(&clone->is_lock);
2411         if (is->is_flags & IS_STATESYNC)
2412                 clone->is_sync = ipf_sync_new(softc, SMC_STATE, fin, clone);
2413         DT2(iss_clone, ipstate_t *, is, ipstate_t *, clone);
2414         SBUMP(ipf_state_stats.iss_cloned);
2415         return clone;
2416 }
2417
2418
2419 /* ------------------------------------------------------------------------ */
2420 /* Function:    ipf_matchsrcdst                                             */
2421 /* Returns:     Nil                                                         */
2422 /* Parameters:  fin(I)   - pointer to packet information                    */
2423 /*              is(I)    - pointer to state structure                       */
2424 /*              src(I)   - pointer to source address                        */
2425 /*              dst(I)   - pointer to destination address                   */
2426 /*              tcp(I)   - pointer to TCP/UDP header                        */
2427 /*              cmask(I) - mask of FI_* bits to check                       */
2428 /*                                                                          */
2429 /* Match a state table entry against an IP packet.  The logic below is that */
2430 /* ret gets set to one if the match succeeds, else remains 0.  If it is     */
2431 /* still 0 after the test. no match.                                        */
2432 /* ------------------------------------------------------------------------ */
2433 static ipstate_t *
2434 ipf_matchsrcdst(fin, is, src, dst, tcp, cmask)
2435         fr_info_t *fin;
2436         ipstate_t *is;
2437         i6addr_t *src, *dst;
2438         tcphdr_t *tcp;
2439         u_32_t cmask;
2440 {
2441         ipf_main_softc_t *softc = fin->fin_main_soft;
2442         ipf_state_softc_t *softs = softc->ipf_state_soft;
2443         int ret = 0, rev, out, flags, flx = 0, idx;
2444         u_short sp, dp;
2445         u_32_t cflx;
2446         void *ifp;
2447
2448         /*
2449          * If a connection is about to be deleted, no packets
2450          * are allowed to match it.
2451          */
2452         if (is->is_sti.tqe_ifq == &softs->ipf_state_deletetq)
2453                 return NULL;
2454
2455         rev = IP6_NEQ(&is->is_dst, dst);
2456         ifp = fin->fin_ifp;
2457         out = fin->fin_out;
2458         flags = is->is_flags;
2459         sp = 0;
2460         dp = 0;
2461
2462         if (tcp != NULL) {
2463                 sp = htons(fin->fin_sport);
2464                 dp = ntohs(fin->fin_dport);
2465         }
2466         if (!rev) {
2467                 if (tcp != NULL) {
2468                         if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
2469                                 rev = 1;
2470                         else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
2471                                 rev = 1;
2472                 }
2473         }
2474
2475         idx = (out << 1) + rev;
2476
2477         /*
2478          * If the interface for this 'direction' is set, make sure it matches.
2479          * An interface name that is not set matches any, as does a name of *.
2480          */
2481         if ((is->is_ifp[idx] == ifp) || (is->is_ifp[idx] == NULL &&
2482             (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '-' ||
2483              *is->is_ifname[idx] == '*')))
2484                 ret = 1;
2485
2486         if (ret == 0) {
2487                 DT2(iss_lookup_badifp, fr_info_t *, fin, ipstate_t *, is);
2488                 SBUMP(ipf_state_stats.iss_lookup_badifp);
2489                 /* TRACE is, out, rev, idx */
2490                 return NULL;
2491         }
2492         ret = 0;
2493
2494         /*
2495          * Match addresses and ports.
2496          */
2497         if (rev == 0) {
2498                 if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
2499                     (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
2500                         if (tcp) {
2501                                 if ((sp == is->is_sport || flags & SI_W_SPORT)
2502                                     &&
2503                                     (dp == is->is_dport || flags & SI_W_DPORT))
2504                                         ret = 1;
2505                         } else {
2506                                 ret = 1;
2507                         }
2508                 }
2509         } else {
2510                 if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
2511                     (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
2512                         if (tcp) {
2513                                 if ((dp == is->is_sport || flags & SI_W_SPORT)
2514                                     &&
2515                                     (sp == is->is_dport || flags & SI_W_DPORT))
2516                                         ret = 1;
2517                         } else {
2518                                 ret = 1;
2519                         }
2520                 }
2521         }
2522
2523         if (ret == 0) {
2524                 SBUMP(ipf_state_stats.iss_lookup_badport);
2525                 DT2(iss_lookup_badport, fr_info_t *, fin, ipstate_t *, is);
2526                 /* TRACE rev, is, sp, dp, src, dst */
2527                 return NULL;
2528         }
2529
2530         /*
2531          * Whether or not this should be here, is questionable, but the aim
2532          * is to get this out of the main line.
2533          */
2534         if (tcp == NULL)
2535                 flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
2536
2537         /*
2538          * Only one of the source or destination address can be flaged as a
2539          * wildcard.  Fill in the missing address, if set.
2540          * For IPv6, if the address being copied in is multicast, then
2541          * don't reset the wild flag - multicast causes it to be set in the
2542          * first place!
2543          */
2544         if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
2545                 fr_ip_t *fi = &fin->fin_fi;
2546
2547                 if ((flags & SI_W_SADDR) != 0) {
2548                         if (rev == 0) {
2549                                 is->is_src = fi->fi_src;
2550                                 is->is_flags &= ~SI_W_SADDR;
2551                         } else {
2552                                 if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2553                                         is->is_src = fi->fi_dst;
2554                                         is->is_flags &= ~SI_W_SADDR;
2555                                 }
2556                         }
2557                 } else if ((flags & SI_W_DADDR) != 0) {
2558                         if (rev == 0) {
2559                                 if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2560                                         is->is_dst = fi->fi_dst;
2561                                         is->is_flags &= ~SI_W_DADDR;
2562                                 }
2563                         } else {
2564                                 is->is_dst = fi->fi_src;
2565                                 is->is_flags &= ~SI_W_DADDR;
2566                         }
2567                 }
2568                 if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
2569                         ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2570                 }
2571         }
2572
2573         flx = fin->fin_flx & cmask;
2574         cflx = is->is_flx[out][rev];
2575
2576         /*
2577          * Match up any flags set from IP options.
2578          */
2579         if ((cflx && (flx != (cflx & cmask))) ||
2580             ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
2581             ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
2582             ((fin->fin_auth & is->is_authmsk) != is->is_auth)) {
2583                 SBUMPD(ipf_state_stats, iss_miss_mask);
2584                 return NULL;
2585         }
2586
2587         if ((fin->fin_flx & FI_IGNORE) != 0) {
2588                 fin->fin_rev = rev;
2589                 return is;
2590         }
2591
2592         /*
2593          * Only one of the source or destination port can be flagged as a
2594          * wildcard.  When filling it in, fill in a copy of the matched entry
2595          * if it has the cloning flag set.
2596          */
2597         if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
2598                 if ((flags & SI_CLONE) != 0) {
2599                         ipstate_t *clone;
2600
2601                         clone = ipf_state_clone(fin, tcp, is);
2602                         if (clone == NULL)
2603                                 return NULL;
2604                         is = clone;
2605                 } else {
2606                         ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2607                 }
2608
2609                 if ((flags & SI_W_SPORT) != 0) {
2610                         if (rev == 0) {
2611                                 is->is_sport = sp;
2612                                 is->is_send = ntohl(tcp->th_seq);
2613                         } else {
2614                                 is->is_sport = dp;
2615                                 is->is_send = ntohl(tcp->th_ack);
2616                         }
2617                         is->is_maxsend = is->is_send + 1;
2618                 } else if ((flags & SI_W_DPORT) != 0) {
2619                         if (rev == 0) {
2620                                 is->is_dport = dp;
2621                                 is->is_dend = ntohl(tcp->th_ack);
2622                         } else {
2623                                 is->is_dport = sp;
2624                                 is->is_dend = ntohl(tcp->th_seq);
2625                         }
2626                         is->is_maxdend = is->is_dend + 1;
2627                 }
2628                 is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
2629                 if ((flags & SI_CLONED) && softs->ipf_state_logging)
2630                         ipf_state_log(softc, is, ISL_CLONE);
2631         }
2632
2633         ret = -1;
2634
2635         if (is->is_flx[out][rev] == 0) {
2636                 is->is_flx[out][rev] = flx;
2637                 if (rev == 1 && is->is_optmsk[1] == 0) {
2638                         is->is_opt[1] = fin->fin_optmsk;
2639                         is->is_optmsk[1] = 0xffffffff;
2640                         if (is->is_v == 6) {
2641                                 is->is_opt[1] &= ~0x8;
2642                                 is->is_optmsk[1] &= ~0x8;
2643                         }
2644                 }
2645         }
2646
2647         /*
2648          * Check if the interface name for this "direction" is set and if not,
2649          * fill it in.
2650          */
2651         if (is->is_ifp[idx] == NULL &&
2652             (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
2653                 is->is_ifp[idx] = ifp;
2654                 COPYIFNAME(fin->fin_v, ifp, is->is_ifname[idx]);
2655         }
2656         fin->fin_rev = rev;
2657         return is;
2658 }
2659
2660
2661 /* ------------------------------------------------------------------------ */
2662 /* Function:    ipf_checkicmpmatchingstate                                  */
2663 /* Returns:     Nil                                                         */
2664 /* Parameters:  fin(I) - pointer to packet information                      */
2665 /*                                                                          */
2666 /* If we've got an ICMP error message, using the information stored in the  */
2667 /* ICMP packet, look for a matching state table entry.                      */
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 static ipstate_t *
2673 ipf_checkicmpmatchingstate(fin)
2674         fr_info_t *fin;
2675 {
2676         ipf_main_softc_t *softc = fin->fin_main_soft;
2677         ipf_state_softc_t *softs = softc->ipf_state_soft;
2678         ipstate_t *is, **isp;
2679         i6addr_t dst, src;
2680         struct icmp *ic;
2681         u_short savelen;
2682         icmphdr_t *icmp;
2683         fr_info_t ofin;
2684         tcphdr_t *tcp;
2685         int type, len;
2686         u_char  pr;
2687         ip_t *oip;
2688         u_int hv;
2689
2690         /*
2691          * Does it at least have the return (basic) IP header ?
2692          * Is it an actual recognised ICMP error type?
2693          * Only a basic IP header (no options) should be with
2694          * an ICMP error header.
2695          */
2696         if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
2697             (fin->fin_plen < ICMPERR_MINPKTLEN) ||
2698             !(fin->fin_flx & FI_ICMPERR)) {
2699                 SBUMPD(ipf_state_stats, iss_icmp_bad);
2700                 return NULL;
2701         }
2702         ic = fin->fin_dp;
2703         type = ic->icmp_type;
2704
2705         oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
2706         /*
2707          * Check if the at least the old IP header (with options) and
2708          * 8 bytes of payload is present.
2709          */
2710         if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2)) {
2711                 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
2712                 return NULL;
2713         }
2714
2715         /*
2716          * Sanity Checks.
2717          */
2718         len = fin->fin_dlen - ICMPERR_ICMPHLEN;
2719         if ((len <= 0) || ((IP_HL(oip) << 2) > len)) {
2720                 DT2(iss_icmp_len, fr_info_t *, fin, struct ip*, oip);
2721                 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
2722                 return NULL;
2723         }
2724
2725         /*
2726          * Is the buffer big enough for all of it ?  It's the size of the IP
2727          * header claimed in the encapsulated part which is of concern.  It
2728          * may be too big to be in this buffer but not so big that it's
2729          * outside the ICMP packet, leading to TCP deref's causing problems.
2730          * This is possible because we don't know how big oip_hl is when we
2731          * do the pullup early in ipf_check() and thus can't guarantee it is
2732          * all here now.
2733          */
2734 #ifdef  _KERNEL
2735         {
2736         mb_t *m;
2737
2738         m = fin->fin_m;
2739 # if defined(MENTAT)
2740         if ((char *)oip + len > (char *)m->b_wptr) {
2741                 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_2);
2742                 return NULL;
2743         }
2744 # else
2745         if ((char *)oip + len > (char *)fin->fin_ip + m->m_len) {
2746                 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_3);
2747                 return NULL;
2748         }
2749 # endif
2750         }
2751 #endif
2752
2753         bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
2754
2755         /*
2756          * in the IPv4 case we must zero the i6addr union otherwise
2757          * the IP6_EQ and IP6_NEQ macros produce the wrong results because
2758          * of the 'junk' in the unused part of the union
2759          */
2760         bzero((char *)&src, sizeof(src));
2761         bzero((char *)&dst, sizeof(dst));
2762
2763         /*
2764          * we make an fin entry to be able to feed it to
2765          * matchsrcdst note that not all fields are encessary
2766          * but this is the cleanest way. Note further we fill
2767          * in fin_mp such that if someone uses it we'll get
2768          * a kernel panic. ipf_matchsrcdst does not use this.
2769          *
2770          * watch out here, as ip is in host order and oip in network
2771          * order. Any change we make must be undone afterwards, like
2772          * oip->ip_len.
2773          */
2774         savelen = oip->ip_len;
2775         oip->ip_len = htons(len);
2776
2777         ofin.fin_flx = FI_NOCKSUM;
2778         ofin.fin_v = 4;
2779         ofin.fin_ip = oip;
2780         ofin.fin_m = NULL;      /* if dereferenced, panic XXX */
2781         ofin.fin_mp = NULL;     /* if dereferenced, panic XXX */
2782         (void) ipf_makefrip(IP_HL(oip) << 2, oip, &ofin);
2783         ofin.fin_ifp = fin->fin_ifp;
2784         ofin.fin_out = !fin->fin_out;
2785
2786         hv = (pr = oip->ip_p);
2787         src.in4 = oip->ip_src;
2788         hv += src.in4.s_addr;
2789         dst.in4 = oip->ip_dst;
2790         hv += dst.in4.s_addr;
2791
2792         /*
2793          * Reset the short and bad flag here because in ipf_matchsrcdst()
2794          * the flags for the current packet (fin_flx) are compared against
2795          * those for the existing session.
2796          */
2797         ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2798
2799         /*
2800          * Put old values of ip_len back as we don't know
2801          * if we have to forward the packet or process it again.
2802          */
2803         oip->ip_len = savelen;
2804
2805         switch (oip->ip_p)
2806         {
2807         case IPPROTO_ICMP :
2808                 /*
2809                  * an ICMP error can only be generated as a result of an
2810                  * ICMP query, not as the response on an ICMP error
2811                  *
2812                  * XXX theoretically ICMP_ECHOREP and the other reply's are
2813                  * ICMP query's as well, but adding them here seems strange XXX
2814                  */
2815                 if ((ofin.fin_flx & FI_ICMPERR) != 0) {
2816                         DT1(iss_icmp_icmperr, fr_info_t *, &ofin);
2817                         SBUMP(ipf_state_stats.iss_icmp_icmperr);
2818                         return NULL;
2819                 }
2820
2821                 /*
2822                  * perform a lookup of the ICMP packet in the state table
2823                  */
2824                 icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2825                 hv += icmp->icmp_id;
2826                 hv = DOUBLE_HASH(hv);
2827
2828                 READ_ENTER(&softc->ipf_state);
2829                 for (isp = &softs->ipf_state_table[hv];
2830                      ((is = *isp) != NULL); ) {
2831                         isp = &is->is_hnext;
2832                         if ((is->is_p != pr) || (is->is_v != 4))
2833                                 continue;
2834                         if (is->is_pass & FR_NOICMPERR)
2835                                 continue;
2836
2837                         is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2838                                             NULL, FI_ICMPCMP);
2839                         if ((is != NULL) && !ipf_allowstateicmp(fin, is, &src))
2840                                 return is;
2841                 }
2842                 RWLOCK_EXIT(&softc->ipf_state);
2843                 SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_1);
2844                 return NULL;
2845         case IPPROTO_TCP :
2846         case IPPROTO_UDP :
2847                 break;
2848         default :
2849                 SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_2);
2850                 return NULL;
2851         }
2852
2853         tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2854
2855         hv += tcp->th_dport;;
2856         hv += tcp->th_sport;;
2857         hv = DOUBLE_HASH(hv);
2858
2859         READ_ENTER(&softc->ipf_state);
2860         for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
2861                 isp = &is->is_hnext;
2862                 /*
2863                  * Only allow this icmp though if the
2864                  * encapsulated packet was allowed through the
2865                  * other way around. Note that the minimal amount
2866                  * of info present does not allow for checking against
2867                  * tcp internals such as seq and ack numbers.   Only the
2868                  * ports are known to be present and can be even if the
2869                  * short flag is set.
2870                  */
2871                 if ((is->is_p == pr) && (is->is_v == 4) &&
2872                     (is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2873                                           tcp, FI_ICMPCMP))) {
2874                         if (ipf_allowstateicmp(fin, is, &src) == 0)
2875                                 return is;
2876                 }
2877         }
2878         RWLOCK_EXIT(&softc->ipf_state);
2879         SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_3);
2880         return NULL;
2881 }
2882
2883
2884 /* ------------------------------------------------------------------------ */
2885 /* Function:    ipf_allowstateicmp                                          */
2886 /* Returns:     int - 1 = packet denied, 0 = packet allowed                 */
2887 /* Parameters:  fin(I) - pointer to packet information                      */
2888 /*              is(I)  - pointer to state table entry                       */
2889 /*              src(I) - source address to check permission for             */
2890 /*                                                                          */
2891 /* For an ICMP packet that has so far matched a state table entry, check if */
2892 /* there are any further refinements that might mean we want to block this  */
2893 /* packet.  This code isn't specific to either IPv4 or IPv6.                */
2894 /* ------------------------------------------------------------------------ */
2895 static int
2896 ipf_allowstateicmp(fin, is, src)
2897         fr_info_t *fin;
2898         ipstate_t *is;
2899         i6addr_t *src;
2900 {
2901         ipf_main_softc_t *softc = fin->fin_main_soft;
2902         ipf_state_softc_t *softs = softc->ipf_state_soft;
2903         frentry_t *savefr;
2904         frentry_t *fr;
2905         u_32_t ipass;
2906         int backward;
2907         int oi;
2908         int i;
2909
2910         fr = is->is_rule;
2911         if (fr != NULL && fr->fr_icmpgrp != NULL) {
2912                 savefr = fin->fin_fr;
2913                 fin->fin_fr = fr->fr_icmpgrp->fg_start;
2914
2915                 ipass = ipf_scanlist(fin, softc->ipf_pass);
2916                 fin->fin_fr = savefr;
2917                 if (FR_ISBLOCK(ipass)) {
2918                         SBUMPD(ipf_state_stats, iss_icmp_headblock);
2919                         return 1;
2920                 }
2921         }
2922
2923         /*
2924          * i  : the index of this packet (the icmp unreachable)
2925          * oi : the index of the original packet found in the
2926          *      icmp header (i.e. the packet causing this icmp)
2927          * backward : original packet was backward compared to
2928          *            the state
2929          */
2930         backward = IP6_NEQ(&is->is_src, src);
2931         fin->fin_rev = !backward;
2932         i = (!backward << 1) + fin->fin_out;
2933         oi = (backward << 1) + !fin->fin_out;
2934
2935         if (is->is_pass & FR_NOICMPERR) {
2936                 SBUMPD(ipf_state_stats, iss_icmp_banned);
2937                 return 1;
2938         }
2939         if (is->is_icmppkts[i] > is->is_pkts[oi]) {
2940                 SBUMPD(ipf_state_stats, iss_icmp_toomany);
2941                 return 1;
2942         }
2943
2944         DT2(iss_icmp_hits, fr_info_t *, fin, ipstate_t *, is);
2945         SBUMP(ipf_state_stats.iss_icmp_hits);
2946         is->is_icmppkts[i]++;
2947
2948         /*
2949          * we deliberately do not touch the timeouts
2950          * for the accompanying state table entry.
2951          * It remains to be seen if that is correct. XXX
2952          */
2953         return 0;
2954 }
2955
2956
2957 /* ------------------------------------------------------------------------ */
2958 /* Function:    ipf_ipsmove                                                 */
2959 /* Returns:     Nil                                                         */
2960 /* Parameters:  is(I) - pointer to state table entry                        */
2961 /*              hv(I) - new hash value for state table entry                */
2962 /* Write Locks: ipf_state                                                   */
2963 /*                                                                          */
2964 /* Move a state entry from one position in the hash table to another.       */
2965 /* ------------------------------------------------------------------------ */
2966 static void
2967 ipf_ipsmove(softs, is, hv)
2968         ipf_state_softc_t *softs;
2969         ipstate_t *is;
2970         u_int hv;
2971 {
2972         ipstate_t **isp;
2973         u_int hvm;
2974
2975         hvm = is->is_hv;
2976
2977         /* TRACE is, is_hv, hvm */
2978
2979         /*
2980          * Remove the hash from the old location...
2981          */
2982         isp = is->is_phnext;
2983         if (is->is_hnext)
2984                 is->is_hnext->is_phnext = isp;
2985         *isp = is->is_hnext;
2986         if (softs->ipf_state_table[hvm] == NULL)
2987                 softs->ipf_state_stats.iss_inuse--;
2988         softs->ipf_state_stats.iss_bucketlen[hvm]--;
2989
2990         /*
2991          * ...and put the hash in the new one.
2992          */
2993         hvm = DOUBLE_HASH(hv);
2994         is->is_hv = hvm;
2995
2996         /* TRACE is, hv, is_hv, hvm */
2997
2998         isp = &softs->ipf_state_table[hvm];
2999         if (*isp)
3000                 (*isp)->is_phnext = &is->is_hnext;
3001         else
3002                 softs->ipf_state_stats.iss_inuse++;
3003         softs->ipf_state_stats.iss_bucketlen[hvm]++;
3004         is->is_phnext = isp;
3005         is->is_hnext = *isp;
3006         *isp = is;
3007 }
3008
3009
3010 /* ------------------------------------------------------------------------ */
3011 /* Function:    ipf_state_lookup                                            */
3012 /* Returns:     ipstate_t* - NULL == no matching state found,               */
3013 /*                           else pointer to state information is returned  */
3014 /* Parameters:  fin(I)  - pointer to packet information                     */
3015 /*              tcp(I)  - pointer to TCP/UDP header.                        */
3016 /*              ifqp(O) - pointer for storing tailq timeout                 */
3017 /*                                                                          */
3018 /* Search the state table for a matching entry to the packet described by   */
3019 /* the contents of *fin. For certain protocols, when a match is found the   */
3020 /* timeout queue is also selected and stored in ifpq if it is non-NULL.     */
3021 /*                                                                          */
3022 /* If we return NULL then no lock on ipf_state is held.                     */
3023 /* If we return non-null then a read-lock on ipf_state is held.             */
3024 /* ------------------------------------------------------------------------ */
3025 ipstate_t *
3026 ipf_state_lookup(fin, tcp, ifqp)
3027         fr_info_t *fin;
3028         tcphdr_t *tcp;
3029         ipftq_t **ifqp;
3030 {
3031         ipf_main_softc_t *softc = fin->fin_main_soft;
3032         ipf_state_softc_t *softs = softc->ipf_state_soft;
3033         u_int hv, hvm, pr, v, tryagain;
3034         ipstate_t *is, **isp;
3035         u_short dport, sport;
3036         i6addr_t src, dst;
3037         struct icmp *ic;
3038         ipftq_t *ifq;
3039         int oow;
3040
3041         is = NULL;
3042         ifq = NULL;
3043         tcp = fin->fin_dp;
3044         ic = (struct icmp *)tcp;
3045         hv = (pr = fin->fin_fi.fi_p);
3046         src = fin->fin_fi.fi_src;
3047         dst = fin->fin_fi.fi_dst;
3048         hv += src.in4.s_addr;
3049         hv += dst.in4.s_addr;
3050
3051         v = fin->fin_fi.fi_v;
3052 #ifdef  USE_INET6
3053         if (v == 6) {
3054                 hv  += fin->fin_fi.fi_src.i6[1];
3055                 hv  += fin->fin_fi.fi_src.i6[2];
3056                 hv  += fin->fin_fi.fi_src.i6[3];
3057
3058                 if ((fin->fin_p == IPPROTO_ICMPV6) &&
3059                     IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
3060                         hv -= dst.in4.s_addr;
3061                 } else {
3062                         hv += fin->fin_fi.fi_dst.i6[1];
3063                         hv += fin->fin_fi.fi_dst.i6[2];
3064                         hv += fin->fin_fi.fi_dst.i6[3];
3065                 }
3066         }
3067 #endif
3068         if ((v == 4) &&
3069             (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
3070                 if (fin->fin_out == 0) {
3071                         hv -= src.in4.s_addr;
3072                 } else {
3073                         hv -= dst.in4.s_addr;
3074                 }
3075         }
3076
3077         /* TRACE fin_saddr, fin_daddr, hv */
3078
3079         /*
3080          * Search the hash table for matching packet header info.
3081          */
3082         switch (pr)
3083         {
3084 #ifdef  USE_INET6
3085         case IPPROTO_ICMPV6 :
3086                 tryagain = 0;
3087                 if (v == 6) {
3088                         if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
3089                             (ic->icmp_type == ICMP6_ECHO_REPLY)) {
3090                                 hv += ic->icmp_id;
3091                         }
3092                 }
3093                 READ_ENTER(&softc->ipf_state);
3094 icmp6again:
3095                 hvm = DOUBLE_HASH(hv);
3096                 for (isp = &softs->ipf_state_table[hvm];
3097                      ((is = *isp) != NULL); ) {
3098                         isp = &is->is_hnext;
3099                         if ((is->is_p != pr) || (is->is_v != v))
3100                                 continue;
3101                         is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3102                         if (is != NULL &&
3103                             ipf_matchicmpqueryreply(v, &is->is_icmp,
3104                                                    ic, fin->fin_rev)) {
3105                                 if (fin->fin_rev)
3106                                         ifq = &softs->ipf_state_icmpacktq;
3107                                 else
3108                                         ifq = &softs->ipf_state_icmptq;
3109                                 break;
3110                         }
3111                 }
3112
3113                 if (is != NULL) {
3114                         if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
3115                                 hv += fin->fin_fi.fi_src.i6[0];
3116                                 hv += fin->fin_fi.fi_src.i6[1];
3117                                 hv += fin->fin_fi.fi_src.i6[2];
3118                                 hv += fin->fin_fi.fi_src.i6[3];
3119                                 ipf_ipsmove(softs, is, hv);
3120                                 MUTEX_DOWNGRADE(&softc->ipf_state);
3121                         }
3122                         break;
3123                 }
3124                 RWLOCK_EXIT(&softc->ipf_state);
3125
3126                 /*
3127                  * No matching icmp state entry. Perhaps this is a
3128                  * response to another state entry.
3129                  *
3130                  * XXX With some ICMP6 packets, the "other" address is already
3131                  * in the packet, after the ICMP6 header, and this could be
3132                  * used in place of the multicast address.  However, taking
3133                  * advantage of this requires some significant code changes
3134                  * to handle the specific types where that is the case.
3135                  */
3136                 if ((softs->ipf_state_stats.iss_wild != 0) &&
3137                     ((fin->fin_flx & FI_NOWILD) == 0) &&
3138                     (v == 6) && (tryagain == 0)) {
3139                         hv -= fin->fin_fi.fi_src.i6[0];
3140                         hv -= fin->fin_fi.fi_src.i6[1];
3141                         hv -= fin->fin_fi.fi_src.i6[2];
3142                         hv -= fin->fin_fi.fi_src.i6[3];
3143                         tryagain = 1;
3144                         WRITE_ENTER(&softc->ipf_state);
3145                         goto icmp6again;
3146                 }
3147
3148                 is = ipf_checkicmp6matchingstate(fin);
3149                 if (is != NULL)
3150                         return is;
3151                 break;
3152 #endif
3153
3154         case IPPROTO_ICMP :
3155                 if (v == 4) {
3156                         hv += ic->icmp_id;
3157                 }
3158                 hv = DOUBLE_HASH(hv);
3159                 READ_ENTER(&softc->ipf_state);
3160                 for (isp = &softs->ipf_state_table[hv];
3161                      ((is = *isp) != NULL); ) {
3162                         isp = &is->is_hnext;
3163                         if ((is->is_p != pr) || (is->is_v != v))
3164                                 continue;
3165                         is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3166                         if ((is != NULL) &&
3167                             (ic->icmp_id == is->is_icmp.ici_id) &&
3168                             ipf_matchicmpqueryreply(v, &is->is_icmp,
3169                                                    ic, fin->fin_rev)) {
3170                                 if (fin->fin_rev)
3171                                         ifq = &softs->ipf_state_icmpacktq;
3172                                 else
3173                                         ifq = &softs->ipf_state_icmptq;
3174                                 break;
3175                         }
3176                 }
3177                 if (is == NULL) {
3178                         RWLOCK_EXIT(&softc->ipf_state);
3179                 }
3180                 break;
3181
3182         case IPPROTO_TCP :
3183         case IPPROTO_UDP :
3184                 ifqp = NULL;
3185                 sport = htons(fin->fin_data[0]);
3186                 hv += sport;
3187                 dport = htons(fin->fin_data[1]);
3188                 hv += dport;
3189                 oow = 0;
3190                 tryagain = 0;
3191                 READ_ENTER(&softc->ipf_state);
3192 retry_tcpudp:
3193                 hvm = DOUBLE_HASH(hv);
3194
3195                 /* TRACE hv, hvm */
3196
3197                 for (isp = &softs->ipf_state_table[hvm];
3198                      ((is = *isp) != NULL); ) {
3199                         isp = &is->is_hnext;
3200                         if ((is->is_p != pr) || (is->is_v != v))
3201                                 continue;
3202                         fin->fin_flx &= ~FI_OOW;
3203                         is = ipf_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
3204                         if (is != NULL) {
3205                                 if (pr == IPPROTO_TCP) {
3206                                         if (!ipf_state_tcp(softc, softs, fin,
3207                                                            tcp, is)) {
3208                                                 oow |= fin->fin_flx & FI_OOW;
3209                                                 continue;
3210                                         }
3211                                 }
3212                                 break;
3213                         }
3214                 }
3215                 if (is != NULL) {
3216                         if (tryagain &&
3217                             !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
3218                                 hv += dport;
3219                                 hv += sport;
3220                                 ipf_ipsmove(softs, is, hv);
3221                                 MUTEX_DOWNGRADE(&softc->ipf_state);
3222                         }
3223                         break;
3224                 }
3225                 RWLOCK_EXIT(&softc->ipf_state);
3226
3227                 if ((softs->ipf_state_stats.iss_wild != 0) &&
3228                     ((fin->fin_flx & FI_NOWILD) == 0)) {
3229                         if (tryagain == 0) {
3230                                 hv -= dport;
3231                                 hv -= sport;
3232                         } else if (tryagain == 1) {
3233                                 hv = fin->fin_fi.fi_p;
3234                                 /*
3235                                  * If we try to pretend this is a reply to a
3236                                  * multicast/broadcast packet then we need to
3237                                  * exclude part of the address from the hash
3238                                  * calculation.
3239                                  */
3240                                 if (fin->fin_out == 0) {
3241                                         hv += src.in4.s_addr;
3242                                 } else {
3243                                         hv += dst.in4.s_addr;
3244                                 }
3245                                 hv += dport;
3246                                 hv += sport;
3247                         }
3248                         tryagain++;
3249                         if (tryagain <= 2) {
3250                                 WRITE_ENTER(&softc->ipf_state);
3251                                 goto retry_tcpudp;
3252                         }
3253                 }
3254                 fin->fin_flx |= oow;
3255                 break;
3256
3257 #if 0
3258         case IPPROTO_GRE :
3259                 gre = fin->fin_dp;
3260                 if (GRE_REV(gre->gr_flags) == 1) {
3261                         hv += gre->gr_call;
3262                 }
3263                 /* FALLTHROUGH */
3264 #endif
3265         default :
3266                 ifqp = NULL;
3267                 hvm = DOUBLE_HASH(hv);
3268                 READ_ENTER(&softc->ipf_state);
3269                 for (isp = &softs->ipf_state_table[hvm];
3270                      ((is = *isp) != NULL); ) {
3271                         isp = &is->is_hnext;
3272                         if ((is->is_p != pr) || (is->is_v != v))
3273                                 continue;
3274                         is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3275                         if (is != NULL) {
3276                                 ifq = &softs->ipf_state_iptq;
3277                                 break;
3278                         }
3279                 }
3280                 if (is == NULL) {
3281                         RWLOCK_EXIT(&softc->ipf_state);
3282                 }
3283                 break;
3284         }
3285
3286         if (is != NULL) {
3287                 if (((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
3288                     (is->is_tqehead[fin->fin_rev] != NULL))
3289                         ifq = is->is_tqehead[fin->fin_rev];
3290                 if (ifq != NULL && ifqp != NULL)
3291                         *ifqp = ifq;
3292         } else {
3293                 SBUMP(ipf_state_stats.iss_lookup_miss);
3294         }
3295         return is;
3296 }
3297
3298
3299 /* ------------------------------------------------------------------------ */
3300 /* Function:    ipf_state_check                                             */
3301 /* Returns:     frentry_t* - NULL == search failed,                         */
3302 /*                           else pointer to rule for matching state        */
3303 /* Parameters:  fin(I)   - pointer to packet information                    */
3304 /*              passp(I) - pointer to filtering result flags                */
3305 /*                                                                          */
3306 /* Check if a packet is associated with an entry in the state table.        */
3307 /* ------------------------------------------------------------------------ */
3308 frentry_t *
3309 ipf_state_check(fin, passp)
3310         fr_info_t *fin;
3311         u_32_t *passp;
3312 {
3313         ipf_main_softc_t *softc = fin->fin_main_soft;
3314         ipf_state_softc_t *softs = softc->ipf_state_soft;
3315         ipftqent_t *tqe;
3316         ipstate_t *is;
3317         frentry_t *fr;
3318         tcphdr_t *tcp;
3319         ipftq_t *ifq;
3320         u_int pass;
3321         int inout;
3322
3323         if (softs->ipf_state_lock || (softs->ipf_state_list == NULL))
3324                 return NULL;
3325
3326         if (fin->fin_flx & (FI_SHORT|FI_FRAGBODY|FI_BAD)) {
3327                 SBUMPD(ipf_state_stats, iss_check_bad);
3328                 return NULL;
3329         }
3330
3331         if ((fin->fin_flx & FI_TCPUDP) ||
3332             (fin->fin_fi.fi_p == IPPROTO_ICMP)
3333 #ifdef  USE_INET6
3334             || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
3335 #endif
3336             )
3337                 tcp = fin->fin_dp;
3338         else
3339                 tcp = NULL;
3340
3341         ifq = NULL;
3342         /*
3343          * Search the hash table for matching packet header info.
3344          */
3345         is = ipf_state_lookup(fin, tcp, &ifq);
3346
3347         switch (fin->fin_p)
3348         {
3349 #ifdef  USE_INET6
3350         case IPPROTO_ICMPV6 :
3351                 if (is != NULL)
3352                         break;
3353                 if (fin->fin_v == 6) {
3354                         is = ipf_checkicmp6matchingstate(fin);
3355                 }
3356                 break;
3357 #endif
3358         case IPPROTO_ICMP :
3359                 if (is != NULL)
3360                         break;
3361                 /*
3362                  * No matching icmp state entry. Perhaps this is a
3363                  * response to another state entry.
3364                  */
3365                 is = ipf_checkicmpmatchingstate(fin);
3366                 break;
3367
3368         case IPPROTO_TCP :
3369                 if (is == NULL)
3370                         break;
3371
3372                 if (is->is_pass & FR_NEWISN) {
3373                         if (fin->fin_out == 0)
3374                                 ipf_fixinisn(fin, is);
3375                         else if (fin->fin_out == 1)
3376                                 ipf_fixoutisn(fin, is);
3377                 }
3378                 break;
3379         default :
3380                 if (fin->fin_rev)
3381                         ifq = &softs->ipf_state_udpacktq;
3382                 else
3383                         ifq = &softs->ipf_state_udptq;
3384                 break;
3385         }
3386         if (is == NULL) {
3387                 SBUMP(ipf_state_stats.iss_check_miss);
3388                 return NULL;
3389         }
3390
3391         fr = is->is_rule;
3392         if (fr != NULL) {
3393                 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
3394                         if (fin->fin_nattag == NULL) {
3395                                 RWLOCK_EXIT(&softc->ipf_state);
3396                                 SBUMPD(ipf_state_stats, iss_check_notag);
3397                                 return NULL;
3398                         }
3399                         if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag)!=0) {
3400                                 RWLOCK_EXIT(&softc->ipf_state);
3401                                 SBUMPD(ipf_state_stats, iss_check_nattag);
3402                                 return NULL;
3403                         }
3404                 }
3405                 (void) strncpy(fin->fin_group, FR_NAME(fr, fr_group),
3406                                FR_GROUPLEN);
3407                 fin->fin_icode = fr->fr_icode;
3408         }
3409
3410         fin->fin_rule = is->is_rulen;
3411         fin->fin_fr = fr;
3412
3413         /*
3414          * If this packet is a fragment and the rule says to track fragments,
3415          * then create a new fragment cache entry.
3416          */
3417         if (fin->fin_flx & FI_FRAG && FR_ISPASS(is->is_pass) &&
3418            is->is_pass & FR_KEEPFRAG)
3419                 (void) ipf_frag_new(softc, fin, is->is_pass);
3420
3421         /*
3422          * For TCP packets, ifq == NULL.  For all others, check if this new
3423          * queue is different to the last one it was on and move it if so.
3424          */
3425         tqe = &is->is_sti;
3426         if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
3427                 ifq = is->is_tqehead[fin->fin_rev];
3428
3429         MUTEX_ENTER(&is->is_lock);
3430
3431         if (ifq != NULL)
3432                 ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq, ifq);
3433
3434         inout = (fin->fin_rev << 1) + fin->fin_out;
3435         is->is_pkts[inout]++;
3436         is->is_bytes[inout] += fin->fin_plen;
3437         fin->fin_pktnum = is->is_pkts[inout] + is->is_icmppkts[inout];
3438
3439         MUTEX_EXIT(&is->is_lock);
3440
3441         pass = is->is_pass;
3442
3443         if (is->is_flags & IS_STATESYNC)
3444                 ipf_sync_update(softc, SMC_STATE, fin, is->is_sync);
3445
3446         RWLOCK_EXIT(&softc->ipf_state);
3447
3448         SBUMP(ipf_state_stats.iss_hits);
3449
3450         fin->fin_dif = &is->is_dif;
3451         fin->fin_tif = &is->is_tifs[fin->fin_rev];
3452         fin->fin_flx |= FI_STATE;
3453         if ((pass & FR_LOGFIRST) != 0)
3454                 pass &= ~(FR_LOGFIRST|FR_LOG);
3455         *passp = pass;
3456         return fr;
3457 }
3458
3459
3460 /* ------------------------------------------------------------------------ */
3461 /* Function:    ipf_fixoutisn                                               */
3462 /* Returns:     Nil                                                         */
3463 /* Parameters:  fin(I) - pointer to packet information                      */
3464 /*              is(I)  - pointer to master state structure                  */
3465 /*                                                                          */
3466 /* Called only for outbound packets, adjusts the sequence number and the    */
3467 /* TCP checksum to match that change.                                       */
3468 /* ------------------------------------------------------------------------ */
3469 static void
3470 ipf_fixoutisn(fin, is)
3471         fr_info_t *fin;
3472         ipstate_t *is;
3473 {
3474         tcphdr_t *tcp;
3475         int rev;
3476         u_32_t seq;
3477
3478         tcp = fin->fin_dp;
3479         rev = fin->fin_rev;
3480         if ((is->is_flags & IS_ISNSYN) != 0) {
3481                 if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3482                         seq = ntohl(tcp->th_seq);
3483                         seq += is->is_isninc[0];
3484                         tcp->th_seq = htonl(seq);
3485                         ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3486                 }
3487         }
3488         if ((is->is_flags & IS_ISNACK) != 0) {
3489                 if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3490                         seq = ntohl(tcp->th_seq);
3491                         seq += is->is_isninc[1];
3492                         tcp->th_seq = htonl(seq);
3493                         ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3494                 }
3495         }
3496 }
3497
3498
3499 /* ------------------------------------------------------------------------ */
3500 /* Function:    ipf_fixinisn                                                */
3501 /* Returns:     Nil                                                         */
3502 /* Parameters:  fin(I)   - pointer to packet information                    */
3503 /*              is(I)  - pointer to master state structure                  */
3504 /*                                                                          */
3505 /* Called only for inbound packets, adjusts the acknowledge number and the  */
3506 /* TCP checksum to match that change.                                       */
3507 /* ------------------------------------------------------------------------ */
3508 static void
3509 ipf_fixinisn(fin, is)
3510         fr_info_t *fin;
3511         ipstate_t *is;
3512 {
3513         tcphdr_t *tcp;
3514         int rev;
3515         u_32_t ack;
3516
3517         tcp = fin->fin_dp;
3518         rev = fin->fin_rev;
3519         if ((is->is_flags & IS_ISNSYN) != 0) {
3520                 if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3521                         ack = ntohl(tcp->th_ack);
3522                         ack -= is->is_isninc[0];
3523                         tcp->th_ack = htonl(ack);
3524                         ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3525                 }
3526         }
3527         if ((is->is_flags & IS_ISNACK) != 0) {
3528                 if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3529                         ack = ntohl(tcp->th_ack);
3530                         ack -= is->is_isninc[1];
3531                         tcp->th_ack = htonl(ack);
3532                         ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3533                 }
3534         }
3535 }
3536
3537
3538 /* ------------------------------------------------------------------------ */
3539 /* Function:    ipf_state_sync                                              */
3540 /* Returns:     Nil                                                         */
3541 /* Parameters:  softc(I) - pointer to soft context main structure           */
3542 /*              ifp(I)   - pointer to interface                             */
3543 /*                                                                          */
3544 /* Walk through all state entries and if an interface pointer match is      */
3545 /* found then look it up again, based on its name in case the pointer has   */
3546 /* changed since last time.                                                 */
3547 /*                                                                          */
3548 /* If ifp is passed in as being non-null then we are only doing updates for */
3549 /* existing, matching, uses of it.                                          */
3550 /* ------------------------------------------------------------------------ */
3551 void
3552 ipf_state_sync(softc, ifp)
3553         ipf_main_softc_t *softc;
3554         void *ifp;
3555 {
3556         ipf_state_softc_t *softs = softc->ipf_state_soft;
3557         ipstate_t *is;
3558         int i;
3559
3560         if (softc->ipf_running <= 0)
3561                 return;
3562
3563         WRITE_ENTER(&softc->ipf_state);
3564
3565         if (softc->ipf_running <= 0) {
3566                 RWLOCK_EXIT(&softc->ipf_state);
3567                 return;
3568         }
3569
3570         for (is = softs->ipf_state_list; is; is = is->is_next) {
3571                 /*
3572                  * Look up all the interface names in the state entry.
3573                  */
3574                 for (i = 0; i < 4; i++) {
3575                         if (ifp == NULL || ifp == is->is_ifp[i])
3576                                 is->is_ifp[i] = ipf_resolvenic(softc,
3577                                                               is->is_ifname[i],
3578                                                               is->is_v);
3579                 }
3580         }
3581         RWLOCK_EXIT(&softc->ipf_state);
3582 }
3583
3584
3585 /* ------------------------------------------------------------------------ */
3586 /* Function:    ipf_state_del                                               */
3587 /* Returns:     int    - 0 = deleted, else refernce count on active struct  */
3588 /* Parameters:  softc(I) - pointer to soft context main structure           */
3589 /*              is(I)  - pointer to state structure to delete               */
3590 /*              why(I) - if not 0, log reason why it was deleted            */
3591 /* Write Locks: ipf_state                                                   */
3592 /*                                                                          */
3593 /* Deletes a state entry from the enumerated list as well as the hash table */
3594 /* and timeout queue lists.  Make adjustments to hash table statistics and  */
3595 /* global counters as required.                                             */
3596 /* ------------------------------------------------------------------------ */
3597 static int
3598 ipf_state_del(softc, is, why)
3599         ipf_main_softc_t *softc;
3600         ipstate_t *is;
3601         int why;
3602 {
3603         ipf_state_softc_t *softs = softc->ipf_state_soft;
3604         int orphan = 1;
3605         frentry_t *fr;
3606
3607         /*
3608          * Since we want to delete this, remove it from the state table,
3609          * where it can be found & used, first.
3610          */
3611         if (is->is_phnext != NULL) {
3612                 *is->is_phnext = is->is_hnext;
3613                 if (is->is_hnext != NULL)
3614                         is->is_hnext->is_phnext = is->is_phnext;
3615                 if (softs->ipf_state_table[is->is_hv] == NULL)
3616                         softs->ipf_state_stats.iss_inuse--;
3617                 softs->ipf_state_stats.iss_bucketlen[is->is_hv]--;
3618
3619                 is->is_phnext = NULL;
3620                 is->is_hnext = NULL;
3621                 orphan = 0;
3622         }
3623
3624         /*
3625          * Because ipf_state_stats.iss_wild is a count of entries in the state
3626          * table that have wildcard flags set, only decerement it once
3627          * and do it here.
3628          */
3629         if (is->is_flags & (SI_WILDP|SI_WILDA)) {
3630                 if (!(is->is_flags & SI_CLONED)) {
3631                         ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
3632                 }
3633                 is->is_flags &= ~(SI_WILDP|SI_WILDA);
3634         }
3635
3636         /*
3637          * Next, remove it from the timeout queue it is in.
3638          */
3639         if (is->is_sti.tqe_ifq != NULL)
3640                 ipf_deletequeueentry(&is->is_sti);
3641
3642         /*
3643          * If it is still in use by something else, do not go any further,
3644          * but note that at this point it is now an orphan.  How can this
3645          * be?  ipf_state_flush() calls ipf_delete() directly because it wants
3646          * to empty the table out and if something has a hold on a state
3647          * entry (such as ipfstat), it'll do the deref path that'll bring
3648          * us back here to do the real delete & free.
3649          */
3650         MUTEX_ENTER(&is->is_lock);
3651         if (is->is_me != NULL) {
3652                 *is->is_me = NULL;
3653                 is->is_me = NULL;
3654                 is->is_ref--;
3655         }
3656         is->is_ref--;
3657         if (is->is_ref > 0) {
3658                 int refs;
3659
3660                 refs = is->is_ref;
3661                 MUTEX_EXIT(&is->is_lock);
3662                 if (!orphan)
3663                         softs->ipf_state_stats.iss_orphan++;
3664                 return refs;
3665         }
3666
3667         fr = is->is_rule;
3668         is->is_rule = NULL;
3669         if (fr != NULL) {
3670                 if (fr->fr_srctrack.ht_max_nodes != 0) {
3671                         (void) ipf_ht_node_del(&fr->fr_srctrack,
3672                                                is->is_family, &is->is_src);
3673                 }
3674         }
3675
3676         ASSERT(is->is_ref == 0);
3677         MUTEX_EXIT(&is->is_lock);
3678
3679         if (is->is_tqehead[0] != NULL) {
3680                 if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
3681                         ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
3682         }
3683         if (is->is_tqehead[1] != NULL) {
3684                 if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
3685                         ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
3686         }
3687
3688         if (is->is_sync)
3689                 ipf_sync_del_state(softc->ipf_sync_soft, is->is_sync);
3690
3691         /*
3692          * Now remove it from the linked list of known states
3693          */
3694         if (is->is_pnext != NULL) {
3695                 *is->is_pnext = is->is_next;
3696
3697                 if (is->is_next != NULL)
3698                         is->is_next->is_pnext = is->is_pnext;
3699
3700                 is->is_pnext = NULL;
3701                 is->is_next = NULL;
3702         }
3703
3704         if (softs->ipf_state_logging != 0 && why != 0)
3705                 ipf_state_log(softc, is, why);
3706
3707         if (is->is_p == IPPROTO_TCP)
3708                 softs->ipf_state_stats.iss_fin++;
3709         else
3710                 softs->ipf_state_stats.iss_expire++;
3711         if (orphan)
3712                 softs->ipf_state_stats.iss_orphan--;
3713
3714         if (fr != NULL) {
3715                 fr->fr_statecnt--;
3716                 (void) ipf_derefrule(softc, &fr);
3717         }
3718
3719         softs->ipf_state_stats.iss_active_proto[is->is_p]--;
3720
3721         MUTEX_DESTROY(&is->is_lock);
3722         KFREE(is);
3723         softs->ipf_state_stats.iss_active--;
3724
3725         return 0;
3726 }
3727
3728
3729 /* ------------------------------------------------------------------------ */
3730 /* Function:    ipf_state_expire                                            */
3731 /* Returns:     Nil                                                         */
3732 /* Parameters:  softc(I) - pointer to soft context main structure           */
3733 /*                                                                          */
3734 /* Slowly expire held state for thingslike UDP and ICMP.  The algorithm     */
3735 /* used here is to keep the queue sorted with the oldest things at the top  */
3736 /* and the youngest at the bottom.  So if the top one doesn't need to be    */
3737 /* expired then neither will any under it.                                  */
3738 /* ------------------------------------------------------------------------ */
3739 void
3740 ipf_state_expire(softc)
3741         ipf_main_softc_t *softc;
3742 {
3743         ipf_state_softc_t *softs = softc->ipf_state_soft;
3744         ipftq_t *ifq, *ifqnext;
3745         ipftqent_t *tqe, *tqn;
3746         ipstate_t *is;
3747         SPL_INT(s);
3748
3749         SPL_NET(s);
3750         WRITE_ENTER(&softc->ipf_state);
3751         for (ifq = softs->ipf_state_tcptq; ifq != NULL; ifq = ifq->ifq_next)
3752                 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3753                         if (tqe->tqe_die > softc->ipf_ticks)
3754                                 break;
3755                         tqn = tqe->tqe_next;
3756                         is = tqe->tqe_parent;
3757                         ipf_state_del(softc, is, ISL_EXPIRE);
3758                 }
3759
3760         for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3761                 ifqnext = ifq->ifq_next;
3762
3763                 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3764                         if (tqe->tqe_die > softc->ipf_ticks)
3765                                 break;
3766                         tqn = tqe->tqe_next;
3767                         is = tqe->tqe_parent;
3768                         ipf_state_del(softc, is, ISL_EXPIRE);
3769                 }
3770         }
3771
3772         for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3773                 ifqnext = ifq->ifq_next;
3774
3775                 if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
3776                     (ifq->ifq_ref == 0)) {
3777                         ipf_freetimeoutqueue(softc, ifq);
3778                 }
3779         }
3780
3781         if (softs->ipf_state_doflush) {
3782                 (void) ipf_state_flush(softc, 2, 0);
3783                 softs->ipf_state_doflush = 0;
3784                 softs->ipf_state_wm_last = softc->ipf_ticks;
3785         }
3786
3787         RWLOCK_EXIT(&softc->ipf_state);
3788         SPL_X(s);
3789 }
3790
3791
3792 /* ------------------------------------------------------------------------ */
3793 /* Function:    ipf_state_flush                                             */
3794 /* Returns:     int - 0 == success, -1 == failure                           */
3795 /* Parameters:  softc(I) - pointer to soft context main structure           */
3796 /*              which(I) - which flush action to perform                    */
3797 /*              proto(I) - which protocol to flush (0 == ALL)               */
3798 /* Write Locks: ipf_state                                                   */
3799 /*                                                                          */
3800 /* Flush state tables.  Three actions currently defined:                    */
3801 /* which == 0 : flush all state table entries                               */
3802 /* which == 1 : flush TCP connections which have started to close but are   */
3803 /*            stuck for some reason.                                        */
3804 /* which == 2 : flush TCP connections which have been idle for a long time, */
3805 /*            starting at > 4 days idle and working back in successive half-*/
3806 /*            days to at most 12 hours old.  If this fails to free enough   */
3807 /*            slots then work backwards in half hour slots to 30 minutes.   */
3808 /*            If that too fails, then work backwards in 30 second intervals */
3809 /*            for the last 30 minutes to at worst 30 seconds idle.          */
3810 /* ------------------------------------------------------------------------ */
3811 int
3812 ipf_state_flush(softc, which, proto)
3813         ipf_main_softc_t *softc;
3814         int which, proto;
3815 {
3816         ipf_state_softc_t *softs = softc->ipf_state_soft;
3817         ipftqent_t *tqe, *tqn;
3818         ipstate_t *is, **isp;
3819         ipftq_t *ifq;
3820         int removed;
3821         SPL_INT(s);
3822
3823         removed = 0;
3824
3825         SPL_NET(s);
3826
3827         switch (which)
3828         {
3829         case 0 :
3830                 SBUMP(ipf_state_stats.iss_flush_all);
3831                 /*
3832                  * Style 0 flush removes everything...
3833                  */
3834                 for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3835                         if ((proto != 0) && (is->is_v != proto)) {
3836                                 isp = &is->is_next;
3837                                 continue;
3838                         }
3839                         if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3840                                 removed++;
3841                         else
3842                                 isp = &is->is_next;
3843                 }
3844                 break;
3845
3846         case 1 :
3847                 SBUMP(ipf_state_stats.iss_flush_closing);
3848                 /*
3849                  * Since we're only interested in things that are closing,
3850                  * we can start with the appropriate timeout queue.
3851                  */
3852                 for (ifq = softs->ipf_state_tcptq + IPF_TCPS_CLOSE_WAIT;
3853                      ifq != NULL; ifq = ifq->ifq_next) {
3854
3855                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3856                                 tqn = tqe->tqe_next;
3857                                 is = tqe->tqe_parent;
3858                                 if (is->is_p != IPPROTO_TCP)
3859                                         break;
3860                                 if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3861                                         removed++;
3862                         }
3863                 }
3864
3865                 /*
3866                  * Also need to look through the user defined queues.
3867                  */
3868                 for (ifq = softs->ipf_state_usertq; ifq != NULL;
3869                      ifq = ifq->ifq_next) {
3870                         for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3871                                 tqn = tqe->tqe_next;
3872                                 is = tqe->tqe_parent;
3873                                 if (is->is_p != IPPROTO_TCP)
3874                                         continue;
3875
3876                                 if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
3877                                     (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
3878                                         if (ipf_state_del(softc, is,
3879                                                           ISL_FLUSH) == 0)
3880                                                 removed++;
3881                                 }
3882                         }
3883                 }
3884                 break;
3885
3886         case 2 :
3887                 break;
3888
3889                 /*
3890                  * Args 5-11 correspond to flushing those particular states
3891                  * for TCP connections.
3892                  */
3893         case IPF_TCPS_CLOSE_WAIT :
3894         case IPF_TCPS_FIN_WAIT_1 :
3895         case IPF_TCPS_CLOSING :
3896         case IPF_TCPS_LAST_ACK :
3897         case IPF_TCPS_FIN_WAIT_2 :
3898         case IPF_TCPS_TIME_WAIT :
3899         case IPF_TCPS_CLOSED :
3900                 SBUMP(ipf_state_stats.iss_flush_queue);
3901                 tqn = softs->ipf_state_tcptq[which].ifq_head;
3902                 while (tqn != NULL) {
3903                         tqe = tqn;
3904                         tqn = tqe->tqe_next;
3905                         is = tqe->tqe_parent;
3906                         if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3907                                 removed++;
3908                 }
3909                 break;
3910
3911         default :
3912                 if (which < 30)
3913                         break;
3914
3915                 SBUMP(ipf_state_stats.iss_flush_state);
3916                 /*
3917                  * Take a large arbitrary number to mean the number of seconds
3918                  * for which which consider to be the maximum value we'll allow
3919                  * the expiration to be.
3920                  */
3921                 which = IPF_TTLVAL(which);
3922                 for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3923                         if ((proto == 0) || (is->is_v == proto)) {
3924                                 if (softc->ipf_ticks - is->is_touched > which) {
3925                                         if (ipf_state_del(softc, is,
3926                                                           ISL_FLUSH) == 0) {
3927                                                 removed++;
3928                                                 continue;
3929                                         }
3930                                 }
3931                         }
3932                         isp = &is->is_next;
3933                 }
3934                 break;
3935         }
3936
3937         if (which != 2) {
3938                 SPL_X(s);
3939                 return removed;
3940         }
3941
3942         SBUMP(ipf_state_stats.iss_flush_timeout);
3943         /*
3944          * Asked to remove inactive entries because the table is full, try
3945          * again, 3 times, if first attempt failed with a different criteria
3946          * each time.  The order tried in must be in decreasing age.
3947          * Another alternative is to implement random drop and drop N entries
3948          * at random until N have been freed up.
3949          */
3950         if (softc->ipf_ticks - softs->ipf_state_wm_last >
3951             softs->ipf_state_wm_freq) {
3952                 removed = ipf_queueflush(softc, ipf_state_flush_entry,
3953                                          softs->ipf_state_tcptq,
3954                                          softs->ipf_state_usertq,
3955                                          &softs->ipf_state_stats.iss_active,
3956                                          softs->ipf_state_size,
3957                                          softs->ipf_state_wm_low);
3958                 softs->ipf_state_wm_last = softc->ipf_ticks;
3959         }
3960
3961         SPL_X(s);
3962         return removed;
3963 }
3964
3965
3966 /* ------------------------------------------------------------------------ */
3967 /* Function:    ipf_state_flush_entry                                       */
3968 /* Returns:     int - 0 = entry deleted, else not deleted                   */
3969 /* Parameters:  softc(I) - pointer to soft context main structure           */
3970 /*              entry(I)  - pointer to state structure to delete            */
3971 /* Write Locks: ipf_state                                                   */
3972 /*                                                                          */
3973 /* This function is a stepping stone between ipf_queueflush() and           */
3974 /* ipf_state_del().  It is used so we can provide a uniform interface via   */
3975 /* the ipf_queueflush() function.                                           */
3976 /* ------------------------------------------------------------------------ */
3977 static int
3978 ipf_state_flush_entry(softc, entry)
3979         ipf_main_softc_t *softc;
3980         void *entry;
3981 {
3982         return ipf_state_del(softc, entry, ISL_FLUSH);
3983 }
3984
3985
3986 /* ------------------------------------------------------------------------ */
3987 /* Function:    ipf_tcp_age                                                 */
3988 /* Returns:     int - 1 == state transition made, 0 == no change (rejected) */
3989 /* Parameters:  tqe(I)   - pointer to timeout queue information             */
3990 /*              fin(I)   - pointer to packet information                    */
3991 /*              tqtab(I) - TCP timeout queue table this is in               */
3992 /*              flags(I) - flags from state/NAT entry                       */
3993 /*              ok(I)    - can we advance state                             */
3994 /*                                                                          */
3995 /* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:          */
3996 /*                                                                          */
3997 /* - (try to) base state transitions on real evidence only,                 */
3998 /*   i.e. packets that are sent and have been received by ipfilter;         */
3999 /*   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.       */
4000 /*                                                                          */
4001 /* - deal with half-closed connections correctly;                           */
4002 /*                                                                          */
4003 /* - store the state of the source in state[0] such that ipfstat            */
4004 /*   displays the state as source/dest instead of dest/source; the calls    */
4005 /*   to ipf_tcp_age have been changed accordingly.                          */
4006 /*                                                                          */
4007 /* Internal Parameters:                                                     */
4008 /*                                                                          */
4009 /*    state[0] = state of source (host that initiated connection)           */
4010 /*    state[1] = state of dest   (host that accepted the connection)        */
4011 /*                                                                          */
4012 /*    dir == 0 : a packet from source to dest                               */
4013 /*    dir == 1 : a packet from dest to source                               */
4014 /*                                                                          */
4015 /* A typical procession for a connection is as follows:                     */
4016 /*                                                                          */
4017 /* +--------------+-------------------+                                     */
4018 /* | Side '0'     | Side '1'          |                                     */
4019 /* +--------------+-------------------+                                     */
4020 /* | 0 -> 1 (SYN) |                   |                                     */
4021 /* |              | 0 -> 2 (SYN-ACK)  |                                     */
4022 /* | 1 -> 3 (ACK) |                   |                                     */
4023 /* |              | 2 -> 4 (ACK-PUSH) |                                     */
4024 /* | 3 -> 4 (ACK) |                   |                                     */
4025 /* |   ...        |   ...             |                                     */
4026 /* |              | 4 -> 6 (FIN-ACK)  |                                     */
4027 /* | 4 -> 5 (ACK) |                   |                                     */
4028 /* |              | 6 -> 6 (ACK-PUSH) |                                     */
4029 /* | 5 -> 5 (ACK) |                   |                                     */
4030 /* | 5 -> 8 (FIN) |                   |                                     */
4031 /* |              | 6 -> 10 (ACK)     |                                     */
4032 /* +--------------+-------------------+                                     */
4033 /*                                                                          */
4034 /* Locking: it is assumed that the parent of the tqe structure is locked.   */
4035 /* ------------------------------------------------------------------------ */
4036 int
4037 ipf_tcp_age(tqe, fin, tqtab, flags, ok)
4038         ipftqent_t *tqe;
4039         fr_info_t *fin;
4040         ipftq_t *tqtab;
4041         int flags, ok;
4042 {
4043         ipf_main_softc_t *softc = fin->fin_main_soft;
4044         int dlen, ostate, nstate, rval, dir;
4045         u_char tcpflags;
4046         tcphdr_t *tcp;
4047
4048         tcp = fin->fin_dp;
4049
4050         rval = 0;
4051         dir = fin->fin_rev;
4052         tcpflags = tcp->th_flags;
4053         dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
4054         ostate = tqe->tqe_state[1 - dir];
4055         nstate = tqe->tqe_state[dir];
4056
4057         if (tcpflags & TH_RST) {
4058                 if (!(tcpflags & TH_PUSH) && !dlen)
4059                         nstate = IPF_TCPS_CLOSED;
4060                 else
4061                         nstate = IPF_TCPS_CLOSE_WAIT;
4062
4063                 if (ostate <= IPF_TCPS_ESTABLISHED) {
4064                         tqe->tqe_state[1 - dir] = IPF_TCPS_CLOSE_WAIT;
4065                 }
4066                 rval = 1;
4067         } else {
4068                 switch (nstate)
4069                 {
4070                 case IPF_TCPS_LISTEN: /* 0 */
4071                         if ((tcpflags & TH_OPENING) == TH_OPENING) {
4072                                 /*
4073                                  * 'dir' received an S and sends SA in
4074                                  * response, LISTEN -> SYN_RECEIVED
4075                                  */
4076                                 nstate = IPF_TCPS_SYN_RECEIVED;
4077                                 rval = 1;
4078                         } else if ((tcpflags & TH_OPENING) == TH_SYN) {
4079                                 /* 'dir' sent S, LISTEN -> SYN_SENT */
4080                                 nstate = IPF_TCPS_SYN_SENT;
4081                                 rval = 1;
4082                         }
4083                         /*
4084                          * the next piece of code makes it possible to get
4085                          * already established connections into the state table
4086                          * after a restart or reload of the filter rules; this
4087                          * does not work when a strict 'flags S keep state' is
4088                          * used for tcp connections of course
4089                          */
4090                         if (((flags & IS_TCPFSM) == 0) &&
4091                             ((tcpflags & TH_ACKMASK) == TH_ACK)) {
4092                                 /*
4093                                  * we saw an A, guess 'dir' is in ESTABLISHED
4094                                  * mode
4095                                  */
4096                                 switch (ostate)
4097                                 {
4098                                 case IPF_TCPS_LISTEN :
4099                                 case IPF_TCPS_SYN_RECEIVED :
4100                                         nstate = IPF_TCPS_HALF_ESTAB;
4101                                         rval = 1;
4102                                         break;
4103                                 case IPF_TCPS_HALF_ESTAB :
4104                                 case IPF_TCPS_ESTABLISHED :
4105                                         nstate = IPF_TCPS_ESTABLISHED;
4106                                         rval = 1;
4107                                         break;
4108                                 default :
4109                                         break;
4110                                 }
4111                         }
4112                         /*
4113                          * TODO: besides regular ACK packets we can have other
4114                          * packets as well; it is yet to be determined how we
4115                          * should initialize the states in those cases
4116                          */
4117                         break;
4118
4119                 case IPF_TCPS_SYN_SENT: /* 1 */
4120                         if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
4121                                 /*
4122                                  * A retransmitted SYN packet.  We do not reset
4123                                  * the timeout here to ipf_tcptimeout because a
4124                                  * connection connect timeout does not renew
4125                                  * after every packet that is sent.  We need to
4126                                  * set rval so as to indicate the packet has
4127                                  * passed the check for its flags being valid
4128                                  * in the TCP FSM.  Setting rval to 2 has the
4129                                  * result of not resetting the timeout.
4130                                  */
4131                                 rval = 2;
4132                         } else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
4133                                    TH_ACK) {
4134                                 /*
4135                                  * we see an A from 'dir' which is in SYN_SENT
4136                                  * state: 'dir' sent an A in response to an SA
4137                                  * which it received, SYN_SENT -> ESTABLISHED
4138                                  */
4139                                 nstate = IPF_TCPS_ESTABLISHED;
4140                                 rval = 1;
4141                         } else if (tcpflags & TH_FIN) {
4142                                 /*
4143                                  * we see an F from 'dir' which is in SYN_SENT
4144                                  * state and wants to close its side of the
4145                                  * connection; SYN_SENT -> FIN_WAIT_1
4146                                  */
4147                                 nstate = IPF_TCPS_FIN_WAIT_1;
4148                                 rval = 1;
4149                         } else if ((tcpflags & TH_OPENING) == TH_OPENING) {
4150                                 /*
4151                                  * we see an SA from 'dir' which is already in
4152                                  * SYN_SENT state, this means we have a
4153                                  * simultaneous open; SYN_SENT -> SYN_RECEIVED
4154                                  */
4155                                 nstate = IPF_TCPS_SYN_RECEIVED;
4156                                 rval = 1;
4157                         }
4158                         break;
4159
4160                 case IPF_TCPS_SYN_RECEIVED: /* 2 */
4161                         if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
4162                                 /*
4163                                  * we see an A from 'dir' which was in
4164                                  * SYN_RECEIVED state so it must now be in
4165                                  * established state, SYN_RECEIVED ->
4166                                  * ESTABLISHED
4167                                  */
4168                                 nstate = IPF_TCPS_ESTABLISHED;
4169                                 rval = 1;
4170                         } else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
4171                                    TH_OPENING) {
4172                                 /*
4173                                  * We see an SA from 'dir' which is already in
4174                                  * SYN_RECEIVED state.
4175                                  */
4176                                 rval = 2;
4177                         } else if (tcpflags & TH_FIN) {
4178                                 /*
4179                                  * we see an F from 'dir' which is in
4180                                  * SYN_RECEIVED state and wants to close its
4181                                  * side of the connection; SYN_RECEIVED ->
4182                                  * FIN_WAIT_1
4183                                  */
4184                                 nstate = IPF_TCPS_FIN_WAIT_1;
4185                                 rval = 1;
4186                         }
4187                         break;
4188
4189                 case IPF_TCPS_HALF_ESTAB: /* 3 */
4190                         if (tcpflags & TH_FIN) {
4191                                 nstate = IPF_TCPS_FIN_WAIT_1;
4192                                 rval = 1;
4193                         } else if ((tcpflags & TH_ACKMASK) == TH_ACK) {
4194                                 /*
4195                                  * If we've picked up a connection in mid
4196                                  * flight, we could be looking at a follow on
4197                                  * packet from the same direction as the one
4198                                  * that created this state.  Recognise it but
4199                                  * do not advance the entire connection's
4200                                  * state.
4201                                  */
4202                                 switch (ostate)
4203                                 {
4204                                 case IPF_TCPS_LISTEN :
4205                                 case IPF_TCPS_SYN_SENT :
4206                                 case IPF_TCPS_SYN_RECEIVED :
4207                                         rval = 1;
4208                                         break;
4209                                 case IPF_TCPS_HALF_ESTAB :
4210                                 case IPF_TCPS_ESTABLISHED :
4211                                         nstate = IPF_TCPS_ESTABLISHED;
4212                                         rval = 1;
4213                                         break;
4214                                 default :
4215                                         break;
4216                                 }
4217                         }
4218                         break;
4219
4220                 case IPF_TCPS_ESTABLISHED: /* 4 */
4221                         rval = 1;
4222                         if (tcpflags & TH_FIN) {
4223                                 /*
4224                                  * 'dir' closed its side of the connection;
4225                                  * this gives us a half-closed connection;
4226                                  * ESTABLISHED -> FIN_WAIT_1
4227                                  */
4228                                 if (ostate == IPF_TCPS_FIN_WAIT_1) {
4229                                         nstate = IPF_TCPS_CLOSING;
4230                                 } else {
4231                                         nstate = IPF_TCPS_FIN_WAIT_1;
4232                                 }
4233                         } else if (tcpflags & TH_ACK) {
4234                                 /*
4235                                  * an ACK, should we exclude other flags here?
4236                                  */
4237                                 if (ostate == IPF_TCPS_FIN_WAIT_1) {
4238                                         /*
4239                                          * We know the other side did an active
4240                                          * close, so we are ACKing the recvd
4241                                          * FIN packet (does the window matching
4242                                          * code guarantee this?) and go into
4243                                          * CLOSE_WAIT state; this gives us a
4244                                          * half-closed connection
4245                                          */
4246                                         nstate = IPF_TCPS_CLOSE_WAIT;
4247                                 } else if (ostate < IPF_TCPS_CLOSE_WAIT) {
4248                                         /*
4249                                          * still a fully established
4250                                          * connection reset timeout
4251                                          */
4252                                         nstate = IPF_TCPS_ESTABLISHED;
4253                                 }
4254                         }
4255                         break;
4256
4257                 case IPF_TCPS_CLOSE_WAIT: /* 5 */
4258                         rval = 1;
4259                         if (tcpflags & TH_FIN) {
4260                                 /*
4261                                  * application closed and 'dir' sent a FIN,
4262                                  * we're now going into LAST_ACK state
4263                                  */
4264                                 nstate = IPF_TCPS_LAST_ACK;
4265                         } else {
4266                                 /*
4267                                  * we remain in CLOSE_WAIT because the other
4268                                  * side has closed already and we did not
4269                                  * close our side yet; reset timeout
4270                                  */
4271                                 nstate = IPF_TCPS_CLOSE_WAIT;
4272                         }
4273                         break;
4274
4275                 case IPF_TCPS_FIN_WAIT_1: /* 6 */
4276                         rval = 1;
4277                         if ((tcpflags & TH_ACK) &&
4278                             ostate > IPF_TCPS_CLOSE_WAIT) {
4279                                 /*
4280                                  * if the other side is not active anymore
4281                                  * it has sent us a FIN packet that we are
4282                                  * ack'ing now with an ACK; this means both
4283                                  * sides have now closed the connection and
4284                                  * we go into TIME_WAIT
4285                                  */
4286                                 /*
4287                                  * XXX: how do we know we really are ACKing
4288                                  * the FIN packet here? does the window code
4289                                  * guarantee that?
4290                                  */
4291                                 nstate = IPF_TCPS_LAST_ACK;
4292                         } else {
4293                                 /*
4294                                  * we closed our side of the connection
4295                                  * already but the other side is still active
4296                                  * (ESTABLISHED/CLOSE_WAIT); continue with
4297                                  * this half-closed connection
4298                                  */
4299                                 nstate = IPF_TCPS_FIN_WAIT_1;
4300                         }
4301                         break;
4302
4303                 case IPF_TCPS_CLOSING: /* 7 */
4304                         if ((tcpflags & (TH_FIN|TH_ACK)) == TH_ACK) {
4305                                 nstate = IPF_TCPS_TIME_WAIT;
4306                         }
4307                         rval = 1;
4308                         break;
4309
4310                 case IPF_TCPS_LAST_ACK: /* 8 */
4311                         if (tcpflags & TH_ACK) {
4312                                 rval = 1;
4313                         }
4314                         /*
4315                          * we cannot detect when we go out of LAST_ACK state
4316                          * to CLOSED because that is based on the reception
4317                          * of ACK packets; ipfilter can only detect that a
4318                          * packet has been sent by a host
4319                          */
4320                         break;
4321
4322                 case IPF_TCPS_FIN_WAIT_2: /* 9 */
4323                         /* NOT USED */
4324                         break;
4325
4326                 case IPF_TCPS_TIME_WAIT: /* 10 */
4327                         /* we're in 2MSL timeout now */
4328                         if (ostate == IPF_TCPS_LAST_ACK) {
4329                                 nstate = IPF_TCPS_CLOSED;
4330                                 rval = 1;
4331                         } else {
4332                                 rval = 2;
4333                         }
4334                         break;
4335
4336                 case IPF_TCPS_CLOSED: /* 11 */
4337                         rval = 2;
4338                         break;
4339
4340                 default :
4341 #if !defined(_KERNEL)
4342                         abort();
4343 #endif
4344                         break;
4345                 }
4346         }
4347
4348         /*
4349          * If rval == 2 then do not update the queue position, but treat the
4350          * packet as being ok.
4351          */
4352         if (rval == 2)
4353                 rval = 1;
4354         else if (rval == 1) {
4355                 if (ok)
4356                         tqe->tqe_state[dir] = nstate;
4357                 if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
4358                         ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq,
4359                                       tqtab + nstate);
4360         }
4361
4362         return rval;
4363 }
4364
4365
4366 /* ------------------------------------------------------------------------ */
4367 /* Function:    ipf_state_log                                               */
4368 /* Returns:     Nil                                                         */
4369 /* Parameters:  softc(I) - pointer to soft context main structure           */
4370 /*              is(I)    - pointer to state structure                       */
4371 /*              type(I)  - type of log entry to create                      */
4372 /*                                                                          */
4373 /* Creates a state table log entry using the state structure and type info. */
4374 /* passed in.  Log packet/byte counts, source/destination address and other */
4375 /* protocol specific information.                                           */
4376 /* ------------------------------------------------------------------------ */
4377 void
4378 ipf_state_log(softc, is, type)
4379         ipf_main_softc_t *softc;
4380         struct ipstate *is;
4381         u_int type;
4382 {
4383 #ifdef  IPFILTER_LOG
4384         struct  ipslog  ipsl;
4385         size_t sizes[1];
4386         void *items[1];
4387         int types[1];
4388
4389         /*
4390          * Copy information out of the ipstate_t structure and into the
4391          * structure used for logging.
4392          */
4393         ipsl.isl_type = type;
4394         ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
4395         ipsl.isl_bytes[0] = is->is_bytes[0];
4396         ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
4397         ipsl.isl_bytes[1] = is->is_bytes[1];
4398         ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
4399         ipsl.isl_bytes[2] = is->is_bytes[2];
4400         ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
4401         ipsl.isl_bytes[3] = is->is_bytes[3];
4402         ipsl.isl_src = is->is_src;
4403         ipsl.isl_dst = is->is_dst;
4404         ipsl.isl_p = is->is_p;
4405         ipsl.isl_v = is->is_v;
4406         ipsl.isl_flags = is->is_flags;
4407         ipsl.isl_tag = is->is_tag;
4408         ipsl.isl_rulen = is->is_rulen;
4409         (void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
4410
4411         if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
4412                 ipsl.isl_sport = is->is_sport;
4413                 ipsl.isl_dport = is->is_dport;
4414                 if (ipsl.isl_p == IPPROTO_TCP) {
4415                         ipsl.isl_state[0] = is->is_state[0];
4416                         ipsl.isl_state[1] = is->is_state[1];
4417                 }
4418         } else if (ipsl.isl_p == IPPROTO_ICMP) {
4419                 ipsl.isl_itype = is->is_icmp.ici_type;
4420         } else if (ipsl.isl_p == IPPROTO_ICMPV6) {
4421                 ipsl.isl_itype = is->is_icmp.ici_type;
4422         } else {
4423                 ipsl.isl_ps.isl_filler[0] = 0;
4424                 ipsl.isl_ps.isl_filler[1] = 0;
4425         }
4426
4427         items[0] = &ipsl;
4428         sizes[0] = sizeof(ipsl);
4429         types[0] = 0;
4430
4431         (void) ipf_log_items(softc, IPL_LOGSTATE, NULL, items, sizes, types, 1);
4432 #endif
4433 }
4434
4435
4436 #ifdef  USE_INET6
4437 /* ------------------------------------------------------------------------ */
4438 /* Function:    ipf_checkicmp6matchingstate                                 */
4439 /* Returns:     ipstate_t* - NULL == no match found,                        */
4440 /*                           else  pointer to matching state entry          */
4441 /* Parameters:  fin(I) - pointer to packet information                      */
4442 /* Locks:       NULL == no locks, else Read Lock on ipf_state               */
4443 /*                                                                          */
4444 /* If we've got an ICMPv6 error message, using the information stored in    */
4445 /* the ICMPv6 packet, look for a matching state table entry.                */
4446 /* ------------------------------------------------------------------------ */
4447 static ipstate_t *
4448 ipf_checkicmp6matchingstate(fin)
4449         fr_info_t *fin;
4450 {
4451         ipf_main_softc_t *softc = fin->fin_main_soft;
4452         ipf_state_softc_t *softs = softc->ipf_state_soft;
4453         struct icmp6_hdr *ic6, *oic;
4454         ipstate_t *is, **isp;
4455         u_short sport, dport;
4456         i6addr_t dst, src;
4457         u_short savelen;
4458         icmpinfo_t *ic;
4459         fr_info_t ofin;
4460         tcphdr_t *tcp;
4461         ip6_t *oip6;
4462         u_char pr;
4463         u_int hv;
4464         int type;
4465
4466         /*
4467          * Does it at least have the return (basic) IP header ?
4468          * Is it an actual recognised ICMP error type?
4469          * Only a basic IP header (no options) should be with
4470          * an ICMP error header.
4471          */
4472         if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
4473             !(fin->fin_flx & FI_ICMPERR)) {
4474                 SBUMPD(ipf_state_stats, iss_icmp_bad);
4475                 return NULL;
4476         }
4477
4478         ic6 = fin->fin_dp;
4479         type = ic6->icmp6_type;
4480
4481         oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
4482         if (fin->fin_plen < sizeof(*oip6)) {
4483                 SBUMPD(ipf_state_stats, iss_icmp_short);
4484                 return NULL;
4485         }
4486
4487         bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
4488         ofin.fin_v = 6;
4489         ofin.fin_ifp = fin->fin_ifp;
4490         ofin.fin_out = !fin->fin_out;
4491         ofin.fin_m = NULL;      /* if dereferenced, panic XXX */
4492         ofin.fin_mp = NULL;     /* if dereferenced, panic XXX */
4493
4494         /*
4495          * We make a fin entry to be able to feed it to
4496          * matchsrcdst. Note that not all fields are necessary
4497          * but this is the cleanest way. Note further we fill
4498          * in fin_mp such that if someone uses it we'll get
4499          * a kernel panic. ipf_matchsrcdst does not use this.
4500          *
4501          * watch out here, as ip is in host order and oip6 in network
4502          * order. Any change we make must be undone afterwards.
4503          */
4504         savelen = oip6->ip6_plen;
4505         oip6->ip6_plen = htons(fin->fin_dlen - ICMPERR_ICMPHLEN);
4506         ofin.fin_flx = FI_NOCKSUM;
4507         ofin.fin_ip = (ip_t *)oip6;
4508         (void) ipf_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
4509         ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
4510         oip6->ip6_plen = savelen;
4511         pr = ofin.fin_p;
4512
4513         /*
4514          * an ICMP error can never generate an ICMP error in response.
4515          */
4516         if (ofin.fin_flx & FI_ICMPERR) {
4517                 DT1(iss_icmp6_icmperr, fr_info_t *, &ofin);
4518                 SBUMP(ipf_state_stats.iss_icmp6_icmperr);
4519                 return NULL;
4520         }
4521
4522         if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
4523                 oic = ofin.fin_dp;
4524                 /*
4525                  * an ICMP error can only be generated as a result of an
4526                  * ICMP query, not as the response on an ICMP error
4527                  *
4528                  * XXX theoretically ICMP_ECHOREP and the other reply's are
4529                  * ICMP query's as well, but adding them here seems strange XXX
4530                  */
4531                  if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK)) {
4532                         DT1(iss_icmp6_notinfo, fr_info_t *, &ofin);
4533                         SBUMP(ipf_state_stats.iss_icmp6_notinfo);
4534                         return NULL;
4535                 }
4536
4537                 /*
4538                  * perform a lookup of the ICMP packet in the state table
4539                  */
4540                 hv = (pr = oip6->ip6_nxt);
4541                 src.in6 = oip6->ip6_src;
4542                 hv += src.in4.s_addr;
4543                 dst.in6 = oip6->ip6_dst;
4544                 hv += dst.in4.s_addr;
4545                 hv += oic->icmp6_id;
4546                 hv += oic->icmp6_seq;
4547                 hv = DOUBLE_HASH(hv);
4548
4549                 READ_ENTER(&softc->ipf_state);
4550                 for (isp = &softs->ipf_state_table[hv];
4551                      ((is = *isp) != NULL); ) {
4552                         ic = &is->is_icmp;
4553                         isp = &is->is_hnext;
4554                         if ((is->is_p == pr) &&
4555                             !(is->is_pass & FR_NOICMPERR) &&
4556                             (oic->icmp6_id == ic->ici_id) &&
4557                             (oic->icmp6_seq == ic->ici_seq) &&
4558                             (is = ipf_matchsrcdst(&ofin, is, &src,
4559                                                  &dst, NULL, FI_ICMPCMP))) {
4560                                 /*
4561                                  * in the state table ICMP query's are stored
4562                                  * with the type of the corresponding ICMP
4563                                  * response. Correct here
4564                                  */
4565                                 if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
4566                                      (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
4567                                      (ic->ici_type - 1 == oic->icmp6_type )) {
4568                                         if (!ipf_allowstateicmp(fin, is, &src))
4569                                                 return is;
4570                                 }
4571                         }
4572                 }
4573                 RWLOCK_EXIT(&softc->ipf_state);
4574                 SBUMPD(ipf_state_stats, iss_icmp6_miss);
4575                 return NULL;
4576         }
4577
4578         hv = (pr = oip6->ip6_nxt);
4579         src.in6 = oip6->ip6_src;
4580         hv += src.i6[0];
4581         hv += src.i6[1];
4582         hv += src.i6[2];
4583         hv += src.i6[3];
4584         dst.in6 = oip6->ip6_dst;
4585         hv += dst.i6[0];
4586         hv += dst.i6[1];
4587         hv += dst.i6[2];
4588         hv += dst.i6[3];
4589
4590         tcp = NULL;
4591
4592         switch (oip6->ip6_nxt)
4593         {
4594         case IPPROTO_TCP :
4595         case IPPROTO_UDP :
4596                 tcp = (tcphdr_t *)(oip6 + 1);
4597                 dport = tcp->th_dport;
4598                 sport = tcp->th_sport;
4599                 hv += dport;
4600                 hv += sport;
4601                 break;
4602
4603         case IPPROTO_ICMPV6 :
4604                 oic = (struct icmp6_hdr *)(oip6 + 1);
4605                 hv += oic->icmp6_id;
4606                 hv += oic->icmp6_seq;
4607                 break;
4608
4609         default :
4610                 break;
4611         }
4612
4613         hv = DOUBLE_HASH(hv);
4614
4615         READ_ENTER(&softc->ipf_state);
4616         for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
4617                 isp = &is->is_hnext;
4618                 /*
4619                  * Only allow this icmp though if the
4620                  * encapsulated packet was allowed through the
4621                  * other way around. Note that the minimal amount
4622                  * of info present does not allow for checking against
4623                  * tcp internals such as seq and ack numbers.
4624                  */
4625                 if ((is->is_p != pr) || (is->is_v != 6) ||
4626                     (is->is_pass & FR_NOICMPERR))
4627                         continue;
4628                 is = ipf_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
4629                 if ((is != NULL) && (ipf_allowstateicmp(fin, is, &src) == 0))
4630                         return is;
4631         }
4632         RWLOCK_EXIT(&softc->ipf_state);
4633         SBUMPD(ipf_state_stats, iss_icmp_miss);
4634         return NULL;
4635 }
4636 #endif
4637
4638
4639 /* ------------------------------------------------------------------------ */
4640 /* Function:    ipf_sttab_init                                              */
4641 /* Returns:     Nil                                                         */
4642 /* Parameters:  softc(I) - pointer to soft context main structure           */
4643 /*              tqp(I)   - pointer to an array of timeout queues for TCP    */
4644 /*                                                                          */
4645 /* Initialise the array of timeout queues for TCP.                          */
4646 /* ------------------------------------------------------------------------ */
4647 void
4648 ipf_sttab_init(softc, tqp)
4649         ipf_main_softc_t *softc;
4650         ipftq_t *tqp;
4651 {
4652         int i;
4653
4654         for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
4655                 IPFTQ_INIT(&tqp[i], 0, "ipftq tcp tab");
4656                 tqp[i].ifq_next = tqp + i + 1;
4657         }
4658         tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
4659         tqp[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcpclosed;
4660         tqp[IPF_TCPS_LISTEN].ifq_ttl = softc->ipf_tcptimeout;
4661         tqp[IPF_TCPS_SYN_SENT].ifq_ttl = softc->ipf_tcpsynsent;
4662         tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = softc->ipf_tcpsynrecv;
4663         tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = softc->ipf_tcpidletimeout;
4664         tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = softc->ipf_tcphalfclosed;
4665         tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = softc->ipf_tcphalfclosed;
4666         tqp[IPF_TCPS_CLOSING].ifq_ttl = softc->ipf_tcptimeout;
4667         tqp[IPF_TCPS_LAST_ACK].ifq_ttl = softc->ipf_tcplastack;
4668         tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = softc->ipf_tcpclosewait;
4669         tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = softc->ipf_tcptimewait;
4670         tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = softc->ipf_tcptimeout;
4671 }
4672
4673
4674 /* ------------------------------------------------------------------------ */
4675 /* Function:    ipf_sttab_destroy                                           */
4676 /* Returns:     Nil                                                         */
4677 /* Parameters:  tqp(I) - pointer to an array of timeout queues for TCP      */
4678 /*                                                                          */
4679 /* Do whatever is necessary to "destroy" each of the entries in the array   */
4680 /* of timeout queues for TCP.                                               */
4681 /* ------------------------------------------------------------------------ */
4682 void
4683 ipf_sttab_destroy(tqp)
4684         ipftq_t *tqp;
4685 {
4686         int i;
4687
4688         for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
4689                 MUTEX_DESTROY(&tqp[i].ifq_lock);
4690 }
4691
4692
4693 /* ------------------------------------------------------------------------ */
4694 /* Function:    ipf_state_deref                                             */
4695 /* Returns:     Nil                                                         */
4696 /* Parameters:  softc(I) - pointer to soft context main structure           */
4697 /*              isp(I) - pointer to pointer to state table entry            */
4698 /*                                                                          */
4699 /* Decrement the reference counter for this state table entry and free it   */
4700 /* if there are no more things using it.                                    */
4701 /*                                                                          */
4702 /* This function is only called when cleaning up after increasing is_ref by */
4703 /* one earlier in the 'code path' so if is_ref is 1 when entering, we do    */
4704 /* have an orphan, otherwise not.  However there is a possible race between */
4705 /* the entry being deleted via flushing with an ioctl call (that calls the  */
4706 /* delete function directly) and the tail end of packet processing so we    */
4707 /* need to grab is_lock before doing the check to synchronise the two code  */
4708 /* paths.                                                                   */
4709 /*                                                                          */
4710 /* When operating in userland (ipftest), we have no timers to clear a state */
4711 /* entry.  Therefore, we make a few simple tests before deleting an entry   */
4712 /* outright.  We compare states on each side looking for a combination of   */
4713 /* TIME_WAIT (should really be FIN_WAIT_2?) and LAST_ACK.  Then we factor   */
4714 /* in packet direction with the interface list to make sure we don't        */
4715 /* prematurely delete an entry on a final inbound packet that's we're also  */
4716 /* supposed to route elsewhere.                                             */
4717 /*                                                                          */
4718 /* Internal parameters:                                                     */
4719 /*    state[0] = state of source (host that initiated connection)           */
4720 /*    state[1] = state of dest   (host that accepted the connection)        */
4721 /*                                                                          */
4722 /*    dir == 0 : a packet from source to dest                               */
4723 /*    dir == 1 : a packet from dest to source                               */
4724 /* ------------------------------------------------------------------------ */
4725 void
4726 ipf_state_deref(softc, isp)
4727         ipf_main_softc_t *softc;
4728         ipstate_t **isp;
4729 {
4730         ipstate_t *is = *isp;
4731
4732         is = *isp;
4733         *isp = NULL;
4734
4735         MUTEX_ENTER(&is->is_lock);
4736         if (is->is_ref > 1) {
4737                 is->is_ref--;
4738                 MUTEX_EXIT(&is->is_lock);
4739 #ifndef _KERNEL
4740                 if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
4741                     (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
4742                         ipf_state_del(softc, is, ISL_EXPIRE);
4743                 }
4744 #endif
4745                 return;
4746         }
4747         MUTEX_EXIT(&is->is_lock);
4748
4749         WRITE_ENTER(&softc->ipf_state);
4750         ipf_state_del(softc, is, ISL_ORPHAN);
4751         RWLOCK_EXIT(&softc->ipf_state);
4752 }
4753
4754
4755 /* ------------------------------------------------------------------------ */
4756 /* Function:    ipf_state_setqueue                                          */
4757 /* Returns:     Nil                                                         */
4758 /* Parameters:  softc(I) - pointer to soft context main structure           */
4759 /*              is(I)    - pointer to state structure                       */
4760 /*              rev(I)   - forward(0) or reverse(1) direction               */
4761 /* Locks:       ipf_state (read or write)                                   */
4762 /*                                                                          */
4763 /* Put the state entry on its default queue entry, using rev as a helped in */
4764 /* determining which queue it should be placed on.                          */
4765 /* ------------------------------------------------------------------------ */
4766 void
4767 ipf_state_setqueue(softc, is, rev)
4768         ipf_main_softc_t *softc;
4769         ipstate_t *is;
4770         int rev;
4771 {
4772         ipf_state_softc_t *softs = softc->ipf_state_soft;
4773         ipftq_t *oifq, *nifq;
4774
4775         if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
4776                 nifq = is->is_tqehead[rev];
4777         else
4778                 nifq = NULL;
4779
4780         if (nifq == NULL) {
4781                 switch (is->is_p)
4782                 {
4783 #ifdef USE_INET6
4784                 case IPPROTO_ICMPV6 :
4785                         if (rev == 1)
4786                                 nifq = &softs->ipf_state_icmpacktq;
4787                         else
4788                                 nifq = &softs->ipf_state_icmptq;
4789                         break;
4790 #endif
4791                 case IPPROTO_ICMP :
4792                         if (rev == 1)
4793                                 nifq = &softs->ipf_state_icmpacktq;
4794                         else
4795                                 nifq = &softs->ipf_state_icmptq;
4796                         break;
4797                 case IPPROTO_TCP :
4798                         nifq = softs->ipf_state_tcptq + is->is_state[rev];
4799                         break;
4800
4801                 case IPPROTO_UDP :
4802                         if (rev == 1)
4803                                 nifq = &softs->ipf_state_udpacktq;
4804                         else
4805                                 nifq = &softs->ipf_state_udptq;
4806                         break;
4807
4808                 default :
4809                         nifq = &softs->ipf_state_iptq;
4810                         break;
4811                 }
4812         }
4813
4814         oifq = is->is_sti.tqe_ifq;
4815         /*
4816          * If it's currently on a timeout queue, move it from one queue to
4817          * another, else put it on the end of the newly determined queue.
4818          */
4819         if (oifq != NULL)
4820                 ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq, nifq);
4821         else
4822                 ipf_queueappend(softc->ipf_ticks, &is->is_sti, nifq, is);
4823         return;
4824 }
4825
4826
4827 /* ------------------------------------------------------------------------ */
4828 /* Function:    ipf_state_iter                                              */
4829 /* Returns:     int - 0 == success, else error                              */
4830 /* Parameters:  softc(I) - pointer to main soft context                     */
4831 /*              token(I) - pointer to ipftoken structure                    */
4832 /*              itp(I)   - pointer to ipfgeniter structure                  */
4833 /*              obj(I)   - pointer to data description structure            */
4834 /*                                                                          */
4835 /* This function handles the SIOCGENITER ioctl for the state tables and     */
4836 /* walks through the list of entries in the state table list (softs->ipf_state_list.)    */
4837 /* ------------------------------------------------------------------------ */
4838 static int
4839 ipf_state_iter(softc, token, itp, obj)
4840         ipf_main_softc_t *softc;
4841         ipftoken_t *token;
4842         ipfgeniter_t *itp;
4843         ipfobj_t *obj;
4844 {
4845         ipf_state_softc_t *softs = softc->ipf_state_soft;
4846         ipstate_t *is, *next, zero;
4847         int error;
4848
4849         if (itp->igi_data == NULL) {
4850                 IPFERROR(100026);
4851                 return EFAULT;
4852         }
4853
4854         if (itp->igi_nitems < 1) {
4855                 IPFERROR(100027);
4856                 return ENOSPC;
4857         }
4858
4859         if (itp->igi_type != IPFGENITER_STATE) {
4860                 IPFERROR(100028);
4861                 return EINVAL;
4862         }
4863
4864         is = token->ipt_data;
4865         if (is == (void *)-1) {
4866                 IPFERROR(100029);
4867                 return ESRCH;
4868         }
4869
4870         error = 0;
4871         obj->ipfo_type = IPFOBJ_IPSTATE;
4872         obj->ipfo_size = sizeof(ipstate_t);
4873
4874         READ_ENTER(&softc->ipf_state);
4875
4876         is = token->ipt_data;
4877         if (is == NULL) {
4878                 next = softs->ipf_state_list;
4879         } else {
4880                 next = is->is_next;
4881         }
4882
4883         /*
4884          * If we find a state entry to use, bump its reference count so that
4885          * it can be used for is_next when we come back.
4886          */
4887         if (next != NULL) {
4888                 MUTEX_ENTER(&next->is_lock);
4889                 next->is_ref++;
4890                 MUTEX_EXIT(&next->is_lock);
4891                 token->ipt_data = next;
4892         } else {
4893                 bzero(&zero, sizeof(zero));
4894                 next = &zero;
4895                 token->ipt_data = NULL;
4896         }
4897         if (next->is_next == NULL)
4898                 ipf_token_mark_complete(token);
4899
4900         RWLOCK_EXIT(&softc->ipf_state);
4901
4902         obj->ipfo_ptr = itp->igi_data;
4903         error = ipf_outobjk(softc, obj, next);
4904         if (is != NULL)
4905                 ipf_state_deref(softc, &is);
4906
4907         return error;
4908 }
4909
4910
4911 /* ------------------------------------------------------------------------ */
4912 /* Function:    ipf_state_gettable                                          */
4913 /* Returns:     int     - 0 = success, else error                           */
4914 /* Parameters:  softc(I) - pointer to main soft context                     */
4915 /*              softs(I) - pointer to state context structure               */
4916 /*              data(I)  - pointer to ioctl data                             */
4917 /*                                                                          */
4918 /* This function handles ioctl requests for tables of state information.    */
4919 /* At present the only table it deals with is the hash bucket statistics.   */
4920 /* ------------------------------------------------------------------------ */
4921 static int
4922 ipf_state_gettable(softc, softs, data)
4923         ipf_main_softc_t *softc;
4924         ipf_state_softc_t *softs;
4925         char *data;
4926 {
4927         ipftable_t table;
4928         int error;
4929
4930         error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
4931         if (error != 0)
4932                 return error;
4933
4934         if (table.ita_type != IPFTABLE_BUCKETS) {
4935                 IPFERROR(100031);
4936                 return EINVAL;
4937         }
4938
4939         error = COPYOUT(softs->ipf_state_stats.iss_bucketlen, table.ita_table,
4940                         softs->ipf_state_size * sizeof(u_int));
4941         if (error != 0) {
4942                 IPFERROR(100032);
4943                 error = EFAULT;
4944         }
4945         return error;
4946 }
4947
4948
4949 /* ------------------------------------------------------------------------ */
4950 /* Function:    ipf_state_setpending                                        */
4951 /* Returns:     Nil                                                         */
4952 /* Parameters:  softc(I) - pointer to main soft context                     */
4953 /*              is(I)    - pointer to state structure                       */
4954 /* Locks:       ipf_state (read or write)                                   */
4955 /*                                                                          */
4956 /* Put the state entry on to the pending queue - this queue has a very      */
4957 /* short lifetime where items are put that can't be deleted straight away   */
4958 /* because of locking issues but we want to delete them ASAP, anyway.       */
4959 /* ------------------------------------------------------------------------ */
4960 void
4961 ipf_state_setpending(softc, is)
4962         ipf_main_softc_t *softc;
4963         ipstate_t *is;
4964 {
4965         ipf_state_softc_t *softs = softc->ipf_state_soft;
4966         ipftq_t *oifq;
4967
4968         oifq = is->is_sti.tqe_ifq;
4969         if (oifq != NULL)
4970                 ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq,
4971                               &softs->ipf_state_pending);
4972         else
4973                 ipf_queueappend(softc->ipf_ticks, &is->is_sti,
4974                                 &softs->ipf_state_pending, is);
4975
4976         MUTEX_ENTER(&is->is_lock);
4977         if (is->is_me != NULL) {
4978                 *is->is_me = NULL;
4979                 is->is_me = NULL;
4980                 is->is_ref--;
4981         }
4982         MUTEX_EXIT(&is->is_lock);
4983 }
4984
4985
4986 /* ------------------------------------------------------------------------ */
4987 /* Function:    ipf_state_matchflush                                        */
4988 /* Returns:     Nil                                                         */
4989 /* Parameters:  softc(I) - pointer to main soft context                     */
4990 /*              data(I)  - pointer to state structure                       */
4991 /* Locks:       ipf_state (read or write)                                   */
4992 /*                                                                          */
4993 /* Flush all entries from the list of state entries that match the          */
4994 /* properties in the array loaded.                                          */
4995 /* ------------------------------------------------------------------------ */
4996 int
4997 ipf_state_matchflush(softc, data)
4998         ipf_main_softc_t *softc;
4999         caddr_t data;
5000 {
5001         ipf_state_softc_t *softs = softc->ipf_state_soft;
5002         int *array, flushed, error;
5003         ipstate_t *state, *statenext;
5004         ipfobj_t obj;
5005
5006         error = ipf_matcharray_load(softc, data, &obj, &array);
5007         if (error != 0)
5008                 return error;
5009
5010         flushed = 0;
5011
5012         for (state = softs->ipf_state_list; state != NULL; state = statenext) {
5013                 statenext = state->is_next;
5014                 if (ipf_state_matcharray(state, array, softc->ipf_ticks) == 0) {
5015                         ipf_state_del(softc, state, ISL_FLUSH);
5016                         flushed++;
5017                 }
5018         }
5019
5020         obj.ipfo_retval = flushed;
5021         error = BCOPYOUT(&obj, data, sizeof(obj));
5022
5023         KFREES(array, array[0] * sizeof(*array));
5024
5025         return error;
5026 }
5027
5028
5029 /* ------------------------------------------------------------------------ */
5030 /* Function:    ipf_state_matcharray                                        */
5031 /* Returns:     int   - 0 = no match, 1 = match                             */
5032 /* Parameters:  state(I) - pointer to state structure                       */
5033 /*              array(I) - pointer to ipf matching expression               */
5034 /*              ticks(I) - current value of ipfilter tick timer             */
5035 /* Locks:       ipf_state (read or write)                                   */
5036 /*                                                                          */
5037 /* Compare a state entry with the match array passed in and return a value  */
5038 /* to indicate whether or not the matching was successful.                  */
5039 /* ------------------------------------------------------------------------ */
5040 static int
5041 ipf_state_matcharray(state, array, ticks)
5042         ipstate_t *state;
5043         int *array;
5044         u_long ticks;
5045 {
5046         int i, n, *x, rv, p;
5047         ipfexp_t *e;
5048
5049         rv = 0;
5050         n = array[0];
5051         x = array + 1;
5052
5053         for (; n > 0; x += 3 + x[3], rv = 0) {
5054                 e = (ipfexp_t *)x;
5055                 n -= e->ipfe_size;
5056                 if (x[0] == IPF_EXP_END)
5057                         break;
5058
5059                 /*
5060                  * If we need to match the protocol and that doesn't match,
5061                  * don't even both with the instruction array.
5062                  */
5063                 p = e->ipfe_cmd >> 16;
5064                 if ((p != 0) && (p != state->is_p))
5065                         break;
5066
5067                 switch (e->ipfe_cmd)
5068                 {
5069                 case IPF_EXP_IP_PR :
5070                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5071                                 rv |= (state->is_p == e->ipfe_arg0[i]);
5072                         }
5073                         break;
5074
5075                 case IPF_EXP_IP_SRCADDR :
5076                         if (state->is_v != 4)
5077                                 break;
5078                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5079                                 rv |= ((state->is_saddr &
5080                                         e->ipfe_arg0[i * 2 + 1]) ==
5081                                       e->ipfe_arg0[i * 2]);
5082                         }
5083                         break;
5084
5085                 case IPF_EXP_IP_DSTADDR :
5086                         if (state->is_v != 4)
5087                                 break;
5088                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5089                                 rv |= ((state->is_daddr &
5090                                         e->ipfe_arg0[i * 2 + 1]) ==
5091                                        e->ipfe_arg0[i * 2]);
5092                         }
5093                         break;
5094
5095                 case IPF_EXP_IP_ADDR :
5096                         if (state->is_v != 4)
5097                                 break;
5098                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5099                                 rv |= ((state->is_saddr &
5100                                         e->ipfe_arg0[i * 2 + 1]) ==
5101                                        e->ipfe_arg0[i * 2]) ||
5102                                        ((state->is_daddr &
5103                                         e->ipfe_arg0[i * 2 + 1]) ==
5104                                        e->ipfe_arg0[i * 2]);
5105                         }
5106                         break;
5107
5108 #ifdef USE_INET6
5109                 case IPF_EXP_IP6_SRCADDR :
5110                         if (state->is_v != 6)
5111                                 break;
5112                         for (i = 0; !rv && i < x[3]; i++) {
5113                                 rv |= IP6_MASKEQ(&state->is_src.in6,
5114                                                  &e->ipfe_arg0[i * 8 + 4],
5115                                                  &e->ipfe_arg0[i * 8]);
5116                         }
5117                         break;
5118
5119                 case IPF_EXP_IP6_DSTADDR :
5120                         if (state->is_v != 6)
5121                                 break;
5122                         for (i = 0; !rv && i < x[3]; i++) {
5123                                 rv |= IP6_MASKEQ(&state->is_dst.in6,
5124                                                  &e->ipfe_arg0[i * 8 + 4],
5125                                                  &e->ipfe_arg0[i * 8]);
5126                         }
5127                         break;
5128
5129                 case IPF_EXP_IP6_ADDR :
5130                         if (state->is_v != 6)
5131                                 break;
5132                         for (i = 0; !rv && i < x[3]; i++) {
5133                                 rv |= IP6_MASKEQ(&state->is_src.in6,
5134                                                  &e->ipfe_arg0[i * 8 + 4],
5135                                                  &e->ipfe_arg0[i * 8]) ||
5136                                       IP6_MASKEQ(&state->is_dst.in6,
5137                                                  &e->ipfe_arg0[i * 8 + 4],
5138                                                  &e->ipfe_arg0[i * 8]);
5139                         }
5140                         break;
5141 #endif
5142
5143                 case IPF_EXP_UDP_PORT :
5144                 case IPF_EXP_TCP_PORT :
5145                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5146                                 rv |= (state->is_sport == e->ipfe_arg0[i]) ||
5147                                       (state->is_dport == e->ipfe_arg0[i]);
5148                         }
5149                         break;
5150
5151                 case IPF_EXP_UDP_SPORT :
5152                 case IPF_EXP_TCP_SPORT :
5153                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5154                                 rv |= (state->is_sport == e->ipfe_arg0[i]);
5155                         }
5156                         break;
5157
5158                 case IPF_EXP_UDP_DPORT :
5159                 case IPF_EXP_TCP_DPORT :
5160                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5161                                 rv |= (state->is_dport == e->ipfe_arg0[i]);
5162                         }
5163                         break;
5164
5165                 case IPF_EXP_TCP_STATE :
5166                         for (i = 0; !rv && i < e->ipfe_narg; i++) {
5167                                 rv |= (state->is_state[0] == e->ipfe_arg0[i]) ||
5168                                       (state->is_state[1] == e->ipfe_arg0[i]);
5169                         }
5170                         break;
5171
5172                 case IPF_EXP_IDLE_GT :
5173                         rv |= (ticks - state->is_touched > e->ipfe_arg0[0]);
5174                         break;
5175                 }
5176
5177                 /*
5178                  * Factor in doing a negative match.
5179                  */
5180                 rv ^= e->ipfe_not;
5181
5182                 if (rv == 0)
5183                         break;
5184         }
5185
5186         return rv;
5187 }
5188
5189
5190 /* ------------------------------------------------------------------------ */
5191 /* Function:    ipf_state_settimeout                                        */
5192 /* Returns:     int 0 = success, else failure                               */
5193 /* Parameters:  softc(I)  - pointer to main soft context                    */
5194 /*              t(I)      - pointer to tuneable being changed               */
5195 /*              p(I)      - pointer to the new value                        */
5196 /*                                                                          */
5197 /* Sets a timeout value for one of the many timeout queues.  We find the    */
5198 /* correct queue using a somewhat manual process of comparing the timeout   */
5199 /* names for each specific value available and calling ipf_apply_timeout on */
5200 /* that queue so that all of the items on it are updated accordingly.       */
5201 /* ------------------------------------------------------------------------ */
5202 int
5203 ipf_state_settimeout(softc, t, p)
5204         struct ipf_main_softc_s *softc;
5205         ipftuneable_t *t;
5206         ipftuneval_t *p;
5207 {
5208         ipf_state_softc_t *softs = softc->ipf_state_soft;
5209
5210         /*
5211          * In case there is nothing to do...
5212          */
5213         if (*t->ipft_pint == p->ipftu_int)
5214                 return 0;
5215
5216         if (!strncmp(t->ipft_name, "tcp_", 4))
5217                 return ipf_settimeout_tcp(t, p, softs->ipf_state_tcptq);
5218
5219         if (!strcmp(t->ipft_name, "udp_timeout")) {
5220                 ipf_apply_timeout(&softs->ipf_state_udptq, p->ipftu_int);
5221         } else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
5222                 ipf_apply_timeout(&softs->ipf_state_udpacktq, p->ipftu_int);
5223         } else if (!strcmp(t->ipft_name, "icmp_timeout")) {
5224                 ipf_apply_timeout(&softs->ipf_state_icmptq, p->ipftu_int);
5225         } else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
5226                 ipf_apply_timeout(&softs->ipf_state_icmpacktq, p->ipftu_int);
5227         } else if (!strcmp(t->ipft_name, "ip_timeout")) {
5228                 ipf_apply_timeout(&softs->ipf_state_iptq, p->ipftu_int);
5229         } else {
5230                 IPFERROR(100034);
5231                 return ESRCH;
5232         }
5233
5234         /*
5235          * Update the tuneable being set.
5236          */
5237         *t->ipft_pint = p->ipftu_int;
5238
5239         return 0;
5240 }
5241
5242
5243 /* ------------------------------------------------------------------------ */
5244 /* Function:    ipf_state_rehash                                            */
5245 /* Returns:     int 0 = success, else failure                               */
5246 /* Parameters:  softc(I)  - pointer to main soft context                    */
5247 /*              t(I)      - pointer to tuneable being changed               */
5248 /*              p(I)      - pointer to the new value                        */
5249 /*                                                                          */
5250 /* To change the size of the state hash table at runtime, a new table has   */
5251 /* to be allocated and then all of the existing entries put in it, bumping  */
5252 /* up the bucketlength for it as we go along.                               */
5253 /* ------------------------------------------------------------------------ */
5254 int
5255 ipf_state_rehash(softc, t, p)
5256         ipf_main_softc_t *softc;
5257         ipftuneable_t *t;
5258         ipftuneval_t *p;
5259 {
5260         ipf_state_softc_t *softs = softc->ipf_state_soft;
5261         ipstate_t **newtab, *is;
5262         u_int *bucketlens;
5263         u_int maxbucket;
5264         u_int newsize;
5265         u_int hv;
5266         int i;
5267
5268         newsize = p->ipftu_int;
5269         /*
5270          * In case there is nothing to do...
5271          */
5272         if (newsize == softs->ipf_state_size)
5273                 return 0;
5274
5275         KMALLOCS(newtab, ipstate_t **, newsize * sizeof(ipstate_t *));
5276         if (newtab == NULL) {
5277                 IPFERROR(100035);
5278                 return ENOMEM;
5279         }
5280
5281         KMALLOCS(bucketlens, u_int *, newsize * sizeof(u_int));
5282         if (bucketlens == NULL) {
5283                 KFREES(newtab, newsize * sizeof(*softs->ipf_state_table));
5284                 IPFERROR(100036);
5285                 return ENOMEM;
5286         }
5287
5288         for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
5289                 maxbucket++;
5290         maxbucket *= 2;
5291
5292         bzero((char *)newtab, newsize * sizeof(ipstate_t *));
5293         bzero((char *)bucketlens, newsize * sizeof(u_int));
5294
5295         WRITE_ENTER(&softc->ipf_state);
5296
5297         if (softs->ipf_state_table != NULL) {
5298                 KFREES(softs->ipf_state_table,
5299                        softs->ipf_state_size * sizeof(*softs->ipf_state_table));
5300         }
5301         softs->ipf_state_table = newtab;
5302
5303         if (softs->ipf_state_stats.iss_bucketlen != NULL) {
5304                 KFREES(softs->ipf_state_stats.iss_bucketlen,
5305                        softs->ipf_state_size * sizeof(u_int));
5306         }
5307         softs->ipf_state_stats.iss_bucketlen = bucketlens;
5308         softs->ipf_state_maxbucket = maxbucket;
5309         softs->ipf_state_size = newsize;
5310
5311         /*
5312          * Walk through the entire list of state table entries and put them
5313          * in the new state table, somewhere.  Because we have a new table,
5314          * we need to restart the counter of how many chains are in use.
5315          */
5316         softs->ipf_state_stats.iss_inuse = 0;
5317         for (is = softs->ipf_state_list; is != NULL; is = is->is_next) {
5318                 is->is_hnext = NULL;
5319                 is->is_phnext = NULL;
5320                 hv = is->is_hv % softs->ipf_state_size;
5321
5322                 if (softs->ipf_state_table[hv] != NULL)
5323                         softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
5324                 else
5325                         softs->ipf_state_stats.iss_inuse++;
5326                 is->is_phnext = softs->ipf_state_table + hv;
5327                 is->is_hnext = softs->ipf_state_table[hv];
5328                 softs->ipf_state_table[hv] = is;
5329                 softs->ipf_state_stats.iss_bucketlen[hv]++;
5330         }
5331         RWLOCK_EXIT(&softc->ipf_state);
5332
5333         return 0;
5334 }
5335
5336
5337 /* ------------------------------------------------------------------------ */
5338 /* Function:    ipf_state_add_tq                                            */
5339 /* Returns:     ipftq_t * - NULL = failure, else pointer to new timeout     */
5340 /*                          queue                                           */
5341 /* Parameters:  softc(I)  - pointer to main soft context                    */
5342 /*              ttl(I)    - pointer to the ttl for the new queue            */
5343 /*                                                                          */
5344 /* Request a pointer to a timeout queue that has a ttl as given by the      */
5345 /* value being passed in.  The timeout queue is added tot the list of those */
5346 /* used internally for stateful filtering.                                  */
5347 /* ------------------------------------------------------------------------ */
5348 ipftq_t *
5349 ipf_state_add_tq(softc, ttl)
5350         ipf_main_softc_t *softc;
5351         int ttl;
5352 {
5353         ipf_state_softc_t *softs = softc->ipf_state_soft;
5354
5355         return ipf_addtimeoutqueue(softc, &softs->ipf_state_usertq, ttl);
5356 }
5357
5358
5359 #ifndef _KERNEL
5360 /*
5361  * Display the built up state table rules and mapping entries.
5362  */
5363 void
5364 ipf_state_dump(softc, arg)
5365         ipf_main_softc_t *softc;
5366         void *arg;
5367 {
5368         ipf_state_softc_t *softs = arg;
5369         ipstate_t *ips;
5370
5371         printf("List of active state sessions:\n");
5372         for (ips = softs->ipf_state_list; ips != NULL; )
5373                 ips = printstate(ips, opts & (OPT_DEBUG|OPT_VERBOSE),
5374                                  softc->ipf_ticks);
5375 }
5376 #endif