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