4 * Copyright (C) 2012 by Darren Reed.
6 * See the IPFILTER.LICENCE file for details on licencing.
8 * Copyright 2008 Sun Microsystems.
12 #if defined(KERNEL) || defined(_KERNEL)
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
22 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
23 (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
24 #include "opt_inet6.h"
26 #if !defined(_KERNEL) && !defined(__KERNEL__)
37 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
38 # include <sys/filio.h>
39 # include <sys/fcntl.h>
41 # include <sys/ioctl.h>
45 # include <sys/protosw.h>
47 #include <sys/socket.h>
49 # include <sys/systm.h>
50 # if !defined(__SVR4) && !defined(__svr4__)
51 # include <sys/mbuf.h>
54 #if defined(__SVR4) || defined(__svr4__)
55 # include <sys/filio.h>
56 # include <sys/byteorder.h>
58 # include <sys/dditypes.h>
60 # include <sys/stream.h>
61 # include <sys/kmem.h>
68 #include <netinet/in.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/ip.h>
71 #include <netinet/tcp.h>
72 #if !defined(__hpux) && !defined(linux)
73 # include <netinet/tcp_fsm.h>
75 #include <netinet/udp.h>
76 #include <netinet/ip_icmp.h>
80 #include "netinet/ip_compat.h"
81 #include "netinet/ip_fil.h"
82 #include "netinet/ip_nat.h"
83 #include "netinet/ip_frag.h"
84 #include "netinet/ip_state.h"
85 #include "netinet/ip_proxy.h"
86 #include "netinet/ip_lookup.h"
87 #include "netinet/ip_dstlist.h"
88 #include "netinet/ip_sync.h"
90 #include <netinet/icmp6.h>
92 #if FREEBSD_GE_REV(300000)
93 # include <sys/malloc.h>
94 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
95 # include <sys/libkern.h>
96 # include <sys/systm.h>
103 static const char sccsid[] = "@(#)ip_state.c 1.8 6/5/96 (C) 1993-2000 Darren Reed";
104 static const char rcsid[] = "@(#)$Id$";
108 static ipftuneable_t ipf_state_tuneables[] = {
109 { { (void *)offsetof(ipf_state_softc_t, ipf_state_max) },
110 "state_max", 1, 0x7fffffff,
111 stsizeof(ipf_state_softc_t, ipf_state_max),
113 { { (void *)offsetof(ipf_state_softc_t, ipf_state_size) },
114 "state_size", 1, 0x7fffffff,
115 stsizeof(ipf_state_softc_t, ipf_state_size),
116 0, NULL, ipf_state_rehash },
117 { { (void *)offsetof(ipf_state_softc_t, ipf_state_lock) },
119 stsizeof(ipf_state_softc_t, ipf_state_lock),
120 IPFT_RDONLY, NULL, NULL },
121 { { (void *)offsetof(ipf_state_softc_t, ipf_state_maxbucket) },
122 "state_maxbucket", 1, 0x7fffffff,
123 stsizeof(ipf_state_softc_t, ipf_state_maxbucket),
125 { { (void *)offsetof(ipf_state_softc_t, ipf_state_logging) },
126 "state_logging",0, 1,
127 stsizeof(ipf_state_softc_t, ipf_state_logging),
129 { { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_high) },
130 "state_wm_high",2, 100,
131 stsizeof(ipf_state_softc_t, ipf_state_wm_high),
133 { { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_low) },
134 "state_wm_low", 1, 99,
135 stsizeof(ipf_state_softc_t, ipf_state_wm_low),
137 { { (void *)offsetof(ipf_state_softc_t, ipf_state_wm_freq) },
138 "state_wm_freq",2, 999999,
139 stsizeof(ipf_state_softc_t, ipf_state_wm_freq),
147 #define SINCL(x) ATOMIC_INCL(softs->x)
148 #define SBUMP(x) (softs->x)++
149 #define SBUMPD(x, y) do { (softs->x.y)++; DT(y); } while (0)
150 #define SBUMPDX(x, y, z)do { (softs->x.y)++; DT(z); } while (0)
153 static ipstate_t *ipf_checkicmp6matchingstate __P((fr_info_t *));
155 static int ipf_allowstateicmp __P((fr_info_t *, ipstate_t *, i6addr_t *));
156 static ipstate_t *ipf_matchsrcdst __P((fr_info_t *, ipstate_t *, i6addr_t *,
157 i6addr_t *, tcphdr_t *, u_32_t));
158 static ipstate_t *ipf_checkicmpmatchingstate __P((fr_info_t *));
159 static int ipf_state_flush_entry __P((ipf_main_softc_t *, void *));
160 static ips_stat_t *ipf_state_stats __P((ipf_main_softc_t *));
161 static int ipf_state_del __P((ipf_main_softc_t *, ipstate_t *, int));
162 static int ipf_state_remove __P((ipf_main_softc_t *, caddr_t));
163 static int ipf_state_match __P((ipstate_t *is1, ipstate_t *is2));
164 static int ipf_state_matchaddresses __P((ipstate_t *is1, ipstate_t *is2));
165 static int ipf_state_matchipv4addrs __P((ipstate_t *is1, ipstate_t *is2));
166 static int ipf_state_matchipv6addrs __P((ipstate_t *is1, ipstate_t *is2));
167 static int ipf_state_matchisps __P((ipstate_t *is1, ipstate_t *is2));
168 static int ipf_state_matchports __P((udpinfo_t *is1, udpinfo_t *is2));
169 static int ipf_state_matcharray __P((ipstate_t *, int *, u_long));
170 static void ipf_ipsmove __P((ipf_state_softc_t *, ipstate_t *, u_int));
171 static int ipf_state_tcp __P((ipf_main_softc_t *, ipf_state_softc_t *,
172 fr_info_t *, tcphdr_t *, ipstate_t *));
173 static int ipf_tcpoptions __P((ipf_state_softc_t *, fr_info_t *,
174 tcphdr_t *, tcpdata_t *));
175 static ipstate_t *ipf_state_clone __P((fr_info_t *, tcphdr_t *, ipstate_t *));
176 static void ipf_fixinisn __P((fr_info_t *, ipstate_t *));
177 static void ipf_fixoutisn __P((fr_info_t *, ipstate_t *));
178 static void ipf_checknewisn __P((fr_info_t *, ipstate_t *));
179 static int ipf_state_iter __P((ipf_main_softc_t *, ipftoken_t *,
180 ipfgeniter_t *, ipfobj_t *));
181 static int ipf_state_gettable __P((ipf_main_softc_t *, ipf_state_softc_t *,
183 static int ipf_state_tcpinwindow __P((struct fr_info *, struct tcpdata *,
184 struct tcpdata *, tcphdr_t *, int));
186 static int ipf_state_getent __P((ipf_main_softc_t *, ipf_state_softc_t *,
188 static int ipf_state_putent __P((ipf_main_softc_t *, ipf_state_softc_t *,
191 #define ONE_DAY IPF_TTLVAL(1 * 86400) /* 1 day */
192 #define FIVE_DAYS (5 * ONE_DAY)
193 #define DOUBLE_HASH(x) (((x) + softs->ipf_state_seed[(x) % \
194 softs->ipf_state_size]) % softs->ipf_state_size)
197 /* ------------------------------------------------------------------------ */
198 /* Function: ipf_state_main_load */
199 /* Returns: int - 0 == success, -1 == failure */
200 /* Parameters: Nil */
202 /* A null-op function that exists as a placeholder so that the flow in */
203 /* other functions is obvious. */
204 /* ------------------------------------------------------------------------ */
206 ipf_state_main_load()
212 /* ------------------------------------------------------------------------ */
213 /* Function: ipf_state_main_unload */
214 /* Returns: int - 0 == success, -1 == failure */
215 /* Parameters: Nil */
217 /* A null-op function that exists as a placeholder so that the flow in */
218 /* other functions is obvious. */
219 /* ------------------------------------------------------------------------ */
221 ipf_state_main_unload()
227 /* ------------------------------------------------------------------------ */
228 /* Function: ipf_state_soft_create */
229 /* Returns: void * - NULL = failure, else pointer to soft context */
230 /* Parameters: softc(I) - pointer to soft context main structure */
232 /* Create a new state soft context structure and populate it with the list */
233 /* of tunables and other default settings. */
234 /* ------------------------------------------------------------------------ */
236 ipf_state_soft_create(softc)
237 ipf_main_softc_t *softc;
239 ipf_state_softc_t *softs;
241 KMALLOC(softs, ipf_state_softc_t *);
245 bzero((char *)softs, sizeof(*softs));
247 softs->ipf_state_tune = ipf_tune_array_copy(softs,
248 sizeof(ipf_state_tuneables),
249 ipf_state_tuneables);
250 if (softs->ipf_state_tune == NULL) {
251 ipf_state_soft_destroy(softc, softs);
254 if (ipf_tune_array_link(softc, softs->ipf_state_tune) == -1) {
255 ipf_state_soft_destroy(softc, softs);
260 softs->ipf_state_logging = 1;
262 softs->ipf_state_logging = 0;
264 softs->ipf_state_size = IPSTATE_SIZE,
265 softs->ipf_state_maxbucket = 0;
266 softs->ipf_state_wm_freq = IPF_TTLVAL(10);
267 softs->ipf_state_max = IPSTATE_MAX;
268 softs->ipf_state_wm_last = 0;
269 softs->ipf_state_wm_high = 99;
270 softs->ipf_state_wm_low = 90;
271 softs->ipf_state_inited = 0;
272 softs->ipf_state_lock = 0;
273 softs->ipf_state_doflush = 0;
279 /* ------------------------------------------------------------------------ */
280 /* Function: ipf_state_soft_destroy */
282 /* Parameters: softc(I) - pointer to soft context main structure */
283 /* arg(I) - pointer to local context to use */
285 /* Undo only what we did in soft create: unlink and free the tunables and */
286 /* free the soft context structure itself. */
287 /* ------------------------------------------------------------------------ */
289 ipf_state_soft_destroy(softc, arg)
290 ipf_main_softc_t *softc;
293 ipf_state_softc_t *softs = arg;
295 if (softs->ipf_state_tune != NULL) {
296 ipf_tune_array_unlink(softc, softs->ipf_state_tune);
297 KFREES(softs->ipf_state_tune, sizeof(ipf_state_tuneables));
298 softs->ipf_state_tune = NULL;
305 /* ------------------------------------------------------------------------ */
306 /* Function: ipf_state_soft_init */
307 /* Returns: int - 0 == success, -1 == failure */
308 /* Parameters: softc(I) - pointer to soft context main structure */
309 /* arg(I) - pointer to local context to use */
311 /* Initialise the state soft context structure so it is ready for use. */
313 /* - allocating a hash table and zero'ing it out */
314 /* - building a secondary table of seeds for double hashing to make it more */
315 /* difficult to attempt to attack the hash table itself (for DoS) */
316 /* - initialise all of the timeout queues, including a table for TCP, some */
317 /* pairs of query/response for UDP and other IP protocols (typically the */
318 /* reply queue has a shorter timeout than the query) */
319 /* ------------------------------------------------------------------------ */
321 ipf_state_soft_init(softc, arg)
322 ipf_main_softc_t *softc;
325 ipf_state_softc_t *softs = arg;
328 KMALLOCS(softs->ipf_state_table,
329 ipstate_t **, softs->ipf_state_size * sizeof(ipstate_t *));
330 if (softs->ipf_state_table == NULL)
333 bzero((char *)softs->ipf_state_table,
334 softs->ipf_state_size * sizeof(ipstate_t *));
336 KMALLOCS(softs->ipf_state_seed, u_long *,
337 softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
338 if (softs->ipf_state_seed == NULL)
341 for (i = 0; i < softs->ipf_state_size; i++) {
343 * XXX - ipf_state_seed[X] should be a random number of sorts.
345 #if FREEBSD_GE_REV(400000)
346 softs->ipf_state_seed[i] = arc4random();
348 softs->ipf_state_seed[i] = ((u_long)softs->ipf_state_seed + i) *
349 softs->ipf_state_size;
350 softs->ipf_state_seed[i] ^= 0xa5a55a5a;
351 softs->ipf_state_seed[i] *= (u_long)softs->ipf_state_seed;
352 softs->ipf_state_seed[i] ^= 0x5a5aa5a5;
353 softs->ipf_state_seed[i] *= softs->ipf_state_max;
357 KMALLOCS(softs->ipf_state_stats.iss_bucketlen, u_int *,
358 softs->ipf_state_size * sizeof(u_int));
359 if (softs->ipf_state_stats.iss_bucketlen == NULL)
362 bzero((char *)softs->ipf_state_stats.iss_bucketlen,
363 softs->ipf_state_size * sizeof(u_int));
365 if (softs->ipf_state_maxbucket == 0) {
366 for (i = softs->ipf_state_size; i > 0; i >>= 1)
367 softs->ipf_state_maxbucket++;
368 softs->ipf_state_maxbucket *= 2;
371 ipf_sttab_init(softc, softs->ipf_state_tcptq);
372 softs->ipf_state_stats.iss_tcptab = softs->ipf_state_tcptq;
373 softs->ipf_state_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
374 &softs->ipf_state_udptq;
376 IPFTQ_INIT(&softs->ipf_state_udptq, softc->ipf_udptimeout,
378 softs->ipf_state_udptq.ifq_next = &softs->ipf_state_udpacktq;
380 IPFTQ_INIT(&softs->ipf_state_udpacktq, softc->ipf_udpacktimeout,
382 softs->ipf_state_udpacktq.ifq_next = &softs->ipf_state_icmptq;
384 IPFTQ_INIT(&softs->ipf_state_icmptq, softc->ipf_icmptimeout,
386 softs->ipf_state_icmptq.ifq_next = &softs->ipf_state_icmpacktq;
388 IPFTQ_INIT(&softs->ipf_state_icmpacktq, softc->ipf_icmpacktimeout,
389 "ipftq icmpack tab");
390 softs->ipf_state_icmpacktq.ifq_next = &softs->ipf_state_iptq;
392 IPFTQ_INIT(&softs->ipf_state_iptq, softc->ipf_iptimeout,
393 "ipftq iptimeout tab");
394 softs->ipf_state_iptq.ifq_next = &softs->ipf_state_pending;
396 IPFTQ_INIT(&softs->ipf_state_pending, IPF_HZ_DIVIDE, "ipftq pending");
397 softs->ipf_state_pending.ifq_next = &softs->ipf_state_deletetq;
399 IPFTQ_INIT(&softs->ipf_state_deletetq, 1, "ipftq delete");
400 softs->ipf_state_deletetq.ifq_next = NULL;
402 MUTEX_INIT(&softs->ipf_stinsert, "ipf state insert mutex");
405 softs->ipf_state_wm_last = softc->ipf_ticks;
406 softs->ipf_state_inited = 1;
412 /* ------------------------------------------------------------------------ */
413 /* Function: ipf_state_soft_fini */
414 /* Returns: int - 0 = success, -1 = failure */
415 /* Parameters: softc(I) - pointer to soft context main structure */
416 /* arg(I) - pointer to local context to use */
418 /* Release and destroy any resources acquired or initialised so that */
419 /* IPFilter can be unloaded or re-initialised. */
420 /* ------------------------------------------------------------------------ */
422 ipf_state_soft_fini(softc, arg)
423 ipf_main_softc_t *softc;
426 ipf_state_softc_t *softs = arg;
427 ipftq_t *ifq, *ifqnext;
430 while ((is = softs->ipf_state_list) != NULL)
431 ipf_state_del(softc, is, ISL_UNLOAD);
434 * Proxy timeout queues are not cleaned here because although they
435 * exist on the state list, appr_unload is called after
436 * ipf_state_unload and the proxies actually are responsible for them
437 * being created. Should the proxy timeouts have their own list?
438 * There's no real justification as this is the only complication.
440 for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
441 ifqnext = ifq->ifq_next;
443 if (ipf_deletetimeoutqueue(ifq) == 0)
444 ipf_freetimeoutqueue(softc, ifq);
447 softs->ipf_state_stats.iss_inuse = 0;
448 softs->ipf_state_stats.iss_active = 0;
450 if (softs->ipf_state_inited == 1) {
451 softs->ipf_state_inited = 0;
452 ipf_sttab_destroy(softs->ipf_state_tcptq);
453 MUTEX_DESTROY(&softs->ipf_state_udptq.ifq_lock);
454 MUTEX_DESTROY(&softs->ipf_state_icmptq.ifq_lock);
455 MUTEX_DESTROY(&softs->ipf_state_udpacktq.ifq_lock);
456 MUTEX_DESTROY(&softs->ipf_state_icmpacktq.ifq_lock);
457 MUTEX_DESTROY(&softs->ipf_state_iptq.ifq_lock);
458 MUTEX_DESTROY(&softs->ipf_state_deletetq.ifq_lock);
459 MUTEX_DESTROY(&softs->ipf_state_pending.ifq_lock);
460 MUTEX_DESTROY(&softs->ipf_stinsert);
463 if (softs->ipf_state_table != NULL) {
464 KFREES(softs->ipf_state_table,
465 softs->ipf_state_size * sizeof(*softs->ipf_state_table));
466 softs->ipf_state_table = NULL;
469 if (softs->ipf_state_seed != NULL) {
470 KFREES(softs->ipf_state_seed,
471 softs->ipf_state_size * sizeof(*softs->ipf_state_seed));
472 softs->ipf_state_seed = NULL;
475 if (softs->ipf_state_stats.iss_bucketlen != NULL) {
476 KFREES(softs->ipf_state_stats.iss_bucketlen,
477 softs->ipf_state_size * sizeof(u_int));
478 softs->ipf_state_stats.iss_bucketlen = NULL;
485 /* ------------------------------------------------------------------------ */
486 /* Function: ipf_state_set_lock */
488 /* Parameters: arg(I) - pointer to local context to use */
489 /* tmp(I) - new value for lock */
491 /* Stub function that allows for external manipulation of ipf_state_lock */
492 /* ------------------------------------------------------------------------ */
494 ipf_state_setlock(arg, tmp)
498 ipf_state_softc_t *softs = arg;
500 softs->ipf_state_lock = tmp;
504 /* ------------------------------------------------------------------------ */
505 /* Function: ipf_state_stats */
506 /* Returns: ips_state_t* - pointer to state stats structure */
507 /* Parameters: softc(I) - pointer to soft context main structure */
509 /* Put all the current numbers and pointers into a single struct and return */
510 /* a pointer to it. */
511 /* ------------------------------------------------------------------------ */
513 ipf_state_stats(softc)
514 ipf_main_softc_t *softc;
516 ipf_state_softc_t *softs = softc->ipf_state_soft;
517 ips_stat_t *issp = &softs->ipf_state_stats;
519 issp->iss_state_size = softs->ipf_state_size;
520 issp->iss_state_max = softs->ipf_state_max;
521 issp->iss_table = softs->ipf_state_table;
522 issp->iss_list = softs->ipf_state_list;
523 issp->iss_ticks = softc->ipf_ticks;
525 #ifdef IPFILTER_LOGGING
526 issp->iss_log_ok = ipf_log_logok(softc, IPF_LOGSTATE);
527 issp->iss_log_fail = ipf_log_failures(softc, IPF_LOGSTATE);
529 issp->iss_log_ok = 0;
530 issp->iss_log_fail = 0;
535 /* ------------------------------------------------------------------------ */
536 /* Function: ipf_state_remove */
537 /* Returns: int - 0 == success, != 0 == failure */
538 /* Parameters: softc(I) - pointer to soft context main structure */
539 /* data(I) - pointer to state structure to delete from table */
541 /* Search for a state structure that matches the one passed, according to */
542 /* the IP addresses and other protocol specific information. */
543 /* ------------------------------------------------------------------------ */
545 ipf_state_remove(softc, data)
546 ipf_main_softc_t *softc;
549 ipf_state_softc_t *softs = softc->ipf_state_soft;
554 error = ipf_inobj(softc, data, NULL, &st, IPFOBJ_IPSTATE);
558 WRITE_ENTER(&softc->ipf_state);
559 for (sp = softs->ipf_state_list; sp; sp = sp->is_next)
560 if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
561 !bcmp((caddr_t)&sp->is_src, (caddr_t)&st.is_src,
562 sizeof(st.is_src)) &&
563 !bcmp((caddr_t)&sp->is_dst, (caddr_t)&st.is_dst,
564 sizeof(st.is_dst)) &&
565 !bcmp((caddr_t)&sp->is_ps, (caddr_t)&st.is_ps,
567 ipf_state_del(softc, sp, ISL_REMOVE);
568 RWLOCK_EXIT(&softc->ipf_state);
571 RWLOCK_EXIT(&softc->ipf_state);
578 /* ------------------------------------------------------------------------ */
579 /* Function: ipf_state_ioctl */
580 /* Returns: int - 0 == success, != 0 == failure */
581 /* Parameters: softc(I) - pointer to soft context main structure */
582 /* data(I) - pointer to ioctl data */
583 /* cmd(I) - ioctl command integer */
584 /* mode(I) - file mode bits used with open */
585 /* uid(I) - uid of process making the ioctl call */
586 /* ctx(I) - pointer specific to context of the call */
588 /* Processes an ioctl call made to operate on the IP Filter state device. */
589 /* ------------------------------------------------------------------------ */
591 ipf_state_ioctl(softc, data, cmd, mode, uid, ctx)
592 ipf_main_softc_t *softc;
598 ipf_state_softc_t *softs = softc->ipf_state_soft;
599 int arg, ret, error = 0;
605 * Delete an entry from the state table.
608 error = ipf_state_remove(softc, data);
612 * Flush the state table
615 error = BCOPYIN(data, &arg, sizeof(arg));
621 WRITE_ENTER(&softc->ipf_state);
622 ret = ipf_state_flush(softc, arg, 4);
623 RWLOCK_EXIT(&softc->ipf_state);
625 error = BCOPYOUT(&ret, data, sizeof(ret));
635 error = BCOPYIN(data, &arg, sizeof(arg));
641 WRITE_ENTER(&softc->ipf_state);
642 ret = ipf_state_flush(softc, arg, 6);
643 RWLOCK_EXIT(&softc->ipf_state);
645 error = BCOPYOUT(&ret, data, sizeof(ret));
654 case SIOCMATCHFLUSH :
655 WRITE_ENTER(&softc->ipf_state);
656 error = ipf_state_matchflush(softc, data);
657 RWLOCK_EXIT(&softc->ipf_state);
662 * Flush the state log.
665 if (!(mode & FWRITE)) {
671 tmp = ipf_log_clear(softc, IPL_LOGSTATE);
672 error = BCOPYOUT(&tmp, data, sizeof(tmp));
681 * Turn logging of state information on/off.
684 if (!(mode & FWRITE)) {
688 error = BCOPYIN(data, &softs->ipf_state_logging,
689 sizeof(softs->ipf_state_logging));
698 * Return the current state of logging.
701 error = BCOPYOUT(&softs->ipf_state_logging, data,
702 sizeof(softs->ipf_state_logging));
710 * Return the number of bytes currently waiting to be read.
713 arg = ipf_log_bytesused(softc, IPL_LOGSTATE);
714 error = BCOPYOUT(&arg, data, sizeof(arg));
723 * Get the current state statistics.
726 error = ipf_outobj(softc, data, ipf_state_stats(softc),
731 * Lock/Unlock the state table. (Locking prevents any changes, which
732 * means no packets match).
735 if (!(mode & FWRITE)) {
739 error = ipf_lock(data, &softs->ipf_state_lock);
744 * Add an entry to the current state table.
747 if (!softs->ipf_state_lock || !(mode &FWRITE)) {
752 error = ipf_state_putent(softc, softs, data);
756 * Get a state table entry.
759 if (!softs->ipf_state_lock) {
764 error = ipf_state_getent(softc, softs, data);
768 * Return a copy of the hash table bucket lengths
771 error = BCOPYOUT(softs->ipf_state_stats.iss_bucketlen, data,
772 softs->ipf_state_size * sizeof(u_int));
785 error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
790 token = ipf_token_find(softc, IPFGENITER_STATE, uid, ctx);
792 error = ipf_state_iter(softc, token, &iter, &obj);
793 WRITE_ENTER(&softc->ipf_tokens);
794 ipf_token_deref(softc, token);
795 RWLOCK_EXIT(&softc->ipf_tokens);
805 error = ipf_state_gettable(softc, softs, data);
809 error = BCOPYIN(data, &arg, sizeof(arg));
815 error = ipf_token_del(softc, arg, uid, ctx);
821 error = ipf_outobj(softc, data, softs->ipf_state_tcptq,
834 /* ------------------------------------------------------------------------ */
835 /* Function: ipf_state_getent */
836 /* Returns: int - 0 == success, != 0 == failure */
837 /* Parameters: softc(I) - pointer to soft context main structure */
838 /* softs(I) - pointer to state context structure */
839 /* data(I) - pointer to state structure to retrieve from table*/
841 /* Copy out state information from the kernel to a user space process. If */
842 /* there is a filter rule associated with the state entry, copy that out */
843 /* as well. The entry to copy out is taken from the value of "ips_next" in */
844 /* the struct passed in and if not null and not found in the list of current*/
845 /* state entries, the retrieval fails. */
846 /* ------------------------------------------------------------------------ */
848 ipf_state_getent(softc, softs, data)
849 ipf_main_softc_t *softc;
850 ipf_state_softc_t *softs;
857 error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
861 READ_ENTER(&softc->ipf_state);
864 isn = softs->ipf_state_list;
866 if (ips.ips_next == NULL) {
867 RWLOCK_EXIT(&softc->ipf_state);
875 * Make sure the pointer we're copying from exists in the
876 * current list of entries. Security precaution to prevent
877 * copying of random kernel data.
879 for (is = softs->ipf_state_list; is; is = is->is_next)
883 RWLOCK_EXIT(&softc->ipf_state);
888 ips.ips_next = isn->is_next;
889 bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
890 ips.ips_rule = isn->is_rule;
891 if (isn->is_rule != NULL)
892 bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
894 RWLOCK_EXIT(&softc->ipf_state);
895 error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
900 /* ------------------------------------------------------------------------ */
901 /* Function: ipf_state_putent */
902 /* Returns: int - 0 == success, != 0 == failure */
903 /* Parameters: softc(I) - pointer to soft context main structure */
904 /* softs(I) - pointer to state context structure */
905 /* data(I) - pointer to state information struct */
907 /* This function implements the SIOCSTPUT ioctl: insert a state entry into */
908 /* the state table. If the state info. includes a pointer to a filter rule */
909 /* then also add in an orphaned rule (will not show up in any "ipfstat -io" */
911 /* ------------------------------------------------------------------------ */
913 ipf_state_putent(softc, softs, data)
914 ipf_main_softc_t *softc;
915 ipf_state_softc_t *softs;
924 error = ipf_inobj(softc, data, NULL, &ips, IPFOBJ_STATESAVE);
928 KMALLOC(isn, ipstate_t *);
934 bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
935 bzero((char *)isn, offsetof(struct ipstate, is_pkts));
936 isn->is_sti.tqe_pnext = NULL;
937 isn->is_sti.tqe_next = NULL;
938 isn->is_sti.tqe_ifq = NULL;
939 isn->is_sti.tqe_parent = isn;
940 isn->is_ifp[0] = NULL;
941 isn->is_ifp[1] = NULL;
942 isn->is_ifp[2] = NULL;
943 isn->is_ifp[3] = NULL;
950 READ_ENTER(&softc->ipf_state);
951 inserr = ipf_state_insert(softc, isn, 0);
952 MUTEX_EXIT(&isn->is_lock);
953 RWLOCK_EXIT(&softc->ipf_state);
958 if (isn->is_flags & SI_NEWFR) {
959 KMALLOC(fr, frentry_t *);
965 bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
966 out = fr->fr_flags & FR_OUTQUE ? 1 : 0;
968 ips.ips_is.is_rule = fr;
969 MUTEX_NUKE(&fr->fr_lock);
970 MUTEX_INIT(&fr->fr_lock, "state filter rule lock");
973 * Look up all the interface names in the rule.
975 for (i = 0; i < 4; i++) {
976 if (fr->fr_ifnames[i] == -1) {
977 fr->fr_ifas[i] = NULL;
980 name = fr->fr_names + fr->fr_ifnames[i];
981 fr->fr_ifas[i] = ipf_resolvenic(softc, name,
985 for (i = 0; i < 4; i++) {
986 name = isn->is_ifname[i];
987 isn->is_ifp[i] = ipf_resolvenic(softc, name,
994 fr->fr_type = FR_T_NONE;
996 (void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[0],
998 (void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_tifs[1],
1000 (void) ipf_resolvedest(softc, fr->fr_names, &fr->fr_dif,
1004 * send a copy back to userland of what we ended up
1005 * to allow for verification.
1007 error = ipf_outobj(softc, data, &ips, IPFOBJ_STATESAVE);
1010 MUTEX_DESTROY(&fr->fr_lock);
1015 READ_ENTER(&softc->ipf_state);
1016 error = ipf_state_insert(softc, isn, 0);
1017 MUTEX_EXIT(&isn->is_lock);
1018 RWLOCK_EXIT(&softc->ipf_state);
1021 READ_ENTER(&softc->ipf_state);
1022 for (is = softs->ipf_state_list; is; is = is->is_next)
1023 if (is->is_rule == fr) {
1024 error = ipf_state_insert(softc, isn, 0);
1025 MUTEX_EXIT(&isn->is_lock);
1033 RWLOCK_EXIT(&softc->ipf_state);
1045 /* ------------------------------------------------------------------------ */
1046 /* Function: ipf_state_insert */
1047 /* Returns: int - 0 == success, -1 == failure */
1048 /* Parameters: softc(I) - pointer to soft context main structure */
1049 /* Parameters: is(I) - pointer to state structure */
1050 /* rev(I) - flag indicating direction of packet */
1052 /* Inserts a state structure into the hash table (for lookups) and the list */
1053 /* of state entries (for enumeration). Resolves all of the interface names */
1054 /* to pointers and adjusts running stats for the hash table as appropriate. */
1056 /* This function can fail if the filter rule has had a population policy of */
1057 /* IP addresses used with stateful filteirng assigned to it. */
1059 /* Locking: it is assumed that some kind of lock on ipf_state is held. */
1060 /* Exits with is_lock initialised and held - *EVEN IF ERROR*. */
1061 /* ------------------------------------------------------------------------ */
1063 ipf_state_insert(softc, is, rev)
1064 ipf_main_softc_t *softc;
1068 ipf_state_softc_t *softs = softc->ipf_state_soft;
1074 * Look up all the interface names in the state entry.
1076 for (i = 0; i < 4; i++) {
1077 if (is->is_ifp[i] != NULL)
1079 is->is_ifp[i] = ipf_resolvenic(softc, is->is_ifname[i],
1084 * If we could trust is_hv, then the modulous would not be needed,
1085 * but when running with IPFILTER_SYNC, this stops bad values.
1087 hv = is->is_hv % softs->ipf_state_size;
1092 * We need to get both of these locks...the first because it is
1093 * possible that once the insert is complete another packet might
1094 * come along, match the entry and want to update it.
1096 MUTEX_INIT(&is->is_lock, "ipf state entry");
1097 MUTEX_ENTER(&is->is_lock);
1098 MUTEX_ENTER(&softs->ipf_stinsert);
1102 if ((fr->fr_srctrack.ht_max_nodes != 0) &&
1103 (ipf_ht_node_add(softc, &fr->fr_srctrack,
1104 is->is_family, &is->is_src) == -1)) {
1105 SBUMPD(ipf_state_stats, iss_max_track);
1106 MUTEX_EXIT(&softs->ipf_stinsert);
1110 MUTEX_ENTER(&fr->fr_lock);
1112 MUTEX_EXIT(&fr->fr_lock);
1116 if (is->is_flags & (SI_WILDP|SI_WILDA)) {
1117 DT(iss_wild_plus_one);
1118 SINCL(ipf_state_stats.iss_wild);
1121 SBUMP(ipf_state_stats.iss_proto[is->is_p]);
1122 SBUMP(ipf_state_stats.iss_active_proto[is->is_p]);
1125 * add into list table.
1127 if (softs->ipf_state_list != NULL)
1128 softs->ipf_state_list->is_pnext = &is->is_next;
1129 is->is_pnext = &softs->ipf_state_list;
1130 is->is_next = softs->ipf_state_list;
1131 softs->ipf_state_list = is;
1133 if (softs->ipf_state_table[hv] != NULL)
1134 softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
1136 softs->ipf_state_stats.iss_inuse++;
1137 is->is_phnext = softs->ipf_state_table + hv;
1138 is->is_hnext = softs->ipf_state_table[hv];
1139 softs->ipf_state_table[hv] = is;
1140 softs->ipf_state_stats.iss_bucketlen[hv]++;
1141 softs->ipf_state_stats.iss_active++;
1142 MUTEX_EXIT(&softs->ipf_stinsert);
1144 ipf_state_setqueue(softc, is, rev);
1150 /* ------------------------------------------------------------------------ */
1151 /* Function: ipf_state_matchipv4addrs */
1152 /* Returns: int - 2 addresses match (strong match), 1 reverse match, */
1154 /* Parameters: is1, is2 pointers to states we are checking */
1156 /* Function matches IPv4 addresses it returns strong match for ICMP proto */
1157 /* even there is only reverse match */
1158 /* ------------------------------------------------------------------------ */
1160 ipf_state_matchipv4addrs(is1, is2)
1161 ipstate_t *is1, *is2;
1165 if (is1->is_saddr == is2->is_saddr && is1->is_daddr == is2->is_daddr)
1167 else if (is1->is_saddr == is2->is_daddr &&
1168 is1->is_daddr == is2->is_saddr) {
1169 /* force strong match for ICMP protocol */
1170 rv = (is1->is_p == IPPROTO_ICMP) ? 2 : 1;
1179 /* ------------------------------------------------------------------------ */
1180 /* Function: ipf_state_matchipv6addrs */
1181 /* Returns: int - 2 addresses match (strong match), 1 reverse match, */
1183 /* Parameters: is1, is2 pointers to states we are checking */
1185 /* Function matches IPv6 addresses it returns strong match for ICMP proto */
1186 /* even there is only reverse match */
1187 /* ------------------------------------------------------------------------ */
1189 ipf_state_matchipv6addrs(is1, is2)
1190 ipstate_t *is1, *is2;
1194 if (IP6_EQ(&is1->is_src, &is2->is_src) &&
1195 IP6_EQ(&is1->is_dst, &is2->is_dst))
1197 else if (IP6_EQ(&is1->is_src, &is2->is_dst) &&
1198 IP6_EQ(&is1->is_dst, &is2->is_src)) {
1199 /* force strong match for ICMPv6 protocol */
1200 rv = (is1->is_p == IPPROTO_ICMPV6) ? 2 : 1;
1209 /* ------------------------------------------------------------------------ */
1210 /* Function: ipf_state_matchaddresses */
1211 /* Returns: int - 2 addresses match, 1 reverse match, zero no match */
1212 /* Parameters: is1, is2 pointers to states we are checking */
1214 /* function retruns true if two pairs of addresses belong to single */
1215 /* connection. suppose there are two endpoints: */
1216 /* endpoint1 1.1.1.1 */
1217 /* endpoint2 1.1.1.2 */
1219 /* the state is established by packet flying from .1 to .2 so we see: */
1220 /* is1->src = 1.1.1.1 */
1221 /* is1->dst = 1.1.1.2 */
1222 /* now endpoint 1.1.1.2 sends answer */
1223 /* retreives is1 record created by first packat and compares it with is2 */
1224 /* temporal record, is2 is initialized as follows: */
1225 /* is2->src = 1.1.1.2 */
1226 /* is2->dst = 1.1.1.1 */
1227 /* in this case 1 will be returned */
1229 /* the ipf_matchaddresses() assumes those two records to be same. of course */
1230 /* the ipf_matchaddresses() also assume records are same in case you pass */
1231 /* identical arguments (i.e. ipf_matchaddress(is1, is1) would return 2 */
1232 /* ------------------------------------------------------------------------ */
1234 ipf_state_matchaddresses(is1, is2)
1235 ipstate_t *is1, *is2;
1239 if (is1->is_v == 4) {
1240 rv = ipf_state_matchipv4addrs(is1, is2);
1243 rv = ipf_state_matchipv6addrs(is1, is2);
1250 /* ------------------------------------------------------------------------ */
1251 /* Function: ipf_matchports */
1252 /* Returns: int - 2 match, 1 rverse match, 0 no match */
1253 /* Parameters: ppairs1, ppairs - src, dst ports we want to match */
1255 /* performs the same match for isps members as for addresses */
1256 /* ------------------------------------------------------------------------ */
1258 ipf_state_matchports(ppairs1, ppairs2)
1259 udpinfo_t *ppairs1, *ppairs2;
1263 if (ppairs1->us_sport == ppairs2->us_sport &&
1264 ppairs1->us_dport == ppairs2->us_dport)
1266 else if (ppairs1->us_sport == ppairs2->us_dport &&
1267 ppairs1->us_dport == ppairs2->us_sport)
1276 /* ------------------------------------------------------------------------ */
1277 /* Function: ipf_matchisps */
1278 /* Returns: int - nonzero if isps members match, 0 nomatch */
1279 /* Parameters: is1, is2 - states we want to match */
1281 /* performs the same match for isps members as for addresses */
1282 /* ------------------------------------------------------------------------ */
1284 ipf_state_matchisps(is1, is2)
1285 ipstate_t *is1, *is2;
1289 if (is1->is_p == is2->is_p) {
1295 /* greinfo_t can be also interprted as port pair */
1296 rv = ipf_state_matchports(&is1->is_ps.is_us,
1301 case IPPROTO_ICMPV6 :
1302 /* force strong match for ICMP datagram. */
1303 if (bcmp(&is1->is_ps, &is2->is_ps,
1304 sizeof(icmpinfo_t)) == 0) {
1322 /* ------------------------------------------------------------------------ */
1323 /* Function: ipf_state_match */
1324 /* Returns: int - nonzero match, zero no match */
1325 /* Parameters: is1, is2 - states we want to match */
1327 /* ------------------------------------------------------------------------ */
1329 ipf_state_match(is1, is2)
1330 ipstate_t *is1, *is2;
1336 if (bcmp(&is1->is_pass, &is2->is_pass,
1337 offsetof(struct ipstate, is_authmsk) -
1338 offsetof(struct ipstate, is_pass)) == 0) {
1340 pomatch = ipf_state_matchisps(is1, is2);
1341 amatch = ipf_state_matchaddresses(is1, is2);
1342 rv = (amatch != 0) && (amatch == pomatch);
1350 /* ------------------------------------------------------------------------ */
1351 /* Function: ipf_state_add */
1352 /* Returns: ipstate_t - 0 = success */
1353 /* Parameters: softc(I) - pointer to soft context main structure */
1354 /* fin(I) - pointer to packet information */
1355 /* stsave(O) - pointer to place to save pointer to created */
1356 /* state structure. */
1357 /* flags(I) - flags to use when creating the structure */
1359 /* Creates a new IP state structure from the packet information collected. */
1360 /* Inserts it into the state table and appends to the bottom of the active */
1361 /* list. If the capacity of the table has reached the maximum allowed then */
1362 /* the call will fail and a flush is scheduled for the next timeout call. */
1364 /* NOTE: The use of stsave to point to nat_state will result in memory */
1365 /* corruption. It should only be used to point to objects that will */
1366 /* either outlive this (not expired) or will deref the ip_state_t */
1367 /* when they are deleted. */
1368 /* ------------------------------------------------------------------------ */
1370 ipf_state_add(softc, fin, stsave, flags)
1371 ipf_main_softc_t *softc;
1376 ipf_state_softc_t *softs = softc->ipf_state_soft;
1386 * If a packet that was created locally is trying to go out but we
1387 * do not match here here because of this lock, it is likely that
1388 * the policy will block it and return network unreachable back up
1389 * the stack. To mitigate this error, EAGAIN is returned instead,
1390 * telling the IP stack to try sending this packet again later.
1392 if (softs->ipf_state_lock) {
1393 SBUMPD(ipf_state_stats, iss_add_locked);
1394 fin->fin_error = EAGAIN;
1398 if (fin->fin_flx & (FI_SHORT|FI_STATE|FI_FRAGBODY|FI_BAD)) {
1399 SBUMPD(ipf_state_stats, iss_add_bad);
1403 if ((fin->fin_flx & FI_OOW) && !(fin->fin_tcpf & TH_SYN)) {
1404 SBUMPD(ipf_state_stats, iss_add_oow);
1408 if ((softs->ipf_state_stats.iss_active * 100 / softs->ipf_state_max) >
1409 softs->ipf_state_wm_high) {
1410 softs->ipf_state_doflush = 1;
1414 * If a "keep state" rule has reached the maximum number of references
1415 * to it, then schedule an automatic flush in case we can clear out
1416 * some "dead old wood". Note that because the lock isn't held on
1417 * fr it is possible that we could overflow. The cost of overflowing
1418 * is being ignored here as the number by which it can overflow is
1419 * a product of the number of simultaneous threads that could be
1420 * executing in here, so a limit of 100 won't result in 200, but could
1421 * result in 101 or 102.
1425 if ((softs->ipf_state_stats.iss_active >=
1426 softs->ipf_state_max) && (fr->fr_statemax == 0)) {
1427 SBUMPD(ipf_state_stats, iss_max);
1430 if ((fr->fr_statemax != 0) &&
1431 (fr->fr_statecnt >= fr->fr_statemax)) {
1432 SBUMPD(ipf_state_stats, iss_max_ref);
1439 pass = softc->ipf_flags;
1440 is->is_tag = FR_NOLOGTAG;
1442 pass = fr->fr_flags;
1448 bzero((char *)is, sizeof(*is));
1449 is->is_die = 1 + softc->ipf_ticks;
1451 * We want to check everything that is a property of this packet,
1452 * but we don't (automatically) care about it's fragment status as
1456 is->is_v = fin->fin_v;
1457 is->is_sec = fin->fin_secmsk;
1458 is->is_secmsk = 0xffff;
1459 is->is_auth = fin->fin_auth;
1460 is->is_authmsk = 0xffff;
1461 is->is_family = fin->fin_family;
1462 is->is_opt[0] = fin->fin_optmsk;
1463 is->is_optmsk[0] = 0xffffffff;
1464 if (is->is_v == 6) {
1465 is->is_opt[0] &= ~0x8;
1466 is->is_optmsk[0] &= ~0x8;
1470 * Copy and calculate...
1472 hv = (is->is_p = fin->fin_fi.fi_p);
1473 is->is_src = fin->fin_fi.fi_src;
1475 is->is_dst = fin->fin_fi.fi_dst;
1478 if (fin->fin_v == 6) {
1480 * For ICMPv6, we check to see if the destination address is
1481 * a multicast address. If it is, do not include it in the
1482 * calculation of the hash because the correct reply will come
1483 * back from a real address, not a multicast address.
1485 if ((is->is_p == IPPROTO_ICMPV6) &&
1486 IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
1488 * So you can do keep state with neighbour discovery.
1490 * Here we could use the address from the neighbour
1491 * solicit message to put in the state structure and
1492 * we could use that without a wildcard flag too...
1494 flags |= SI_W_DADDR;
1497 hv += is->is_dst.i6[1];
1498 hv += is->is_dst.i6[2];
1499 hv += is->is_dst.i6[3];
1501 hv += is->is_src.i6[1];
1502 hv += is->is_src.i6[2];
1503 hv += is->is_src.i6[3];
1506 if ((fin->fin_v == 4) &&
1507 (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
1508 flags |= SI_W_DADDR;
1515 case IPPROTO_ICMPV6 :
1518 switch (ic->icmp_type)
1520 case ICMP6_ECHO_REQUEST :
1521 hv += (is->is_icmp.ici_id = ic->icmp_id);
1523 case ICMP6_MEMBERSHIP_QUERY :
1524 case ND_ROUTER_SOLICIT :
1525 case ND_NEIGHBOR_SOLICIT :
1526 case ICMP6_NI_QUERY :
1527 is->is_icmp.ici_type = ic->icmp_type;
1530 SBUMPD(ipf_state_stats, iss_icmp6_notquery);
1538 switch (ic->icmp_type)
1544 is->is_icmp.ici_type = ic->icmp_type;
1545 hv += (is->is_icmp.ici_id = ic->icmp_id);
1548 SBUMPD(ipf_state_stats, iss_icmp_notquery);
1557 is->is_gre.gs_flags = gre->gr_flags;
1558 is->is_gre.gs_ptype = gre->gr_ptype;
1559 if (GRE_REV(is->is_gre.gs_flags) == 1) {
1560 is->is_call[0] = fin->fin_data[0];
1561 is->is_call[1] = fin->fin_data[1];
1569 if (tcp->th_flags & TH_RST) {
1570 SBUMPD(ipf_state_stats, iss_tcp_rstadd);
1574 /* TRACE is, flags, hv */
1577 * The endian of the ports doesn't matter, but the ack and
1578 * sequence numbers do as we do mathematics on them later.
1580 is->is_sport = htons(fin->fin_data[0]);
1581 is->is_dport = htons(fin->fin_data[1]);
1582 if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1587 /* TRACE is, flags, hv */
1590 * If this is a real packet then initialise fields in the
1591 * state information structure from the TCP header information.
1595 is->is_maxswin = ntohs(tcp->th_win);
1596 if (is->is_maxswin == 0)
1599 if ((fin->fin_flx & FI_IGNORE) == 0) {
1600 is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
1601 (TCP_OFF(tcp) << 2) +
1602 ((tcp->th_flags & TH_SYN) ? 1 : 0) +
1603 ((tcp->th_flags & TH_FIN) ? 1 : 0);
1604 is->is_maxsend = is->is_send;
1607 * Window scale option is only present in
1608 * SYN/SYN-ACK packet.
1610 if ((tcp->th_flags & ~(TH_FIN|TH_ACK|TH_ECNALL)) ==
1612 (TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
1613 if (ipf_tcpoptions(softs, fin, tcp,
1614 &is->is_tcp.ts_data[0]) == -1)
1615 fin->fin_flx |= FI_BAD;
1618 if ((fin->fin_out != 0) && (pass & FR_NEWISN) != 0) {
1619 ipf_checknewisn(fin, is);
1620 ipf_fixoutisn(fin, is);
1623 if ((tcp->th_flags & TH_OPENING) == TH_SYN)
1626 is->is_maxdwin = is->is_maxswin * 2;
1627 is->is_dend = ntohl(tcp->th_ack);
1628 is->is_maxdend = ntohl(tcp->th_ack);
1629 is->is_maxdwin *= 2;
1634 * If we're creating state for a starting connection, start
1635 * the timer on it as we'll never see an error if it fails
1643 is->is_sport = htons(fin->fin_data[0]);
1644 is->is_dport = htons(fin->fin_data[1]);
1645 if ((flags & (SI_W_DPORT|SI_W_SPORT)) == 0) {
1646 hv += tcp->th_dport;
1647 hv += tcp->th_sport;
1654 hv = DOUBLE_HASH(hv);
1658 * Look for identical state.
1660 for (is = softs->ipf_state_table[hv % softs->ipf_state_size];
1661 is != NULL; is = is->is_hnext) {
1662 if (ipf_state_match(&ips, is) == 1)
1666 SBUMPD(ipf_state_stats, iss_add_dup);
1670 if (softs->ipf_state_stats.iss_bucketlen[hv] >=
1671 softs->ipf_state_maxbucket) {
1672 SBUMPD(ipf_state_stats, iss_bucket_full);
1675 KMALLOC(is, ipstate_t *);
1677 SBUMPD(ipf_state_stats, iss_nomem);
1680 bcopy((char *)&ips, (char *)is, sizeof(*is));
1681 is->is_flags = flags & IS_INHERITED;
1682 is->is_rulen = fin->fin_rule;
1686 * Do not do the modulous here, it is done in ipf_state_insert().
1691 (void) strncpy(is->is_group, FR_NAME(fr, fr_group),
1693 if (fr->fr_age[0] != 0) {
1694 tq = ipf_addtimeoutqueue(softc,
1695 &softs->ipf_state_usertq,
1697 is->is_tqehead[0] = tq;
1698 is->is_sti.tqe_flags |= TQE_RULEBASED;
1700 if (fr->fr_age[1] != 0) {
1701 tq = ipf_addtimeoutqueue(softc,
1702 &softs->ipf_state_usertq,
1704 is->is_tqehead[1] = tq;
1705 is->is_sti.tqe_flags |= TQE_RULEBASED;
1708 is->is_tag = fr->fr_logtag;
1712 * It may seem strange to set is_ref to 2, but if stsave is not NULL
1713 * then a copy of the pointer is being stored somewhere else and in
1714 * the end, it will expect to be able to do osmething with it.
1717 if (stsave != NULL) {
1723 is->is_pkts[0] = 0, is->is_bytes[0] = 0;
1724 is->is_pkts[1] = 0, is->is_bytes[1] = 0;
1725 is->is_pkts[2] = 0, is->is_bytes[2] = 0;
1726 is->is_pkts[3] = 0, is->is_bytes[3] = 0;
1727 if ((fin->fin_flx & FI_IGNORE) == 0) {
1728 is->is_pkts[out] = 1;
1729 fin->fin_pktnum = 1;
1730 is->is_bytes[out] = fin->fin_plen;
1731 is->is_flx[out][0] = fin->fin_flx & FI_CMP;
1732 is->is_flx[out][0] &= ~FI_OOW;
1735 if (pass & FR_STLOOSE)
1736 is->is_flags |= IS_LOOSE;
1738 if (pass & FR_STSTRICT)
1739 is->is_flags |= IS_STRICT;
1741 if (pass & FR_STATESYNC)
1742 is->is_flags |= IS_STATESYNC;
1744 if (pass & FR_LOGFIRST)
1745 is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
1747 READ_ENTER(&softc->ipf_state);
1749 if (ipf_state_insert(softc, is, fin->fin_rev) == -1) {
1750 RWLOCK_EXIT(&softc->ipf_state);
1752 * This is a bit more manual than it should be but
1753 * ipf_state_del cannot be called.
1755 MUTEX_EXIT(&is->is_lock);
1756 MUTEX_DESTROY(&is->is_lock);
1757 if (is->is_tqehead[0] != NULL) {
1758 if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
1759 ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
1760 is->is_tqehead[0] = NULL;
1762 if (is->is_tqehead[1] != NULL) {
1763 if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
1764 ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
1765 is->is_tqehead[1] = NULL;
1772 * Filling in the interface name is after the insert so that an
1773 * event (such as add/delete) of an interface that is referenced
1774 * by this rule will see this state entry.
1778 * The name '-' is special for network interfaces and causes
1779 * a NULL name to be present, always, allowing packets to
1780 * match it, regardless of their interface.
1782 if ((fin->fin_ifp == NULL) ||
1783 (fr->fr_ifnames[out << 1] != -1 &&
1784 fr->fr_names[fr->fr_ifnames[out << 1] + 0] == '-' &&
1785 fr->fr_names[fr->fr_ifnames[out << 1] + 1] == '\0')) {
1786 is->is_ifp[out << 1] = fr->fr_ifas[0];
1787 strncpy(is->is_ifname[out << 1],
1788 fr->fr_names + fr->fr_ifnames[0],
1789 sizeof(fr->fr_ifnames[0]));
1791 is->is_ifp[out << 1] = fin->fin_ifp;
1792 COPYIFNAME(fin->fin_v, fin->fin_ifp,
1793 is->is_ifname[out << 1]);
1796 is->is_ifp[(out << 1) + 1] = fr->fr_ifas[1];
1797 if (fr->fr_ifnames[1] != -1) {
1798 strncpy(is->is_ifname[(out << 1) + 1],
1799 fr->fr_names + fr->fr_ifnames[1],
1800 sizeof(fr->fr_ifnames[1]));
1803 is->is_ifp[(1 - out) << 1] = fr->fr_ifas[2];
1804 if (fr->fr_ifnames[2] != -1) {
1805 strncpy(is->is_ifname[((1 - out) << 1)],
1806 fr->fr_names + fr->fr_ifnames[2],
1807 sizeof(fr->fr_ifnames[2]));
1810 is->is_ifp[((1 - out) << 1) + 1] = fr->fr_ifas[3];
1811 if (fr->fr_ifnames[3] != -1) {
1812 strncpy(is->is_ifname[((1 - out) << 1) + 1],
1813 fr->fr_names + fr->fr_ifnames[3],
1814 sizeof(fr->fr_ifnames[3]));
1817 if (fin->fin_ifp != NULL) {
1818 is->is_ifp[out << 1] = fin->fin_ifp;
1819 COPYIFNAME(fin->fin_v, fin->fin_ifp,
1820 is->is_ifname[out << 1]);
1824 if (fin->fin_p == IPPROTO_TCP) {
1826 * If we're creating state for a starting connection, start the
1827 * timer on it as we'll never see an error if it fails to
1830 (void) ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
1833 MUTEX_EXIT(&is->is_lock);
1834 if ((is->is_flags & IS_STATESYNC) && ((is->is_flags & SI_CLONE) == 0))
1835 is->is_sync = ipf_sync_new(softc, SMC_STATE, fin, is);
1836 if (softs->ipf_state_logging)
1837 ipf_state_log(softc, is, ISL_NEW);
1839 RWLOCK_EXIT(&softc->ipf_state);
1841 fin->fin_flx |= FI_STATE;
1842 if (fin->fin_flx & FI_FRAG)
1843 (void) ipf_frag_new(softc, fin, pass);
1845 fdp = &fr->fr_tifs[0];
1846 if (fdp->fd_type == FRD_DSTLIST) {
1847 ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1850 bcopy(fdp, &is->is_tifs[0], sizeof(*fdp));
1853 fdp = &fr->fr_tifs[1];
1854 if (fdp->fd_type == FRD_DSTLIST) {
1855 ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1858 bcopy(fdp, &is->is_tifs[1], sizeof(*fdp));
1860 fin->fin_tif = &is->is_tifs[fin->fin_rev];
1863 if (fdp->fd_type == FRD_DSTLIST) {
1864 ipf_dstlist_select_node(fin, fdp->fd_ptr, NULL,
1867 bcopy(fdp, &is->is_dif, sizeof(*fdp));
1869 fin->fin_dif = &is->is_dif;
1875 /* ------------------------------------------------------------------------ */
1876 /* Function: ipf_tcpoptions */
1877 /* Returns: int - 1 == packet matches state entry, 0 == it does not, */
1878 /* -1 == packet has bad TCP options data */
1879 /* Parameters: softs(I) - pointer to state context structure */
1880 /* fin(I) - pointer to packet information */
1881 /* tcp(I) - pointer to TCP packet header */
1882 /* td(I) - pointer to TCP data held as part of the state */
1884 /* Look after the TCP header for any options and deal with those that are */
1885 /* present. Record details about those that we recogise. */
1886 /* ------------------------------------------------------------------------ */
1888 ipf_tcpoptions(softs, fin, tcp, td)
1889 ipf_state_softc_t *softs;
1894 int off, mlen, ol, i, len, retval;
1895 char buf[64], *s, opt;
1898 len = (TCP_OFF(tcp) << 2);
1899 if (fin->fin_dlen < len) {
1900 SBUMPD(ipf_state_stats, iss_tcp_toosmall);
1903 len -= sizeof(*tcp);
1905 off = fin->fin_plen - fin->fin_dlen + sizeof(*tcp) + fin->fin_ipoff;
1908 mlen = MSGDSIZE(m) - off;
1916 COPYDATA(m, off, len, buf);
1918 for (s = buf; len > 0; ) {
1920 if (opt == TCPOPT_EOL)
1922 else if (opt == TCPOPT_NOP)
1928 if (ol < 2 || ol > len)
1932 * Extract the TCP options we are interested in out of
1933 * the header and store them in the the tcpdata struct.
1937 case TCPOPT_WINDOW :
1938 if (ol == TCPOLEN_WINDOW) {
1940 if (i > TCP_WSCALE_MAX)
1944 td->td_winscale = i;
1945 td->td_winflags |= TCP_WSCALE_SEEN|
1950 case TCPOPT_MAXSEG :
1952 * So, if we wanted to set the TCP MAXSEG,
1953 * it should be done here...
1955 if (ol == TCPOLEN_MAXSEG) {
1963 case TCPOPT_SACK_PERMITTED :
1964 if (ol == TCPOLEN_SACK_PERMITTED)
1965 td->td_winflags |= TCP_SACK_PERMIT;
1975 SBUMPD(ipf_state_stats, iss_tcp_badopt);
1981 /* ------------------------------------------------------------------------ */
1982 /* Function: ipf_state_tcp */
1983 /* Returns: int - 1 == packet matches state entry, 0 == it does not */
1984 /* Parameters: softc(I) - pointer to soft context main structure */
1985 /* softs(I) - pointer to state context structure */
1986 /* fin(I) - pointer to packet information */
1987 /* tcp(I) - pointer to TCP packet header */
1988 /* is(I) - pointer to master state structure */
1990 /* Check to see if a packet with TCP headers fits within the TCP window. */
1991 /* Change timeout depending on whether new packet is a SYN-ACK returning */
1992 /* for a SYN or a RST or FIN which indicate time to close up shop. */
1993 /* ------------------------------------------------------------------------ */
1995 ipf_state_tcp(softc, softs, fin, tcp, is)
1996 ipf_main_softc_t *softc;
1997 ipf_state_softc_t *softs;
2002 tcpdata_t *fdata, *tdata;
2003 int source, ret, flags;
2005 source = !fin->fin_rev;
2006 if (((is->is_flags & IS_TCPFSM) != 0) && (source == 1) &&
2007 (ntohs(is->is_sport) != fin->fin_data[0]))
2009 fdata = &is->is_tcp.ts_data[!source];
2010 tdata = &is->is_tcp.ts_data[source];
2012 MUTEX_ENTER(&is->is_lock);
2015 * If a SYN packet is received for a connection that is on the way out
2016 * but hasn't yet departed then advance this session along the way.
2018 if ((tcp->th_flags & TH_OPENING) == TH_SYN) {
2019 if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
2020 (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
2021 is->is_state[!source] = IPF_TCPS_CLOSED;
2022 ipf_movequeue(softc->ipf_ticks, &is->is_sti,
2024 &softs->ipf_state_deletetq);
2025 MUTEX_EXIT(&is->is_lock);
2026 DT1(iss_tcp_closing, ipstate_t *, is);
2027 SBUMP(ipf_state_stats.iss_tcp_closing);
2032 if (is->is_flags & IS_LOOSE)
2035 ret = ipf_state_tcpinwindow(fin, fdata, tdata, tcp,
2039 * Nearing end of connection, start timeout.
2041 ret = ipf_tcp_age(&is->is_sti, fin, softs->ipf_state_tcptq,
2044 MUTEX_EXIT(&is->is_lock);
2045 DT2(iss_tcp_fsm, fr_info_t *, fin, ipstate_t *, is);
2046 SBUMP(ipf_state_stats.iss_tcp_fsm);
2050 if (softs->ipf_state_logging > 4)
2051 ipf_state_log(softc, is, ISL_STATECHANGE);
2054 * set s0's as appropriate. Use syn-ack packet as it
2055 * contains both pieces of required information.
2058 * Window scale option is only present in SYN/SYN-ACK packet.
2059 * Compare with ~TH_FIN to mask out T/TCP setups.
2061 flags = tcp->th_flags & ~(TH_FIN|TH_ECNALL);
2062 if (flags == (TH_SYN|TH_ACK)) {
2063 is->is_s0[source] = ntohl(tcp->th_ack);
2064 is->is_s0[!source] = ntohl(tcp->th_seq) + 1;
2065 if ((TCP_OFF(tcp) > (sizeof(tcphdr_t) >> 2))) {
2066 if (ipf_tcpoptions(softs, fin, tcp,
2068 fin->fin_flx |= FI_BAD;
2070 if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2071 ipf_checknewisn(fin, is);
2072 } else if (flags == TH_SYN) {
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,
2077 fin->fin_flx |= FI_BAD;
2080 if ((fin->fin_out != 0) && (is->is_pass & FR_NEWISN))
2081 ipf_checknewisn(fin, is);
2086 DT2(iss_tcp_oow, fr_info_t *, fin, ipstate_t *, is);
2087 SBUMP(ipf_state_stats.iss_tcp_oow);
2090 MUTEX_EXIT(&is->is_lock);
2095 /* ------------------------------------------------------------------------ */
2096 /* Function: ipf_checknewisn */
2098 /* Parameters: fin(I) - pointer to packet information */
2099 /* is(I) - pointer to master state structure */
2101 /* Check to see if this TCP connection is expecting and needs a new */
2102 /* sequence number for a particular direction of the connection. */
2104 /* NOTE: This does not actually change the sequence numbers, only gets new */
2106 /* ------------------------------------------------------------------------ */
2108 ipf_checknewisn(fin, is)
2112 u_32_t sumd, old, new;
2119 if (((i == 0) && !(is->is_flags & IS_ISNSYN)) ||
2120 ((i == 1) && !(is->is_flags & IS_ISNACK))) {
2121 old = ntohl(tcp->th_seq);
2122 new = ipf_newisn(fin);
2123 is->is_isninc[i] = new - old;
2124 CALC_SUMD(old, new, sumd);
2125 is->is_sumd[i] = (sumd & 0xffff) + (sumd >> 16);
2127 is->is_flags |= ((i == 0) ? IS_ISNSYN : IS_ISNACK);
2132 /* ------------------------------------------------------------------------ */
2133 /* Function: ipf_state_tcpinwindow */
2134 /* Returns: int - 1 == packet inside TCP "window", 0 == not inside. */
2135 /* Parameters: fin(I) - pointer to packet information */
2136 /* fdata(I) - pointer to tcp state informatio (forward) */
2137 /* tdata(I) - pointer to tcp state informatio (reverse) */
2138 /* tcp(I) - pointer to TCP packet header */
2140 /* Given a packet has matched addresses and ports, check to see if it is */
2141 /* within the TCP data window. In a show of generosity, allow packets that */
2142 /* are within the window space behind the current sequence # as well. */
2143 /* ------------------------------------------------------------------------ */
2145 ipf_state_tcpinwindow(fin, fdata, tdata, tcp, flags)
2147 tcpdata_t *fdata, *tdata;
2151 ipf_main_softc_t *softc = fin->fin_main_soft;
2152 ipf_state_softc_t *softs = softc->ipf_state_soft;
2153 tcp_seq seq, ack, end;
2154 int ackskew, tcpflags;
2159 * Find difference between last checked packet and this packet.
2161 tcpflags = tcp->th_flags;
2162 seq = ntohl(tcp->th_seq);
2163 ack = ntohl(tcp->th_ack);
2164 if (tcpflags & TH_SYN)
2165 win = ntohs(tcp->th_win);
2167 win = ntohs(tcp->th_win) << fdata->td_winscale;
2170 * A window of 0 produces undesirable behaviour from this function.
2175 dsize = fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2176 ((tcpflags & TH_SYN) ? 1 : 0) + ((tcpflags & TH_FIN) ? 1 : 0);
2179 * if window scaling is present, the scaling is only allowed
2180 * for windows not in the first SYN packet. In that packet the
2181 * window is 65535 to specify the largest window possible
2182 * for receivers not implementing the window scale option.
2183 * Currently, we do not assume TTCP here. That means that
2184 * if we see a second packet from a host (after the initial
2185 * SYN), we can assume that the receiver of the SYN did
2186 * already send back the SYN/ACK (and thus that we know if
2187 * the receiver also does window scaling)
2189 if (!(tcpflags & TH_SYN) && (fdata->td_winflags & TCP_WSCALE_FIRST)) {
2190 fdata->td_winflags &= ~TCP_WSCALE_FIRST;
2191 fdata->td_maxwin = win;
2196 if ((fdata->td_end == 0) &&
2197 (!(flags & IS_TCPFSM) ||
2198 ((tcpflags & TH_OPENING) == TH_OPENING))) {
2200 * Must be a (outgoing) SYN-ACK in reply to a SYN.
2202 fdata->td_end = end - 1;
2203 fdata->td_maxwin = 1;
2204 fdata->td_maxend = end + win;
2207 if (!(tcpflags & TH_ACK)) { /* Pretend an ack was sent */
2208 ack = tdata->td_end;
2209 } else if (((tcpflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
2211 /* gross hack to get around certain broken tcp stacks */
2212 ack = tdata->td_end;
2215 maxwin = tdata->td_maxwin;
2216 ackskew = tdata->td_end - ack;
2219 * Strict sequencing only allows in-order delivery.
2221 if ((flags & IS_STRICT) != 0) {
2222 if (seq != fdata->td_end) {
2223 DT2(iss_tcp_struct, tcpdata_t *, fdata, int, seq);
2224 SBUMP(ipf_state_stats.iss_tcp_strict);
2225 fin->fin_flx |= FI_OOW;
2230 #define SEQ_GE(a,b) ((int)((a) - (b)) >= 0)
2231 #define SEQ_GT(a,b) ((int)((a) - (b)) > 0)
2233 if ((SEQ_GE(fdata->td_maxend, end)) &&
2234 (SEQ_GE(seq, fdata->td_end - maxwin)) &&
2235 /* XXX what about big packets */
2236 #define MAXACKWINDOW 66000
2237 (-ackskew <= (MAXACKWINDOW)) &&
2238 ( ackskew <= (MAXACKWINDOW << fdata->td_winscale))) {
2241 * Microsoft Windows will send the next packet to the right of the
2242 * window if SACK is in use.
2244 } else if ((seq == fdata->td_maxend) && (ackskew == 0) &&
2245 (fdata->td_winflags & TCP_SACK_PERMIT) &&
2246 (tdata->td_winflags & TCP_SACK_PERMIT)) {
2247 DT2(iss_sinsack, tcpdata_t *, fdata, int, seq);
2248 SBUMP(ipf_state_stats.iss_winsack);
2251 * Sometimes a TCP RST will be generated with only the ACK field
2254 } else if ((seq == 0) && (tcpflags == (TH_RST|TH_ACK)) &&
2255 (ackskew >= -1) && (ackskew <= 1)) {
2257 } else if (!(flags & IS_TCPFSM)) {
2260 i = (fin->fin_rev << 1) + fin->fin_out;
2263 if (is_pkts[i]0 == 0) {
2265 * Picking up a connection in the middle, the "next"
2266 * packet seen from a direction that is new should be
2267 * accepted, even if it appears out of sequence.
2272 if (!(fdata->td_winflags &
2273 (TCP_WSCALE_SEEN|TCP_WSCALE_FIRST))) {
2275 * No TCPFSM and no window scaling, so make some
2278 if ((seq == fdata->td_maxend) && (ackskew == 0))
2280 else if (SEQ_GE(seq + maxwin, fdata->td_end - maxwin))
2285 /* TRACE(inseq, fdata, tdata, seq, end, ack, ackskew, win, maxwin) */
2288 /* if ackskew < 0 then this should be due to fragmented
2289 * packets. There is no way to know the length of the
2290 * total packet in advance.
2291 * We do know the total length from the fragment cache though.
2292 * Note however that there might be more sessions with
2293 * exactly the same source and destination parameters in the
2294 * state cache (and source and destination is the only stuff
2295 * that is saved in the fragment cache). Note further that
2296 * some TCP connections in the state cache are hashed with
2297 * sport and dport as well which makes it not worthwhile to
2299 * Thus, when ackskew is negative but still seems to belong
2300 * to this session, we bump up the destinations end value.
2303 tdata->td_end = ack;
2305 /* update max window seen */
2306 if (fdata->td_maxwin < win)
2307 fdata->td_maxwin = win;
2308 if (SEQ_GT(end, fdata->td_end))
2309 fdata->td_end = end;
2310 if (SEQ_GE(ack + win, tdata->td_maxend))
2311 tdata->td_maxend = ack + win;
2314 SBUMP(ipf_state_stats.iss_oow);
2315 fin->fin_flx |= FI_OOW;
2320 /* ------------------------------------------------------------------------ */
2321 /* Function: ipf_state_clone */
2322 /* Returns: ipstate_t* - NULL == cloning failed, */
2323 /* else pointer to new state structure */
2324 /* Parameters: fin(I) - pointer to packet information */
2325 /* tcp(I) - pointer to TCP/UDP header */
2326 /* is(I) - pointer to master state structure */
2328 /* Create a "duplcate" state table entry from the master. */
2329 /* ------------------------------------------------------------------------ */
2331 ipf_state_clone(fin, tcp, is)
2336 ipf_main_softc_t *softc = fin->fin_main_soft;
2337 ipf_state_softc_t *softs = softc->ipf_state_soft;
2341 if (softs->ipf_state_stats.iss_active == softs->ipf_state_max) {
2342 SBUMPD(ipf_state_stats, iss_max);
2343 softs->ipf_state_doflush = 1;
2346 KMALLOC(clone, ipstate_t *);
2347 if (clone == NULL) {
2348 SBUMPD(ipf_state_stats, iss_clone_nomem);
2351 bcopy((char *)is, (char *)clone, sizeof(*clone));
2353 MUTEX_NUKE(&clone->is_lock);
2355 * It has not yet been placed on any timeout queue, so make sure
2356 * all of that data is zero'd out.
2358 clone->is_sti.tqe_pnext = NULL;
2359 clone->is_sti.tqe_next = NULL;
2360 clone->is_sti.tqe_ifq = NULL;
2361 clone->is_sti.tqe_parent = clone;
2363 clone->is_die = ONE_DAY + softc->ipf_ticks;
2364 clone->is_state[0] = 0;
2365 clone->is_state[1] = 0;
2366 send = ntohl(tcp->th_seq) + fin->fin_dlen - (TCP_OFF(tcp) << 2) +
2367 ((tcp->th_flags & TH_SYN) ? 1 : 0) +
2368 ((tcp->th_flags & TH_FIN) ? 1 : 0);
2370 if (fin->fin_rev == 1) {
2371 clone->is_dend = send;
2372 clone->is_maxdend = send;
2374 clone->is_maxswin = 1;
2375 clone->is_maxdwin = ntohs(tcp->th_win);
2376 if (clone->is_maxdwin == 0)
2377 clone->is_maxdwin = 1;
2379 clone->is_send = send;
2380 clone->is_maxsend = send;
2382 clone->is_maxdwin = 1;
2383 clone->is_maxswin = ntohs(tcp->th_win);
2384 if (clone->is_maxswin == 0)
2385 clone->is_maxswin = 1;
2388 clone->is_flags &= ~SI_CLONE;
2389 clone->is_flags |= SI_CLONED;
2390 if (ipf_state_insert(softc, clone, fin->fin_rev) == -1) {
2396 if (clone->is_p == IPPROTO_TCP) {
2397 (void) ipf_tcp_age(&clone->is_sti, fin, softs->ipf_state_tcptq,
2398 clone->is_flags, 2);
2400 MUTEX_EXIT(&clone->is_lock);
2401 if (is->is_flags & IS_STATESYNC)
2402 clone->is_sync = ipf_sync_new(softc, SMC_STATE, fin, clone);
2403 DT2(iss_clone, ipstate_t *, is, ipstate_t *, clone);
2404 SBUMP(ipf_state_stats.iss_cloned);
2409 /* ------------------------------------------------------------------------ */
2410 /* Function: ipf_matchsrcdst */
2412 /* Parameters: fin(I) - pointer to packet information */
2413 /* is(I) - pointer to state structure */
2414 /* src(I) - pointer to source address */
2415 /* dst(I) - pointer to destination address */
2416 /* tcp(I) - pointer to TCP/UDP header */
2417 /* cmask(I) - mask of FI_* bits to check */
2419 /* Match a state table entry against an IP packet. The logic below is that */
2420 /* ret gets set to one if the match succeeds, else remains 0. If it is */
2421 /* still 0 after the test. no match. */
2422 /* ------------------------------------------------------------------------ */
2424 ipf_matchsrcdst(fin, is, src, dst, tcp, cmask)
2427 i6addr_t *src, *dst;
2431 ipf_main_softc_t *softc = fin->fin_main_soft;
2432 ipf_state_softc_t *softs = softc->ipf_state_soft;
2433 int ret = 0, rev, out, flags, flx = 0, idx;
2439 * If a connection is about to be deleted, no packets
2440 * are allowed to match it.
2442 if (is->is_sti.tqe_ifq == &softs->ipf_state_deletetq)
2445 rev = IP6_NEQ(&is->is_dst, dst);
2448 flags = is->is_flags;
2453 sp = htons(fin->fin_sport);
2454 dp = ntohs(fin->fin_dport);
2458 if (!(flags & SI_W_SPORT) && (sp != is->is_sport))
2460 else if (!(flags & SI_W_DPORT) && (dp != is->is_dport))
2465 idx = (out << 1) + rev;
2468 * If the interface for this 'direction' is set, make sure it matches.
2469 * An interface name that is not set matches any, as does a name of *.
2471 if ((is->is_ifp[idx] == ifp) || (is->is_ifp[idx] == NULL &&
2472 (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '-' ||
2473 *is->is_ifname[idx] == '*')))
2477 DT2(iss_lookup_badifp, fr_info_t *, fin, ipstate_t *, is);
2478 SBUMP(ipf_state_stats.iss_lookup_badifp);
2479 /* TRACE is, out, rev, idx */
2485 * Match addresses and ports.
2488 if ((IP6_EQ(&is->is_dst, dst) || (flags & SI_W_DADDR)) &&
2489 (IP6_EQ(&is->is_src, src) || (flags & SI_W_SADDR))) {
2491 if ((sp == is->is_sport || flags & SI_W_SPORT)
2493 (dp == is->is_dport || flags & SI_W_DPORT))
2500 if ((IP6_EQ(&is->is_dst, src) || (flags & SI_W_DADDR)) &&
2501 (IP6_EQ(&is->is_src, dst) || (flags & SI_W_SADDR))) {
2503 if ((dp == is->is_sport || flags & SI_W_SPORT)
2505 (sp == is->is_dport || flags & SI_W_DPORT))
2514 SBUMP(ipf_state_stats.iss_lookup_badport);
2515 DT2(iss_lookup_badport, fr_info_t *, fin, ipstate_t *, is);
2516 /* TRACE rev, is, sp, dp, src, dst */
2521 * Whether or not this should be here, is questionable, but the aim
2522 * is to get this out of the main line.
2525 flags = is->is_flags & ~(SI_WILDP|SI_NEWFR|SI_CLONE|SI_CLONED);
2528 * Only one of the source or destination address can be flaged as a
2529 * wildcard. Fill in the missing address, if set.
2530 * For IPv6, if the address being copied in is multicast, then
2531 * don't reset the wild flag - multicast causes it to be set in the
2534 if ((flags & (SI_W_SADDR|SI_W_DADDR))) {
2535 fr_ip_t *fi = &fin->fin_fi;
2537 if ((flags & SI_W_SADDR) != 0) {
2539 is->is_src = fi->fi_src;
2540 is->is_flags &= ~SI_W_SADDR;
2542 if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2543 is->is_src = fi->fi_dst;
2544 is->is_flags &= ~SI_W_SADDR;
2547 } else if ((flags & SI_W_DADDR) != 0) {
2549 if (!(fin->fin_flx & (FI_MULTICAST|FI_MBCAST))){
2550 is->is_dst = fi->fi_dst;
2551 is->is_flags &= ~SI_W_DADDR;
2554 is->is_dst = fi->fi_src;
2555 is->is_flags &= ~SI_W_DADDR;
2558 if ((is->is_flags & (SI_WILDA|SI_WILDP)) == 0) {
2559 ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2563 flx = fin->fin_flx & cmask;
2564 cflx = is->is_flx[out][rev];
2567 * Match up any flags set from IP options.
2569 if ((cflx && (flx != (cflx & cmask))) ||
2570 ((fin->fin_optmsk & is->is_optmsk[rev]) != is->is_opt[rev]) ||
2571 ((fin->fin_secmsk & is->is_secmsk) != is->is_sec) ||
2572 ((fin->fin_auth & is->is_authmsk) != is->is_auth)) {
2573 SBUMPD(ipf_state_stats, iss_miss_mask);
2577 if ((fin->fin_flx & FI_IGNORE) != 0) {
2583 * Only one of the source or destination port can be flagged as a
2584 * wildcard. When filling it in, fill in a copy of the matched entry
2585 * if it has the cloning flag set.
2587 if ((flags & (SI_W_SPORT|SI_W_DPORT))) {
2588 if ((flags & SI_CLONE) != 0) {
2591 clone = ipf_state_clone(fin, tcp, is);
2596 ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
2599 if ((flags & SI_W_SPORT) != 0) {
2602 is->is_send = ntohl(tcp->th_seq);
2605 is->is_send = ntohl(tcp->th_ack);
2607 is->is_maxsend = is->is_send + 1;
2608 } else if ((flags & SI_W_DPORT) != 0) {
2611 is->is_dend = ntohl(tcp->th_ack);
2614 is->is_dend = ntohl(tcp->th_seq);
2616 is->is_maxdend = is->is_dend + 1;
2618 is->is_flags &= ~(SI_W_SPORT|SI_W_DPORT);
2619 if ((flags & SI_CLONED) && softs->ipf_state_logging)
2620 ipf_state_log(softc, is, ISL_CLONE);
2625 if (is->is_flx[out][rev] == 0) {
2626 is->is_flx[out][rev] = flx;
2627 if (rev == 1 && is->is_optmsk[1] == 0) {
2628 is->is_opt[1] = fin->fin_optmsk;
2629 is->is_optmsk[1] = 0xffffffff;
2630 if (is->is_v == 6) {
2631 is->is_opt[1] &= ~0x8;
2632 is->is_optmsk[1] &= ~0x8;
2638 * Check if the interface name for this "direction" is set and if not,
2641 if (is->is_ifp[idx] == NULL &&
2642 (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) {
2643 is->is_ifp[idx] = ifp;
2644 COPYIFNAME(fin->fin_v, ifp, is->is_ifname[idx]);
2651 /* ------------------------------------------------------------------------ */
2652 /* Function: ipf_checkicmpmatchingstate */
2654 /* Parameters: fin(I) - pointer to packet information */
2656 /* If we've got an ICMP error message, using the information stored in the */
2657 /* ICMP packet, look for a matching state table entry. */
2659 /* If we return NULL then no lock on ipf_state is held. */
2660 /* If we return non-null then a read-lock on ipf_state is held. */
2661 /* ------------------------------------------------------------------------ */
2663 ipf_checkicmpmatchingstate(fin)
2666 ipf_main_softc_t *softc = fin->fin_main_soft;
2667 ipf_state_softc_t *softs = softc->ipf_state_soft;
2668 ipstate_t *is, **isp;
2681 * Does it at least have the return (basic) IP header ?
2682 * Is it an actual recognised ICMP error type?
2683 * Only a basic IP header (no options) should be with
2684 * an ICMP error header.
2686 if ((fin->fin_v != 4) || (fin->fin_hlen != sizeof(ip_t)) ||
2687 (fin->fin_plen < ICMPERR_MINPKTLEN) ||
2688 !(fin->fin_flx & FI_ICMPERR)) {
2689 SBUMPD(ipf_state_stats, iss_icmp_bad);
2693 type = ic->icmp_type;
2695 oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
2697 * Check if the at least the old IP header (with options) and
2698 * 8 bytes of payload is present.
2700 if (fin->fin_plen < ICMPERR_MAXPKTLEN + ((IP_HL(oip) - 5) << 2)) {
2701 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
2708 len = fin->fin_dlen - ICMPERR_ICMPHLEN;
2709 if ((len <= 0) || ((IP_HL(oip) << 2) > len)) {
2710 DT2(iss_icmp_len, fr_info_t *, fin, struct ip*, oip);
2711 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_1);
2716 * Is the buffer big enough for all of it ? It's the size of the IP
2717 * header claimed in the encapsulated part which is of concern. It
2718 * may be too big to be in this buffer but not so big that it's
2719 * outside the ICMP packet, leading to TCP deref's causing problems.
2720 * This is possible because we don't know how big oip_hl is when we
2721 * do the pullup early in ipf_check() and thus can't guarantee it is
2729 # if defined(MENTAT)
2730 if ((char *)oip + len > (char *)m->b_wptr) {
2731 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_2);
2735 if ((char *)oip + len > (char *)fin->fin_ip + m->m_len) {
2736 SBUMPDX(ipf_state_stats, iss_icmp_short, iss_icmp_short_3);
2743 bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
2746 * in the IPv4 case we must zero the i6addr union otherwise
2747 * the IP6_EQ and IP6_NEQ macros produce the wrong results because
2748 * of the 'junk' in the unused part of the union
2750 bzero((char *)&src, sizeof(src));
2751 bzero((char *)&dst, sizeof(dst));
2754 * we make an fin entry to be able to feed it to
2755 * matchsrcdst note that not all fields are encessary
2756 * but this is the cleanest way. Note further we fill
2757 * in fin_mp such that if someone uses it we'll get
2758 * a kernel panic. ipf_matchsrcdst does not use this.
2760 * watch out here, as ip is in host order and oip in network
2761 * order. Any change we make must be undone afterwards, like
2764 savelen = oip->ip_len;
2765 oip->ip_len = htons(len);
2767 ofin.fin_flx = FI_NOCKSUM;
2770 ofin.fin_m = NULL; /* if dereferenced, panic XXX */
2771 ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
2772 (void) ipf_makefrip(IP_HL(oip) << 2, oip, &ofin);
2773 ofin.fin_ifp = fin->fin_ifp;
2774 ofin.fin_out = !fin->fin_out;
2776 hv = (pr = oip->ip_p);
2777 src.in4 = oip->ip_src;
2778 hv += src.in4.s_addr;
2779 dst.in4 = oip->ip_dst;
2780 hv += dst.in4.s_addr;
2783 * Reset the short and bad flag here because in ipf_matchsrcdst()
2784 * the flags for the current packet (fin_flx) are compared against
2785 * those for the existing session.
2787 ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
2790 * Put old values of ip_len back as we don't know
2791 * if we have to forward the packet or process it again.
2793 oip->ip_len = savelen;
2799 * an ICMP error can only be generated as a result of an
2800 * ICMP query, not as the response on an ICMP error
2802 * XXX theoretically ICMP_ECHOREP and the other reply's are
2803 * ICMP query's as well, but adding them here seems strange XXX
2805 if ((ofin.fin_flx & FI_ICMPERR) != 0) {
2806 DT1(iss_icmp_icmperr, fr_info_t *, &ofin);
2807 SBUMP(ipf_state_stats.iss_icmp_icmperr);
2812 * perform a lookup of the ICMP packet in the state table
2814 icmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2815 hv += icmp->icmp_id;
2816 hv = DOUBLE_HASH(hv);
2818 READ_ENTER(&softc->ipf_state);
2819 for (isp = &softs->ipf_state_table[hv];
2820 ((is = *isp) != NULL); ) {
2821 isp = &is->is_hnext;
2822 if ((is->is_p != pr) || (is->is_v != 4))
2824 if (is->is_pass & FR_NOICMPERR)
2827 is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2829 if ((is != NULL) && !ipf_allowstateicmp(fin, is, &src))
2832 RWLOCK_EXIT(&softc->ipf_state);
2833 SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_1);
2839 SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_2);
2843 tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2845 hv += tcp->th_dport;;
2846 hv += tcp->th_sport;;
2847 hv = DOUBLE_HASH(hv);
2849 READ_ENTER(&softc->ipf_state);
2850 for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
2851 isp = &is->is_hnext;
2853 * Only allow this icmp though if the
2854 * encapsulated packet was allowed through the
2855 * other way around. Note that the minimal amount
2856 * of info present does not allow for checking against
2857 * tcp internals such as seq and ack numbers. Only the
2858 * ports are known to be present and can be even if the
2859 * short flag is set.
2861 if ((is->is_p == pr) && (is->is_v == 4) &&
2862 (is = ipf_matchsrcdst(&ofin, is, &src, &dst,
2863 tcp, FI_ICMPCMP))) {
2864 if (ipf_allowstateicmp(fin, is, &src) == 0)
2868 RWLOCK_EXIT(&softc->ipf_state);
2869 SBUMPDX(ipf_state_stats, iss_icmp_miss, iss_icmp_miss_3);
2874 /* ------------------------------------------------------------------------ */
2875 /* Function: ipf_allowstateicmp */
2876 /* Returns: int - 1 = packet denied, 0 = packet allowed */
2877 /* Parameters: fin(I) - pointer to packet information */
2878 /* is(I) - pointer to state table entry */
2879 /* src(I) - source address to check permission for */
2881 /* For an ICMP packet that has so far matched a state table entry, check if */
2882 /* there are any further refinements that might mean we want to block this */
2883 /* packet. This code isn't specific to either IPv4 or IPv6. */
2884 /* ------------------------------------------------------------------------ */
2886 ipf_allowstateicmp(fin, is, src)
2891 ipf_main_softc_t *softc = fin->fin_main_soft;
2892 ipf_state_softc_t *softs = softc->ipf_state_soft;
2901 if (fr != NULL && fr->fr_icmpgrp != NULL) {
2902 savefr = fin->fin_fr;
2903 fin->fin_fr = fr->fr_icmpgrp->fg_start;
2905 ipass = ipf_scanlist(fin, softc->ipf_pass);
2906 fin->fin_fr = savefr;
2907 if (FR_ISBLOCK(ipass)) {
2908 SBUMPD(ipf_state_stats, iss_icmp_headblock);
2914 * i : the index of this packet (the icmp unreachable)
2915 * oi : the index of the original packet found in the
2916 * icmp header (i.e. the packet causing this icmp)
2917 * backward : original packet was backward compared to
2920 backward = IP6_NEQ(&is->is_src, src);
2921 fin->fin_rev = !backward;
2922 i = (!backward << 1) + fin->fin_out;
2923 oi = (backward << 1) + !fin->fin_out;
2925 if (is->is_pass & FR_NOICMPERR) {
2926 SBUMPD(ipf_state_stats, iss_icmp_banned);
2929 if (is->is_icmppkts[i] > is->is_pkts[oi]) {
2930 SBUMPD(ipf_state_stats, iss_icmp_toomany);
2934 DT2(iss_icmp_hits, fr_info_t *, fin, ipstate_t *, is);
2935 SBUMP(ipf_state_stats.iss_icmp_hits);
2936 is->is_icmppkts[i]++;
2939 * we deliberately do not touch the timeouts
2940 * for the accompanying state table entry.
2941 * It remains to be seen if that is correct. XXX
2947 /* ------------------------------------------------------------------------ */
2948 /* Function: ipf_ipsmove */
2950 /* Parameters: is(I) - pointer to state table entry */
2951 /* hv(I) - new hash value for state table entry */
2952 /* Write Locks: ipf_state */
2954 /* Move a state entry from one position in the hash table to another. */
2955 /* ------------------------------------------------------------------------ */
2957 ipf_ipsmove(softs, is, hv)
2958 ipf_state_softc_t *softs;
2967 /* TRACE is, is_hv, hvm */
2970 * Remove the hash from the old location...
2972 isp = is->is_phnext;
2974 is->is_hnext->is_phnext = isp;
2975 *isp = is->is_hnext;
2976 if (softs->ipf_state_table[hvm] == NULL)
2977 softs->ipf_state_stats.iss_inuse--;
2978 softs->ipf_state_stats.iss_bucketlen[hvm]--;
2981 * ...and put the hash in the new one.
2983 hvm = DOUBLE_HASH(hv);
2986 /* TRACE is, hv, is_hv, hvm */
2988 isp = &softs->ipf_state_table[hvm];
2990 (*isp)->is_phnext = &is->is_hnext;
2992 softs->ipf_state_stats.iss_inuse++;
2993 softs->ipf_state_stats.iss_bucketlen[hvm]++;
2994 is->is_phnext = isp;
2995 is->is_hnext = *isp;
3000 /* ------------------------------------------------------------------------ */
3001 /* Function: ipf_state_lookup */
3002 /* Returns: ipstate_t* - NULL == no matching state found, */
3003 /* else pointer to state information is returned */
3004 /* Parameters: fin(I) - pointer to packet information */
3005 /* tcp(I) - pointer to TCP/UDP header. */
3006 /* ifqp(O) - pointer for storing tailq timeout */
3008 /* Search the state table for a matching entry to the packet described by */
3009 /* the contents of *fin. For certain protocols, when a match is found the */
3010 /* timeout queue is also selected and stored in ifpq if it is non-NULL. */
3012 /* If we return NULL then no lock on ipf_state is held. */
3013 /* If we return non-null then a read-lock on ipf_state is held. */
3014 /* ------------------------------------------------------------------------ */
3016 ipf_state_lookup(fin, tcp, ifqp)
3021 ipf_main_softc_t *softc = fin->fin_main_soft;
3022 ipf_state_softc_t *softs = softc->ipf_state_soft;
3023 u_int hv, hvm, pr, v, tryagain;
3024 ipstate_t *is, **isp;
3025 u_short dport, sport;
3034 ic = (struct icmp *)tcp;
3035 hv = (pr = fin->fin_fi.fi_p);
3036 src = fin->fin_fi.fi_src;
3037 dst = fin->fin_fi.fi_dst;
3038 hv += src.in4.s_addr;
3039 hv += dst.in4.s_addr;
3041 v = fin->fin_fi.fi_v;
3044 hv += fin->fin_fi.fi_src.i6[1];
3045 hv += fin->fin_fi.fi_src.i6[2];
3046 hv += fin->fin_fi.fi_src.i6[3];
3048 if ((fin->fin_p == IPPROTO_ICMPV6) &&
3049 IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
3050 hv -= dst.in4.s_addr;
3052 hv += fin->fin_fi.fi_dst.i6[1];
3053 hv += fin->fin_fi.fi_dst.i6[2];
3054 hv += fin->fin_fi.fi_dst.i6[3];
3059 (fin->fin_flx & (FI_MULTICAST|FI_BROADCAST|FI_MBCAST))) {
3060 if (fin->fin_out == 0) {
3061 hv -= src.in4.s_addr;
3063 hv -= dst.in4.s_addr;
3067 /* TRACE fin_saddr, fin_daddr, hv */
3070 * Search the hash table for matching packet header info.
3075 case IPPROTO_ICMPV6 :
3078 if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
3079 (ic->icmp_type == ICMP6_ECHO_REPLY)) {
3083 READ_ENTER(&softc->ipf_state);
3085 hvm = DOUBLE_HASH(hv);
3086 for (isp = &softs->ipf_state_table[hvm];
3087 ((is = *isp) != NULL); ) {
3088 isp = &is->is_hnext;
3089 if ((is->is_p != pr) || (is->is_v != v))
3091 is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3093 ipf_matchicmpqueryreply(v, &is->is_icmp,
3094 ic, fin->fin_rev)) {
3096 ifq = &softs->ipf_state_icmpacktq;
3098 ifq = &softs->ipf_state_icmptq;
3104 if ((tryagain != 0) && !(is->is_flags & SI_W_DADDR)) {
3105 hv += fin->fin_fi.fi_src.i6[0];
3106 hv += fin->fin_fi.fi_src.i6[1];
3107 hv += fin->fin_fi.fi_src.i6[2];
3108 hv += fin->fin_fi.fi_src.i6[3];
3109 ipf_ipsmove(softs, is, hv);
3110 MUTEX_DOWNGRADE(&softc->ipf_state);
3114 RWLOCK_EXIT(&softc->ipf_state);
3117 * No matching icmp state entry. Perhaps this is a
3118 * response to another state entry.
3120 * XXX With some ICMP6 packets, the "other" address is already
3121 * in the packet, after the ICMP6 header, and this could be
3122 * used in place of the multicast address. However, taking
3123 * advantage of this requires some significant code changes
3124 * to handle the specific types where that is the case.
3126 if ((softs->ipf_state_stats.iss_wild != 0) &&
3127 ((fin->fin_flx & FI_NOWILD) == 0) &&
3128 (v == 6) && (tryagain == 0)) {
3129 hv -= fin->fin_fi.fi_src.i6[0];
3130 hv -= fin->fin_fi.fi_src.i6[1];
3131 hv -= fin->fin_fi.fi_src.i6[2];
3132 hv -= fin->fin_fi.fi_src.i6[3];
3134 WRITE_ENTER(&softc->ipf_state);
3138 is = ipf_checkicmp6matchingstate(fin);
3148 hv = DOUBLE_HASH(hv);
3149 READ_ENTER(&softc->ipf_state);
3150 for (isp = &softs->ipf_state_table[hv];
3151 ((is = *isp) != NULL); ) {
3152 isp = &is->is_hnext;
3153 if ((is->is_p != pr) || (is->is_v != v))
3155 is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3157 (ic->icmp_id == is->is_icmp.ici_id) &&
3158 ipf_matchicmpqueryreply(v, &is->is_icmp,
3159 ic, fin->fin_rev)) {
3161 ifq = &softs->ipf_state_icmpacktq;
3163 ifq = &softs->ipf_state_icmptq;
3168 RWLOCK_EXIT(&softc->ipf_state);
3175 sport = htons(fin->fin_data[0]);
3177 dport = htons(fin->fin_data[1]);
3181 READ_ENTER(&softc->ipf_state);
3183 hvm = DOUBLE_HASH(hv);
3187 for (isp = &softs->ipf_state_table[hvm];
3188 ((is = *isp) != NULL); ) {
3189 isp = &is->is_hnext;
3190 if ((is->is_p != pr) || (is->is_v != v))
3192 fin->fin_flx &= ~FI_OOW;
3193 is = ipf_matchsrcdst(fin, is, &src, &dst, tcp, FI_CMP);
3195 if (pr == IPPROTO_TCP) {
3196 if (!ipf_state_tcp(softc, softs, fin,
3198 oow |= fin->fin_flx & FI_OOW;
3207 !(is->is_flags & (SI_CLONE|SI_WILDP|SI_WILDA))) {
3210 ipf_ipsmove(softs, is, hv);
3211 MUTEX_DOWNGRADE(&softc->ipf_state);
3215 RWLOCK_EXIT(&softc->ipf_state);
3217 if ((softs->ipf_state_stats.iss_wild != 0) &&
3218 ((fin->fin_flx & FI_NOWILD) == 0)) {
3219 if (tryagain == 0) {
3222 } else if (tryagain == 1) {
3223 hv = fin->fin_fi.fi_p;
3225 * If we try to pretend this is a reply to a
3226 * multicast/broadcast packet then we need to
3227 * exclude part of the address from the hash
3230 if (fin->fin_out == 0) {
3231 hv += src.in4.s_addr;
3233 hv += dst.in4.s_addr;
3239 if (tryagain <= 2) {
3240 WRITE_ENTER(&softc->ipf_state);
3244 fin->fin_flx |= oow;
3250 if (GRE_REV(gre->gr_flags) == 1) {
3257 hvm = DOUBLE_HASH(hv);
3258 READ_ENTER(&softc->ipf_state);
3259 for (isp = &softs->ipf_state_table[hvm];
3260 ((is = *isp) != NULL); ) {
3261 isp = &is->is_hnext;
3262 if ((is->is_p != pr) || (is->is_v != v))
3264 is = ipf_matchsrcdst(fin, is, &src, &dst, NULL, FI_CMP);
3266 ifq = &softs->ipf_state_iptq;
3271 RWLOCK_EXIT(&softc->ipf_state);
3277 if (((is->is_sti.tqe_flags & TQE_RULEBASED) != 0) &&
3278 (is->is_tqehead[fin->fin_rev] != NULL))
3279 ifq = is->is_tqehead[fin->fin_rev];
3280 if (ifq != NULL && ifqp != NULL)
3283 SBUMP(ipf_state_stats.iss_lookup_miss);
3289 /* ------------------------------------------------------------------------ */
3290 /* Function: ipf_state_check */
3291 /* Returns: frentry_t* - NULL == search failed, */
3292 /* else pointer to rule for matching state */
3293 /* Parameters: fin(I) - pointer to packet information */
3294 /* passp(I) - pointer to filtering result flags */
3296 /* Check if a packet is associated with an entry in the state table. */
3297 /* ------------------------------------------------------------------------ */
3299 ipf_state_check(fin, passp)
3303 ipf_main_softc_t *softc = fin->fin_main_soft;
3304 ipf_state_softc_t *softs = softc->ipf_state_soft;
3313 if (softs->ipf_state_lock || (softs->ipf_state_list == NULL))
3316 if (fin->fin_flx & (FI_SHORT|FI_FRAGBODY|FI_BAD)) {
3317 SBUMPD(ipf_state_stats, iss_check_bad);
3321 if ((fin->fin_flx & FI_TCPUDP) ||
3322 (fin->fin_fi.fi_p == IPPROTO_ICMP)
3324 || (fin->fin_fi.fi_p == IPPROTO_ICMPV6)
3333 * Search the hash table for matching packet header info.
3335 is = ipf_state_lookup(fin, tcp, &ifq);
3340 case IPPROTO_ICMPV6 :
3343 if (fin->fin_v == 6) {
3344 is = ipf_checkicmp6matchingstate(fin);
3352 * No matching icmp state entry. Perhaps this is a
3353 * response to another state entry.
3355 is = ipf_checkicmpmatchingstate(fin);
3362 if (is->is_pass & FR_NEWISN) {
3363 if (fin->fin_out == 0)
3364 ipf_fixinisn(fin, is);
3365 else if (fin->fin_out == 1)
3366 ipf_fixoutisn(fin, is);
3371 ifq = &softs->ipf_state_udpacktq;
3373 ifq = &softs->ipf_state_udptq;
3377 SBUMP(ipf_state_stats.iss_check_miss);
3383 if ((fin->fin_out == 0) && (fr->fr_nattag.ipt_num[0] != 0)) {
3384 if (fin->fin_nattag == NULL) {
3385 RWLOCK_EXIT(&softc->ipf_state);
3386 SBUMPD(ipf_state_stats, iss_check_notag);
3389 if (ipf_matchtag(&fr->fr_nattag, fin->fin_nattag)!=0) {
3390 RWLOCK_EXIT(&softc->ipf_state);
3391 SBUMPD(ipf_state_stats, iss_check_nattag);
3395 (void) strncpy(fin->fin_group, FR_NAME(fr, fr_group),
3397 fin->fin_icode = fr->fr_icode;
3400 fin->fin_rule = is->is_rulen;
3404 * If this packet is a fragment and the rule says to track fragments,
3405 * then create a new fragment cache entry.
3407 if ((fin->fin_flx & FI_FRAG) && FR_ISPASS(is->is_pass))
3408 (void) ipf_frag_new(softc, fin, is->is_pass);
3411 * For TCP packets, ifq == NULL. For all others, check if this new
3412 * queue is different to the last one it was on and move it if so.
3415 if ((tqe->tqe_flags & TQE_RULEBASED) != 0)
3416 ifq = is->is_tqehead[fin->fin_rev];
3418 MUTEX_ENTER(&is->is_lock);
3421 ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq, ifq);
3423 inout = (fin->fin_rev << 1) + fin->fin_out;
3424 is->is_pkts[inout]++;
3425 is->is_bytes[inout] += fin->fin_plen;
3426 fin->fin_pktnum = is->is_pkts[inout] + is->is_icmppkts[inout];
3428 MUTEX_EXIT(&is->is_lock);
3432 if (is->is_flags & IS_STATESYNC)
3433 ipf_sync_update(softc, SMC_STATE, fin, is->is_sync);
3435 RWLOCK_EXIT(&softc->ipf_state);
3437 SBUMP(ipf_state_stats.iss_hits);
3439 fin->fin_dif = &is->is_dif;
3440 fin->fin_tif = &is->is_tifs[fin->fin_rev];
3441 fin->fin_flx |= FI_STATE;
3442 if ((pass & FR_LOGFIRST) != 0)
3443 pass &= ~(FR_LOGFIRST|FR_LOG);
3449 /* ------------------------------------------------------------------------ */
3450 /* Function: ipf_fixoutisn */
3452 /* Parameters: fin(I) - pointer to packet information */
3453 /* is(I) - pointer to master state structure */
3455 /* Called only for outbound packets, adjusts the sequence number and the */
3456 /* TCP checksum to match that change. */
3457 /* ------------------------------------------------------------------------ */
3459 ipf_fixoutisn(fin, is)
3469 if ((is->is_flags & IS_ISNSYN) != 0) {
3470 if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3471 seq = ntohl(tcp->th_seq);
3472 seq += is->is_isninc[0];
3473 tcp->th_seq = htonl(seq);
3474 ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3477 if ((is->is_flags & IS_ISNACK) != 0) {
3478 if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3479 seq = ntohl(tcp->th_seq);
3480 seq += is->is_isninc[1];
3481 tcp->th_seq = htonl(seq);
3482 ipf_fix_outcksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3488 /* ------------------------------------------------------------------------ */
3489 /* Function: ipf_fixinisn */
3491 /* Parameters: fin(I) - pointer to packet information */
3492 /* is(I) - pointer to master state structure */
3494 /* Called only for inbound packets, adjusts the acknowledge number and the */
3495 /* TCP checksum to match that change. */
3496 /* ------------------------------------------------------------------------ */
3498 ipf_fixinisn(fin, is)
3508 if ((is->is_flags & IS_ISNSYN) != 0) {
3509 if ((rev == 1) && (fin->fin_cksum < FI_CK_L4PART)) {
3510 ack = ntohl(tcp->th_ack);
3511 ack -= is->is_isninc[0];
3512 tcp->th_ack = htonl(ack);
3513 ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[0], 0);
3516 if ((is->is_flags & IS_ISNACK) != 0) {
3517 if ((rev == 0) && (fin->fin_cksum < FI_CK_L4PART)) {
3518 ack = ntohl(tcp->th_ack);
3519 ack -= is->is_isninc[1];
3520 tcp->th_ack = htonl(ack);
3521 ipf_fix_incksum(0, &tcp->th_sum, is->is_sumd[1], 0);
3527 /* ------------------------------------------------------------------------ */
3528 /* Function: ipf_state_sync */
3530 /* Parameters: softc(I) - pointer to soft context main structure */
3531 /* ifp(I) - pointer to interface */
3533 /* Walk through all state entries and if an interface pointer match is */
3534 /* found then look it up again, based on its name in case the pointer has */
3535 /* changed since last time. */
3537 /* If ifp is passed in as being non-null then we are only doing updates for */
3538 /* existing, matching, uses of it. */
3539 /* ------------------------------------------------------------------------ */
3541 ipf_state_sync(softc, ifp)
3542 ipf_main_softc_t *softc;
3545 ipf_state_softc_t *softs = softc->ipf_state_soft;
3549 if (softc->ipf_running <= 0)
3552 WRITE_ENTER(&softc->ipf_state);
3554 if (softc->ipf_running <= 0) {
3555 RWLOCK_EXIT(&softc->ipf_state);
3559 for (is = softs->ipf_state_list; is; is = is->is_next) {
3561 * Look up all the interface names in the state entry.
3563 for (i = 0; i < 4; i++) {
3564 if (ifp == NULL || ifp == is->is_ifp[i])
3565 is->is_ifp[i] = ipf_resolvenic(softc,
3570 RWLOCK_EXIT(&softc->ipf_state);
3574 /* ------------------------------------------------------------------------ */
3575 /* Function: ipf_state_del */
3576 /* Returns: int - 0 = deleted, else refernce count on active struct */
3577 /* Parameters: softc(I) - pointer to soft context main structure */
3578 /* is(I) - pointer to state structure to delete */
3579 /* why(I) - if not 0, log reason why it was deleted */
3580 /* Write Locks: ipf_state */
3582 /* Deletes a state entry from the enumerated list as well as the hash table */
3583 /* and timeout queue lists. Make adjustments to hash table statistics and */
3584 /* global counters as required. */
3585 /* ------------------------------------------------------------------------ */
3587 ipf_state_del(softc, is, why)
3588 ipf_main_softc_t *softc;
3592 ipf_state_softc_t *softs = softc->ipf_state_soft;
3597 * Since we want to delete this, remove it from the state table,
3598 * where it can be found & used, first.
3600 if (is->is_phnext != NULL) {
3601 *is->is_phnext = is->is_hnext;
3602 if (is->is_hnext != NULL)
3603 is->is_hnext->is_phnext = is->is_phnext;
3604 if (softs->ipf_state_table[is->is_hv] == NULL)
3605 softs->ipf_state_stats.iss_inuse--;
3606 softs->ipf_state_stats.iss_bucketlen[is->is_hv]--;
3608 is->is_phnext = NULL;
3609 is->is_hnext = NULL;
3614 * Because ipf_state_stats.iss_wild is a count of entries in the state
3615 * table that have wildcard flags set, only decerement it once
3618 if (is->is_flags & (SI_WILDP|SI_WILDA)) {
3619 if (!(is->is_flags & SI_CLONED)) {
3620 ATOMIC_DECL(softs->ipf_state_stats.iss_wild);
3622 is->is_flags &= ~(SI_WILDP|SI_WILDA);
3626 * Next, remove it from the timeout queue it is in.
3628 if (is->is_sti.tqe_ifq != NULL)
3629 ipf_deletequeueentry(&is->is_sti);
3632 * If it is still in use by something else, do not go any further,
3633 * but note that at this point it is now an orphan. How can this
3634 * be? ipf_state_flush() calls ipf_delete() directly because it wants
3635 * to empty the table out and if something has a hold on a state
3636 * entry (such as ipfstat), it'll do the deref path that'll bring
3637 * us back here to do the real delete & free.
3639 MUTEX_ENTER(&is->is_lock);
3640 if (is->is_me != NULL) {
3645 if (is->is_ref > 1) {
3650 MUTEX_EXIT(&is->is_lock);
3652 softs->ipf_state_stats.iss_orphan++;
3655 MUTEX_EXIT(&is->is_lock);
3660 if (fr->fr_srctrack.ht_max_nodes != 0) {
3661 (void) ipf_ht_node_del(&fr->fr_srctrack,
3662 is->is_family, &is->is_src);
3668 if (is->is_tqehead[0] != NULL) {
3669 if (ipf_deletetimeoutqueue(is->is_tqehead[0]) == 0)
3670 ipf_freetimeoutqueue(softc, is->is_tqehead[0]);
3672 if (is->is_tqehead[1] != NULL) {
3673 if (ipf_deletetimeoutqueue(is->is_tqehead[1]) == 0)
3674 ipf_freetimeoutqueue(softc, is->is_tqehead[1]);
3678 ipf_sync_del_state(softc->ipf_sync_soft, is->is_sync);
3681 * Now remove it from the linked list of known states
3683 if (is->is_pnext != NULL) {
3684 *is->is_pnext = is->is_next;
3686 if (is->is_next != NULL)
3687 is->is_next->is_pnext = is->is_pnext;
3689 is->is_pnext = NULL;
3693 if (softs->ipf_state_logging != 0 && why != 0)
3694 ipf_state_log(softc, is, why);
3696 if (is->is_p == IPPROTO_TCP)
3697 softs->ipf_state_stats.iss_fin++;
3699 softs->ipf_state_stats.iss_expire++;
3701 softs->ipf_state_stats.iss_orphan--;
3705 (void) ipf_derefrule(softc, &fr);
3708 softs->ipf_state_stats.iss_active_proto[is->is_p]--;
3710 MUTEX_DESTROY(&is->is_lock);
3712 softs->ipf_state_stats.iss_active--;
3718 /* ------------------------------------------------------------------------ */
3719 /* Function: ipf_state_expire */
3721 /* Parameters: softc(I) - pointer to soft context main structure */
3723 /* Slowly expire held state for thingslike UDP and ICMP. The algorithm */
3724 /* used here is to keep the queue sorted with the oldest things at the top */
3725 /* and the youngest at the bottom. So if the top one doesn't need to be */
3726 /* expired then neither will any under it. */
3727 /* ------------------------------------------------------------------------ */
3729 ipf_state_expire(softc)
3730 ipf_main_softc_t *softc;
3732 ipf_state_softc_t *softs = softc->ipf_state_soft;
3733 ipftq_t *ifq, *ifqnext;
3734 ipftqent_t *tqe, *tqn;
3739 WRITE_ENTER(&softc->ipf_state);
3740 for (ifq = softs->ipf_state_tcptq; ifq != NULL; ifq = ifq->ifq_next)
3741 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3742 if (tqe->tqe_die > softc->ipf_ticks)
3744 tqn = tqe->tqe_next;
3745 is = tqe->tqe_parent;
3746 ipf_state_del(softc, is, ISL_EXPIRE);
3749 for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3750 ifqnext = ifq->ifq_next;
3752 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3753 if (tqe->tqe_die > softc->ipf_ticks)
3755 tqn = tqe->tqe_next;
3756 is = tqe->tqe_parent;
3757 ipf_state_del(softc, is, ISL_EXPIRE);
3761 for (ifq = softs->ipf_state_usertq; ifq != NULL; ifq = ifqnext) {
3762 ifqnext = ifq->ifq_next;
3764 if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
3765 (ifq->ifq_ref == 0)) {
3766 ipf_freetimeoutqueue(softc, ifq);
3770 if (softs->ipf_state_doflush) {
3771 (void) ipf_state_flush(softc, 2, 0);
3772 softs->ipf_state_doflush = 0;
3773 softs->ipf_state_wm_last = softc->ipf_ticks;
3776 RWLOCK_EXIT(&softc->ipf_state);
3781 /* ------------------------------------------------------------------------ */
3782 /* Function: ipf_state_flush */
3783 /* Returns: int - 0 == success, -1 == failure */
3784 /* Parameters: softc(I) - pointer to soft context main structure */
3785 /* which(I) - which flush action to perform */
3786 /* proto(I) - which protocol to flush (0 == ALL) */
3787 /* Write Locks: ipf_state */
3789 /* Flush state tables. Three actions currently defined: */
3790 /* which == 0 : flush all state table entries */
3791 /* which == 1 : flush TCP connections which have started to close but are */
3792 /* stuck for some reason. */
3793 /* which == 2 : flush TCP connections which have been idle for a long time, */
3794 /* starting at > 4 days idle and working back in successive half-*/
3795 /* days to at most 12 hours old. If this fails to free enough */
3796 /* slots then work backwards in half hour slots to 30 minutes. */
3797 /* If that too fails, then work backwards in 30 second intervals */
3798 /* for the last 30 minutes to at worst 30 seconds idle. */
3799 /* ------------------------------------------------------------------------ */
3801 ipf_state_flush(softc, which, proto)
3802 ipf_main_softc_t *softc;
3805 ipf_state_softc_t *softs = softc->ipf_state_soft;
3806 ipftqent_t *tqe, *tqn;
3807 ipstate_t *is, **isp;
3819 SBUMP(ipf_state_stats.iss_flush_all);
3821 * Style 0 flush removes everything...
3823 for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3824 if ((proto != 0) && (is->is_v != proto)) {
3828 if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3836 SBUMP(ipf_state_stats.iss_flush_closing);
3838 * Since we're only interested in things that are closing,
3839 * we can start with the appropriate timeout queue.
3841 for (ifq = softs->ipf_state_tcptq + IPF_TCPS_CLOSE_WAIT;
3842 ifq != NULL; ifq = ifq->ifq_next) {
3844 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3845 tqn = tqe->tqe_next;
3846 is = tqe->tqe_parent;
3847 if (is->is_p != IPPROTO_TCP)
3849 if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3855 * Also need to look through the user defined queues.
3857 for (ifq = softs->ipf_state_usertq; ifq != NULL;
3858 ifq = ifq->ifq_next) {
3859 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); ) {
3860 tqn = tqe->tqe_next;
3861 is = tqe->tqe_parent;
3862 if (is->is_p != IPPROTO_TCP)
3865 if ((is->is_state[0] > IPF_TCPS_ESTABLISHED) &&
3866 (is->is_state[1] > IPF_TCPS_ESTABLISHED)) {
3867 if (ipf_state_del(softc, is,
3879 * Args 5-11 correspond to flushing those particular states
3880 * for TCP connections.
3882 case IPF_TCPS_CLOSE_WAIT :
3883 case IPF_TCPS_FIN_WAIT_1 :
3884 case IPF_TCPS_CLOSING :
3885 case IPF_TCPS_LAST_ACK :
3886 case IPF_TCPS_FIN_WAIT_2 :
3887 case IPF_TCPS_TIME_WAIT :
3888 case IPF_TCPS_CLOSED :
3889 SBUMP(ipf_state_stats.iss_flush_queue);
3890 tqn = softs->ipf_state_tcptq[which].ifq_head;
3891 while (tqn != NULL) {
3893 tqn = tqe->tqe_next;
3894 is = tqe->tqe_parent;
3895 if (ipf_state_del(softc, is, ISL_FLUSH) == 0)
3904 SBUMP(ipf_state_stats.iss_flush_state);
3906 * Take a large arbitrary number to mean the number of seconds
3907 * for which which consider to be the maximum value we'll allow
3908 * the expiration to be.
3910 which = IPF_TTLVAL(which);
3911 for (isp = &softs->ipf_state_list; ((is = *isp) != NULL); ) {
3912 if ((proto == 0) || (is->is_v == proto)) {
3913 if (softc->ipf_ticks - is->is_touched > which) {
3914 if (ipf_state_del(softc, is,
3931 SBUMP(ipf_state_stats.iss_flush_timeout);
3933 * Asked to remove inactive entries because the table is full, try
3934 * again, 3 times, if first attempt failed with a different criteria
3935 * each time. The order tried in must be in decreasing age.
3936 * Another alternative is to implement random drop and drop N entries
3937 * at random until N have been freed up.
3939 if (softc->ipf_ticks - softs->ipf_state_wm_last >
3940 softs->ipf_state_wm_freq) {
3941 removed = ipf_queueflush(softc, ipf_state_flush_entry,
3942 softs->ipf_state_tcptq,
3943 softs->ipf_state_usertq,
3944 &softs->ipf_state_stats.iss_active,
3945 softs->ipf_state_size,
3946 softs->ipf_state_wm_low);
3947 softs->ipf_state_wm_last = softc->ipf_ticks;
3955 /* ------------------------------------------------------------------------ */
3956 /* Function: ipf_state_flush_entry */
3957 /* Returns: int - 0 = entry deleted, else not deleted */
3958 /* Parameters: softc(I) - pointer to soft context main structure */
3959 /* entry(I) - pointer to state structure to delete */
3960 /* Write Locks: ipf_state */
3962 /* This function is a stepping stone between ipf_queueflush() and */
3963 /* ipf_state_del(). It is used so we can provide a uniform interface via */
3964 /* the ipf_queueflush() function. */
3965 /* ------------------------------------------------------------------------ */
3967 ipf_state_flush_entry(softc, entry)
3968 ipf_main_softc_t *softc;
3971 return ipf_state_del(softc, entry, ISL_FLUSH);
3975 /* ------------------------------------------------------------------------ */
3976 /* Function: ipf_tcp_age */
3977 /* Returns: int - 1 == state transition made, 0 == no change (rejected) */
3978 /* Parameters: tqe(I) - pointer to timeout queue information */
3979 /* fin(I) - pointer to packet information */
3980 /* tqtab(I) - TCP timeout queue table this is in */
3981 /* flags(I) - flags from state/NAT entry */
3982 /* ok(I) - can we advance state */
3984 /* Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29: */
3986 /* - (try to) base state transitions on real evidence only, */
3987 /* i.e. packets that are sent and have been received by ipfilter; */
3988 /* diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used. */
3990 /* - deal with half-closed connections correctly; */
3992 /* - store the state of the source in state[0] such that ipfstat */
3993 /* displays the state as source/dest instead of dest/source; the calls */
3994 /* to ipf_tcp_age have been changed accordingly. */
3996 /* Internal Parameters: */
3998 /* state[0] = state of source (host that initiated connection) */
3999 /* state[1] = state of dest (host that accepted the connection) */
4001 /* dir == 0 : a packet from source to dest */
4002 /* dir == 1 : a packet from dest to source */
4004 /* A typical procession for a connection is as follows: */
4006 /* +--------------+-------------------+ */
4007 /* | Side '0' | Side '1' | */
4008 /* +--------------+-------------------+ */
4009 /* | 0 -> 1 (SYN) | | */
4010 /* | | 0 -> 2 (SYN-ACK) | */
4011 /* | 1 -> 3 (ACK) | | */
4012 /* | | 2 -> 4 (ACK-PUSH) | */
4013 /* | 3 -> 4 (ACK) | | */
4015 /* | | 4 -> 6 (FIN-ACK) | */
4016 /* | 4 -> 5 (ACK) | | */
4017 /* | | 6 -> 6 (ACK-PUSH) | */
4018 /* | 5 -> 5 (ACK) | | */
4019 /* | 5 -> 8 (FIN) | | */
4020 /* | | 6 -> 10 (ACK) | */
4021 /* +--------------+-------------------+ */
4023 /* Locking: it is assumed that the parent of the tqe structure is locked. */
4024 /* ------------------------------------------------------------------------ */
4026 ipf_tcp_age(tqe, fin, tqtab, flags, ok)
4032 ipf_main_softc_t *softc = fin->fin_main_soft;
4033 int dlen, ostate, nstate, rval, dir;
4041 tcpflags = tcp->th_flags;
4042 dlen = fin->fin_dlen - (TCP_OFF(tcp) << 2);
4043 ostate = tqe->tqe_state[1 - dir];
4044 nstate = tqe->tqe_state[dir];
4046 if (tcpflags & TH_RST) {
4047 if (!(tcpflags & TH_PUSH) && !dlen)
4048 nstate = IPF_TCPS_CLOSED;
4050 nstate = IPF_TCPS_CLOSE_WAIT;
4052 if (ostate <= IPF_TCPS_ESTABLISHED) {
4053 tqe->tqe_state[1 - dir] = IPF_TCPS_CLOSE_WAIT;
4059 case IPF_TCPS_LISTEN: /* 0 */
4060 if ((tcpflags & TH_OPENING) == TH_OPENING) {
4062 * 'dir' received an S and sends SA in
4063 * response, LISTEN -> SYN_RECEIVED
4065 nstate = IPF_TCPS_SYN_RECEIVED;
4067 } else if ((tcpflags & TH_OPENING) == TH_SYN) {
4068 /* 'dir' sent S, LISTEN -> SYN_SENT */
4069 nstate = IPF_TCPS_SYN_SENT;
4073 * the next piece of code makes it possible to get
4074 * already established connections into the state table
4075 * after a restart or reload of the filter rules; this
4076 * does not work when a strict 'flags S keep state' is
4077 * used for tcp connections of course
4079 if (((flags & IS_TCPFSM) == 0) &&
4080 ((tcpflags & TH_ACKMASK) == TH_ACK)) {
4082 * we saw an A, guess 'dir' is in ESTABLISHED
4087 case IPF_TCPS_LISTEN :
4088 case IPF_TCPS_SYN_RECEIVED :
4089 nstate = IPF_TCPS_HALF_ESTAB;
4092 case IPF_TCPS_HALF_ESTAB :
4093 case IPF_TCPS_ESTABLISHED :
4094 nstate = IPF_TCPS_ESTABLISHED;
4102 * TODO: besides regular ACK packets we can have other
4103 * packets as well; it is yet to be determined how we
4104 * should initialize the states in those cases
4108 case IPF_TCPS_SYN_SENT: /* 1 */
4109 if ((tcpflags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
4111 * A retransmitted SYN packet. We do not reset
4112 * the timeout here to ipf_tcptimeout because a
4113 * connection connect timeout does not renew
4114 * after every packet that is sent. We need to
4115 * set rval so as to indicate the packet has
4116 * passed the check for its flags being valid
4117 * in the TCP FSM. Setting rval to 2 has the
4118 * result of not resetting the timeout.
4121 } else if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) ==
4124 * we see an A from 'dir' which is in SYN_SENT
4125 * state: 'dir' sent an A in response to an SA
4126 * which it received, SYN_SENT -> ESTABLISHED
4128 nstate = IPF_TCPS_ESTABLISHED;
4130 } else if (tcpflags & TH_FIN) {
4132 * we see an F from 'dir' which is in SYN_SENT
4133 * state and wants to close its side of the
4134 * connection; SYN_SENT -> FIN_WAIT_1
4136 nstate = IPF_TCPS_FIN_WAIT_1;
4138 } else if ((tcpflags & TH_OPENING) == TH_OPENING) {
4140 * we see an SA from 'dir' which is already in
4141 * SYN_SENT state, this means we have a
4142 * simultaneous open; SYN_SENT -> SYN_RECEIVED
4144 nstate = IPF_TCPS_SYN_RECEIVED;
4149 case IPF_TCPS_SYN_RECEIVED: /* 2 */
4150 if ((tcpflags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
4152 * we see an A from 'dir' which was in
4153 * SYN_RECEIVED state so it must now be in
4154 * established state, SYN_RECEIVED ->
4157 nstate = IPF_TCPS_ESTABLISHED;
4159 } else if ((tcpflags & ~(TH_ECN|TH_CWR)) ==
4162 * We see an SA from 'dir' which is already in
4163 * SYN_RECEIVED state.
4166 } else if (tcpflags & TH_FIN) {
4168 * we see an F from 'dir' which is in
4169 * SYN_RECEIVED state and wants to close its
4170 * side of the connection; SYN_RECEIVED ->
4173 nstate = IPF_TCPS_FIN_WAIT_1;
4178 case IPF_TCPS_HALF_ESTAB: /* 3 */
4179 if (tcpflags & TH_FIN) {
4180 nstate = IPF_TCPS_FIN_WAIT_1;
4182 } else if ((tcpflags & TH_ACKMASK) == TH_ACK) {
4184 * If we've picked up a connection in mid
4185 * flight, we could be looking at a follow on
4186 * packet from the same direction as the one
4187 * that created this state. Recognise it but
4188 * do not advance the entire connection's
4193 case IPF_TCPS_LISTEN :
4194 case IPF_TCPS_SYN_SENT :
4195 case IPF_TCPS_SYN_RECEIVED :
4198 case IPF_TCPS_HALF_ESTAB :
4199 case IPF_TCPS_ESTABLISHED :
4200 nstate = IPF_TCPS_ESTABLISHED;
4209 case IPF_TCPS_ESTABLISHED: /* 4 */
4211 if (tcpflags & TH_FIN) {
4213 * 'dir' closed its side of the connection;
4214 * this gives us a half-closed connection;
4215 * ESTABLISHED -> FIN_WAIT_1
4217 if (ostate == IPF_TCPS_FIN_WAIT_1) {
4218 nstate = IPF_TCPS_CLOSING;
4220 nstate = IPF_TCPS_FIN_WAIT_1;
4222 } else if (tcpflags & TH_ACK) {
4224 * an ACK, should we exclude other flags here?
4226 if (ostate == IPF_TCPS_FIN_WAIT_1) {
4228 * We know the other side did an active
4229 * close, so we are ACKing the recvd
4230 * FIN packet (does the window matching
4231 * code guarantee this?) and go into
4232 * CLOSE_WAIT state; this gives us a
4233 * half-closed connection
4235 nstate = IPF_TCPS_CLOSE_WAIT;
4236 } else if (ostate < IPF_TCPS_CLOSE_WAIT) {
4238 * still a fully established
4239 * connection reset timeout
4241 nstate = IPF_TCPS_ESTABLISHED;
4246 case IPF_TCPS_CLOSE_WAIT: /* 5 */
4248 if (tcpflags & TH_FIN) {
4250 * application closed and 'dir' sent a FIN,
4251 * we're now going into LAST_ACK state
4253 nstate = IPF_TCPS_LAST_ACK;
4256 * we remain in CLOSE_WAIT because the other
4257 * side has closed already and we did not
4258 * close our side yet; reset timeout
4260 nstate = IPF_TCPS_CLOSE_WAIT;
4264 case IPF_TCPS_FIN_WAIT_1: /* 6 */
4266 if ((tcpflags & TH_ACK) &&
4267 ostate > IPF_TCPS_CLOSE_WAIT) {
4269 * if the other side is not active anymore
4270 * it has sent us a FIN packet that we are
4271 * ack'ing now with an ACK; this means both
4272 * sides have now closed the connection and
4273 * we go into TIME_WAIT
4276 * XXX: how do we know we really are ACKing
4277 * the FIN packet here? does the window code
4280 nstate = IPF_TCPS_LAST_ACK;
4283 * we closed our side of the connection
4284 * already but the other side is still active
4285 * (ESTABLISHED/CLOSE_WAIT); continue with
4286 * this half-closed connection
4288 nstate = IPF_TCPS_FIN_WAIT_1;
4292 case IPF_TCPS_CLOSING: /* 7 */
4293 if ((tcpflags & (TH_FIN|TH_ACK)) == TH_ACK) {
4294 nstate = IPF_TCPS_TIME_WAIT;
4299 case IPF_TCPS_LAST_ACK: /* 8 */
4300 if (tcpflags & TH_ACK) {
4304 * we cannot detect when we go out of LAST_ACK state
4305 * to CLOSED because that is based on the reception
4306 * of ACK packets; ipfilter can only detect that a
4307 * packet has been sent by a host
4311 case IPF_TCPS_FIN_WAIT_2: /* 9 */
4315 case IPF_TCPS_TIME_WAIT: /* 10 */
4316 /* we're in 2MSL timeout now */
4317 if (ostate == IPF_TCPS_LAST_ACK) {
4318 nstate = IPF_TCPS_CLOSED;
4325 case IPF_TCPS_CLOSED: /* 11 */
4330 #if !defined(_KERNEL)
4338 * If rval == 2 then do not update the queue position, but treat the
4339 * packet as being ok.
4343 else if (rval == 1) {
4345 tqe->tqe_state[dir] = nstate;
4346 if ((tqe->tqe_flags & TQE_RULEBASED) == 0)
4347 ipf_movequeue(softc->ipf_ticks, tqe, tqe->tqe_ifq,
4355 /* ------------------------------------------------------------------------ */
4356 /* Function: ipf_state_log */
4358 /* Parameters: softc(I) - pointer to soft context main structure */
4359 /* is(I) - pointer to state structure */
4360 /* type(I) - type of log entry to create */
4362 /* Creates a state table log entry using the state structure and type info. */
4363 /* passed in. Log packet/byte counts, source/destination address and other */
4364 /* protocol specific information. */
4365 /* ------------------------------------------------------------------------ */
4367 ipf_state_log(softc, is, type)
4368 ipf_main_softc_t *softc;
4379 * Copy information out of the ipstate_t structure and into the
4380 * structure used for logging.
4382 ipsl.isl_type = type;
4383 ipsl.isl_pkts[0] = is->is_pkts[0] + is->is_icmppkts[0];
4384 ipsl.isl_bytes[0] = is->is_bytes[0];
4385 ipsl.isl_pkts[1] = is->is_pkts[1] + is->is_icmppkts[1];
4386 ipsl.isl_bytes[1] = is->is_bytes[1];
4387 ipsl.isl_pkts[2] = is->is_pkts[2] + is->is_icmppkts[2];
4388 ipsl.isl_bytes[2] = is->is_bytes[2];
4389 ipsl.isl_pkts[3] = is->is_pkts[3] + is->is_icmppkts[3];
4390 ipsl.isl_bytes[3] = is->is_bytes[3];
4391 ipsl.isl_src = is->is_src;
4392 ipsl.isl_dst = is->is_dst;
4393 ipsl.isl_p = is->is_p;
4394 ipsl.isl_v = is->is_v;
4395 ipsl.isl_flags = is->is_flags;
4396 ipsl.isl_tag = is->is_tag;
4397 ipsl.isl_rulen = is->is_rulen;
4398 (void) strncpy(ipsl.isl_group, is->is_group, FR_GROUPLEN);
4400 if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
4401 ipsl.isl_sport = is->is_sport;
4402 ipsl.isl_dport = is->is_dport;
4403 if (ipsl.isl_p == IPPROTO_TCP) {
4404 ipsl.isl_state[0] = is->is_state[0];
4405 ipsl.isl_state[1] = is->is_state[1];
4407 } else if (ipsl.isl_p == IPPROTO_ICMP) {
4408 ipsl.isl_itype = is->is_icmp.ici_type;
4409 } else if (ipsl.isl_p == IPPROTO_ICMPV6) {
4410 ipsl.isl_itype = is->is_icmp.ici_type;
4412 ipsl.isl_ps.isl_filler[0] = 0;
4413 ipsl.isl_ps.isl_filler[1] = 0;
4417 sizes[0] = sizeof(ipsl);
4420 (void) ipf_log_items(softc, IPL_LOGSTATE, NULL, items, sizes, types, 1);
4426 /* ------------------------------------------------------------------------ */
4427 /* Function: ipf_checkicmp6matchingstate */
4428 /* Returns: ipstate_t* - NULL == no match found, */
4429 /* else pointer to matching state entry */
4430 /* Parameters: fin(I) - pointer to packet information */
4431 /* Locks: NULL == no locks, else Read Lock on ipf_state */
4433 /* If we've got an ICMPv6 error message, using the information stored in */
4434 /* the ICMPv6 packet, look for a matching state table entry. */
4435 /* ------------------------------------------------------------------------ */
4437 ipf_checkicmp6matchingstate(fin)
4440 ipf_main_softc_t *softc = fin->fin_main_soft;
4441 ipf_state_softc_t *softs = softc->ipf_state_soft;
4442 struct icmp6_hdr *ic6, *oic;
4443 ipstate_t *is, **isp;
4444 u_short sport, dport;
4456 * Does it at least have the return (basic) IP header ?
4457 * Is it an actual recognised ICMP error type?
4458 * Only a basic IP header (no options) should be with
4459 * an ICMP error header.
4461 if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN) ||
4462 !(fin->fin_flx & FI_ICMPERR)) {
4463 SBUMPD(ipf_state_stats, iss_icmp_bad);
4468 type = ic6->icmp6_type;
4470 oip6 = (ip6_t *)((char *)ic6 + ICMPERR_ICMPHLEN);
4471 if (fin->fin_plen < sizeof(*oip6)) {
4472 SBUMPD(ipf_state_stats, iss_icmp_short);
4476 bcopy((char *)fin, (char *)&ofin, sizeof(*fin));
4478 ofin.fin_ifp = fin->fin_ifp;
4479 ofin.fin_out = !fin->fin_out;
4480 ofin.fin_m = NULL; /* if dereferenced, panic XXX */
4481 ofin.fin_mp = NULL; /* if dereferenced, panic XXX */
4484 * We make a fin entry to be able to feed it to
4485 * matchsrcdst. Note that not all fields are necessary
4486 * but this is the cleanest way. Note further we fill
4487 * in fin_mp such that if someone uses it we'll get
4488 * a kernel panic. ipf_matchsrcdst does not use this.
4490 * watch out here, as ip is in host order and oip6 in network
4491 * order. Any change we make must be undone afterwards.
4493 savelen = oip6->ip6_plen;
4494 oip6->ip6_plen = htons(fin->fin_dlen - ICMPERR_ICMPHLEN);
4495 ofin.fin_flx = FI_NOCKSUM;
4496 ofin.fin_ip = (ip_t *)oip6;
4497 (void) ipf_makefrip(sizeof(*oip6), (ip_t *)oip6, &ofin);
4498 ofin.fin_flx &= ~(FI_BAD|FI_SHORT);
4499 oip6->ip6_plen = savelen;
4503 * an ICMP error can never generate an ICMP error in response.
4505 if (ofin.fin_flx & FI_ICMPERR) {
4506 DT1(iss_icmp6_icmperr, fr_info_t *, &ofin);
4507 SBUMP(ipf_state_stats.iss_icmp6_icmperr);
4511 if (oip6->ip6_nxt == IPPROTO_ICMPV6) {
4514 * an ICMP error can only be generated as a result of an
4515 * ICMP query, not as the response on an ICMP error
4517 * XXX theoretically ICMP_ECHOREP and the other reply's are
4518 * ICMP query's as well, but adding them here seems strange XXX
4520 if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK)) {
4521 DT1(iss_icmp6_notinfo, fr_info_t *, &ofin);
4522 SBUMP(ipf_state_stats.iss_icmp6_notinfo);
4527 * perform a lookup of the ICMP packet in the state table
4529 hv = (pr = oip6->ip6_nxt);
4530 src.in6 = oip6->ip6_src;
4531 hv += src.in4.s_addr;
4532 dst.in6 = oip6->ip6_dst;
4533 hv += dst.in4.s_addr;
4534 hv += oic->icmp6_id;
4535 hv += oic->icmp6_seq;
4536 hv = DOUBLE_HASH(hv);
4538 READ_ENTER(&softc->ipf_state);
4539 for (isp = &softs->ipf_state_table[hv];
4540 ((is = *isp) != NULL); ) {
4542 isp = &is->is_hnext;
4543 if ((is->is_p == pr) &&
4544 !(is->is_pass & FR_NOICMPERR) &&
4545 (oic->icmp6_id == ic->ici_id) &&
4546 (oic->icmp6_seq == ic->ici_seq) &&
4547 (is = ipf_matchsrcdst(&ofin, is, &src,
4548 &dst, NULL, FI_ICMPCMP))) {
4550 * in the state table ICMP query's are stored
4551 * with the type of the corresponding ICMP
4552 * response. Correct here
4554 if (((ic->ici_type == ICMP6_ECHO_REPLY) &&
4555 (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
4556 (ic->ici_type - 1 == oic->icmp6_type )) {
4557 if (!ipf_allowstateicmp(fin, is, &src))
4562 RWLOCK_EXIT(&softc->ipf_state);
4563 SBUMPD(ipf_state_stats, iss_icmp6_miss);
4567 hv = (pr = oip6->ip6_nxt);
4568 src.in6 = oip6->ip6_src;
4573 dst.in6 = oip6->ip6_dst;
4581 switch (oip6->ip6_nxt)
4585 tcp = (tcphdr_t *)(oip6 + 1);
4586 dport = tcp->th_dport;
4587 sport = tcp->th_sport;
4592 case IPPROTO_ICMPV6 :
4593 oic = (struct icmp6_hdr *)(oip6 + 1);
4594 hv += oic->icmp6_id;
4595 hv += oic->icmp6_seq;
4602 hv = DOUBLE_HASH(hv);
4604 READ_ENTER(&softc->ipf_state);
4605 for (isp = &softs->ipf_state_table[hv]; ((is = *isp) != NULL); ) {
4606 isp = &is->is_hnext;
4608 * Only allow this icmp though if the
4609 * encapsulated packet was allowed through the
4610 * other way around. Note that the minimal amount
4611 * of info present does not allow for checking against
4612 * tcp internals such as seq and ack numbers.
4614 if ((is->is_p != pr) || (is->is_v != 6) ||
4615 (is->is_pass & FR_NOICMPERR))
4617 is = ipf_matchsrcdst(&ofin, is, &src, &dst, tcp, FI_ICMPCMP);
4618 if ((is != NULL) && (ipf_allowstateicmp(fin, is, &src) == 0))
4621 RWLOCK_EXIT(&softc->ipf_state);
4622 SBUMPD(ipf_state_stats, iss_icmp_miss);
4628 /* ------------------------------------------------------------------------ */
4629 /* Function: ipf_sttab_init */
4631 /* Parameters: softc(I) - pointer to soft context main structure */
4632 /* tqp(I) - pointer to an array of timeout queues for TCP */
4634 /* Initialise the array of timeout queues for TCP. */
4635 /* ------------------------------------------------------------------------ */
4637 ipf_sttab_init(softc, tqp)
4638 ipf_main_softc_t *softc;
4643 for (i = IPF_TCP_NSTATES - 1; i >= 0; i--) {
4644 IPFTQ_INIT(&tqp[i], 0, "ipftq tcp tab");
4645 tqp[i].ifq_next = tqp + i + 1;
4647 tqp[IPF_TCP_NSTATES - 1].ifq_next = NULL;
4648 tqp[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcpclosed;
4649 tqp[IPF_TCPS_LISTEN].ifq_ttl = softc->ipf_tcptimeout;
4650 tqp[IPF_TCPS_SYN_SENT].ifq_ttl = softc->ipf_tcpsynsent;
4651 tqp[IPF_TCPS_SYN_RECEIVED].ifq_ttl = softc->ipf_tcpsynrecv;
4652 tqp[IPF_TCPS_ESTABLISHED].ifq_ttl = softc->ipf_tcpidletimeout;
4653 tqp[IPF_TCPS_CLOSE_WAIT].ifq_ttl = softc->ipf_tcphalfclosed;
4654 tqp[IPF_TCPS_FIN_WAIT_1].ifq_ttl = softc->ipf_tcphalfclosed;
4655 tqp[IPF_TCPS_CLOSING].ifq_ttl = softc->ipf_tcptimeout;
4656 tqp[IPF_TCPS_LAST_ACK].ifq_ttl = softc->ipf_tcplastack;
4657 tqp[IPF_TCPS_FIN_WAIT_2].ifq_ttl = softc->ipf_tcpclosewait;
4658 tqp[IPF_TCPS_TIME_WAIT].ifq_ttl = softc->ipf_tcptimewait;
4659 tqp[IPF_TCPS_HALF_ESTAB].ifq_ttl = softc->ipf_tcptimeout;
4663 /* ------------------------------------------------------------------------ */
4664 /* Function: ipf_sttab_destroy */
4666 /* Parameters: tqp(I) - pointer to an array of timeout queues for TCP */
4668 /* Do whatever is necessary to "destroy" each of the entries in the array */
4669 /* of timeout queues for TCP. */
4670 /* ------------------------------------------------------------------------ */
4672 ipf_sttab_destroy(tqp)
4677 for (i = IPF_TCP_NSTATES - 1; i >= 0; i--)
4678 MUTEX_DESTROY(&tqp[i].ifq_lock);
4682 /* ------------------------------------------------------------------------ */
4683 /* Function: ipf_state_deref */
4685 /* Parameters: softc(I) - pointer to soft context main structure */
4686 /* isp(I) - pointer to pointer to state table entry */
4688 /* Decrement the reference counter for this state table entry and free it */
4689 /* if there are no more things using it. */
4691 /* This function is only called when cleaning up after increasing is_ref by */
4692 /* one earlier in the 'code path' so if is_ref is 1 when entering, we do */
4693 /* have an orphan, otherwise not. However there is a possible race between */
4694 /* the entry being deleted via flushing with an ioctl call (that calls the */
4695 /* delete function directly) and the tail end of packet processing so we */
4696 /* need to grab is_lock before doing the check to synchronise the two code */
4699 /* When operating in userland (ipftest), we have no timers to clear a state */
4700 /* entry. Therefore, we make a few simple tests before deleting an entry */
4701 /* outright. We compare states on each side looking for a combination of */
4702 /* TIME_WAIT (should really be FIN_WAIT_2?) and LAST_ACK. Then we factor */
4703 /* in packet direction with the interface list to make sure we don't */
4704 /* prematurely delete an entry on a final inbound packet that's we're also */
4705 /* supposed to route elsewhere. */
4707 /* Internal parameters: */
4708 /* state[0] = state of source (host that initiated connection) */
4709 /* state[1] = state of dest (host that accepted the connection) */
4711 /* dir == 0 : a packet from source to dest */
4712 /* dir == 1 : a packet from dest to source */
4713 /* ------------------------------------------------------------------------ */
4715 ipf_state_deref(softc, isp)
4716 ipf_main_softc_t *softc;
4719 ipstate_t *is = *isp;
4724 MUTEX_ENTER(&is->is_lock);
4725 if (is->is_ref > 1) {
4727 MUTEX_EXIT(&is->is_lock);
4729 if ((is->is_sti.tqe_state[0] > IPF_TCPS_ESTABLISHED) ||
4730 (is->is_sti.tqe_state[1] > IPF_TCPS_ESTABLISHED)) {
4731 ipf_state_del(softc, is, ISL_EXPIRE);
4736 MUTEX_EXIT(&is->is_lock);
4738 WRITE_ENTER(&softc->ipf_state);
4739 ipf_state_del(softc, is, ISL_ORPHAN);
4740 RWLOCK_EXIT(&softc->ipf_state);
4744 /* ------------------------------------------------------------------------ */
4745 /* Function: ipf_state_setqueue */
4747 /* Parameters: softc(I) - pointer to soft context main structure */
4748 /* is(I) - pointer to state structure */
4749 /* rev(I) - forward(0) or reverse(1) direction */
4750 /* Locks: ipf_state (read or write) */
4752 /* Put the state entry on its default queue entry, using rev as a helped in */
4753 /* determining which queue it should be placed on. */
4754 /* ------------------------------------------------------------------------ */
4756 ipf_state_setqueue(softc, is, rev)
4757 ipf_main_softc_t *softc;
4761 ipf_state_softc_t *softs = softc->ipf_state_soft;
4762 ipftq_t *oifq, *nifq;
4764 if ((is->is_sti.tqe_flags & TQE_RULEBASED) != 0)
4765 nifq = is->is_tqehead[rev];
4773 case IPPROTO_ICMPV6 :
4775 nifq = &softs->ipf_state_icmpacktq;
4777 nifq = &softs->ipf_state_icmptq;
4782 nifq = &softs->ipf_state_icmpacktq;
4784 nifq = &softs->ipf_state_icmptq;
4787 nifq = softs->ipf_state_tcptq + is->is_state[rev];
4792 nifq = &softs->ipf_state_udpacktq;
4794 nifq = &softs->ipf_state_udptq;
4798 nifq = &softs->ipf_state_iptq;
4803 oifq = is->is_sti.tqe_ifq;
4805 * If it's currently on a timeout queue, move it from one queue to
4806 * another, else put it on the end of the newly determined queue.
4809 ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq, nifq);
4811 ipf_queueappend(softc->ipf_ticks, &is->is_sti, nifq, is);
4816 /* ------------------------------------------------------------------------ */
4817 /* Function: ipf_state_iter */
4818 /* Returns: int - 0 == success, else error */
4819 /* Parameters: softc(I) - pointer to main soft context */
4820 /* token(I) - pointer to ipftoken structure */
4821 /* itp(I) - pointer to ipfgeniter structure */
4822 /* obj(I) - pointer to data description structure */
4824 /* This function handles the SIOCGENITER ioctl for the state tables and */
4825 /* walks through the list of entries in the state table list (softs->ipf_state_list.) */
4826 /* ------------------------------------------------------------------------ */
4828 ipf_state_iter(softc, token, itp, obj)
4829 ipf_main_softc_t *softc;
4834 ipf_state_softc_t *softs = softc->ipf_state_soft;
4835 ipstate_t *is, *next, zero;
4838 if (itp->igi_data == NULL) {
4843 if (itp->igi_nitems < 1) {
4848 if (itp->igi_type != IPFGENITER_STATE) {
4853 is = token->ipt_data;
4854 if (is == (void *)-1) {
4860 obj->ipfo_type = IPFOBJ_IPSTATE;
4861 obj->ipfo_size = sizeof(ipstate_t);
4863 READ_ENTER(&softc->ipf_state);
4865 is = token->ipt_data;
4867 next = softs->ipf_state_list;
4873 * If we find a state entry to use, bump its reference count so that
4874 * it can be used for is_next when we come back.
4877 MUTEX_ENTER(&next->is_lock);
4879 MUTEX_EXIT(&next->is_lock);
4880 token->ipt_data = next;
4882 bzero(&zero, sizeof(zero));
4884 token->ipt_data = NULL;
4886 if (next->is_next == NULL)
4887 ipf_token_mark_complete(token);
4889 RWLOCK_EXIT(&softc->ipf_state);
4891 obj->ipfo_ptr = itp->igi_data;
4892 error = ipf_outobjk(softc, obj, next);
4894 ipf_state_deref(softc, &is);
4900 /* ------------------------------------------------------------------------ */
4901 /* Function: ipf_state_gettable */
4902 /* Returns: int - 0 = success, else error */
4903 /* Parameters: softc(I) - pointer to main soft context */
4904 /* softs(I) - pointer to state context structure */
4905 /* data(I) - pointer to ioctl data */
4907 /* This function handles ioctl requests for tables of state information. */
4908 /* At present the only table it deals with is the hash bucket statistics. */
4909 /* ------------------------------------------------------------------------ */
4911 ipf_state_gettable(softc, softs, data)
4912 ipf_main_softc_t *softc;
4913 ipf_state_softc_t *softs;
4919 error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
4923 if (table.ita_type != IPFTABLE_BUCKETS) {
4928 error = COPYOUT(softs->ipf_state_stats.iss_bucketlen, table.ita_table,
4929 softs->ipf_state_size * sizeof(u_int));
4938 /* ------------------------------------------------------------------------ */
4939 /* Function: ipf_state_setpending */
4941 /* Parameters: softc(I) - pointer to main soft context */
4942 /* is(I) - pointer to state structure */
4943 /* Locks: ipf_state (read or write) */
4945 /* Put the state entry on to the pending queue - this queue has a very */
4946 /* short lifetime where items are put that can't be deleted straight away */
4947 /* because of locking issues but we want to delete them ASAP, anyway. */
4948 /* ------------------------------------------------------------------------ */
4950 ipf_state_setpending(softc, is)
4951 ipf_main_softc_t *softc;
4954 ipf_state_softc_t *softs = softc->ipf_state_soft;
4957 oifq = is->is_sti.tqe_ifq;
4959 ipf_movequeue(softc->ipf_ticks, &is->is_sti, oifq,
4960 &softs->ipf_state_pending);
4962 ipf_queueappend(softc->ipf_ticks, &is->is_sti,
4963 &softs->ipf_state_pending, is);
4965 MUTEX_ENTER(&is->is_lock);
4966 if (is->is_me != NULL) {
4971 MUTEX_EXIT(&is->is_lock);
4975 /* ------------------------------------------------------------------------ */
4976 /* Function: ipf_state_matchflush */
4978 /* Parameters: softc(I) - pointer to main soft context */
4979 /* data(I) - pointer to state structure */
4980 /* Locks: ipf_state (read or write) */
4982 /* Flush all entries from the list of state entries that match the */
4983 /* properties in the array loaded. */
4984 /* ------------------------------------------------------------------------ */
4986 ipf_state_matchflush(softc, data)
4987 ipf_main_softc_t *softc;
4990 ipf_state_softc_t *softs = softc->ipf_state_soft;
4991 int *array, flushed, error;
4992 ipstate_t *state, *statenext;
4995 error = ipf_matcharray_load(softc, data, &obj, &array);
5001 for (state = softs->ipf_state_list; state != NULL; state = statenext) {
5002 statenext = state->is_next;
5003 if (ipf_state_matcharray(state, array, softc->ipf_ticks) == 0) {
5004 ipf_state_del(softc, state, ISL_FLUSH);
5009 obj.ipfo_retval = flushed;
5010 error = BCOPYOUT(&obj, data, sizeof(obj));
5012 KFREES(array, array[0] * sizeof(*array));
5018 /* ------------------------------------------------------------------------ */
5019 /* Function: ipf_state_matcharray */
5020 /* Returns: int - 0 = no match, 1 = match */
5021 /* Parameters: state(I) - pointer to state structure */
5022 /* array(I) - pointer to ipf matching expression */
5023 /* ticks(I) - current value of ipfilter tick timer */
5024 /* Locks: ipf_state (read or write) */
5026 /* Compare a state entry with the match array passed in and return a value */
5027 /* to indicate whether or not the matching was successful. */
5028 /* ------------------------------------------------------------------------ */
5030 ipf_state_matcharray(state, array, ticks)
5035 int i, n, *x, rv, p;
5042 for (; n > 0; x += 3 + x[3], rv = 0) {
5045 if (x[0] == IPF_EXP_END)
5049 * If we need to match the protocol and that doesn't match,
5050 * don't even both with the instruction array.
5052 p = e->ipfe_cmd >> 16;
5053 if ((p != 0) && (p != state->is_p))
5056 switch (e->ipfe_cmd)
5058 case IPF_EXP_IP_PR :
5059 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5060 rv |= (state->is_p == e->ipfe_arg0[i]);
5064 case IPF_EXP_IP_SRCADDR :
5065 if (state->is_v != 4)
5067 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5068 rv |= ((state->is_saddr &
5069 e->ipfe_arg0[i * 2 + 1]) ==
5070 e->ipfe_arg0[i * 2]);
5074 case IPF_EXP_IP_DSTADDR :
5075 if (state->is_v != 4)
5077 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5078 rv |= ((state->is_daddr &
5079 e->ipfe_arg0[i * 2 + 1]) ==
5080 e->ipfe_arg0[i * 2]);
5084 case IPF_EXP_IP_ADDR :
5085 if (state->is_v != 4)
5087 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5088 rv |= ((state->is_saddr &
5089 e->ipfe_arg0[i * 2 + 1]) ==
5090 e->ipfe_arg0[i * 2]) ||
5092 e->ipfe_arg0[i * 2 + 1]) ==
5093 e->ipfe_arg0[i * 2]);
5098 case IPF_EXP_IP6_SRCADDR :
5099 if (state->is_v != 6)
5101 for (i = 0; !rv && i < x[3]; i++) {
5102 rv |= IP6_MASKEQ(&state->is_src.in6,
5103 &e->ipfe_arg0[i * 8 + 4],
5104 &e->ipfe_arg0[i * 8]);
5108 case IPF_EXP_IP6_DSTADDR :
5109 if (state->is_v != 6)
5111 for (i = 0; !rv && i < x[3]; i++) {
5112 rv |= IP6_MASKEQ(&state->is_dst.in6,
5113 &e->ipfe_arg0[i * 8 + 4],
5114 &e->ipfe_arg0[i * 8]);
5118 case IPF_EXP_IP6_ADDR :
5119 if (state->is_v != 6)
5121 for (i = 0; !rv && i < x[3]; i++) {
5122 rv |= IP6_MASKEQ(&state->is_src.in6,
5123 &e->ipfe_arg0[i * 8 + 4],
5124 &e->ipfe_arg0[i * 8]) ||
5125 IP6_MASKEQ(&state->is_dst.in6,
5126 &e->ipfe_arg0[i * 8 + 4],
5127 &e->ipfe_arg0[i * 8]);
5132 case IPF_EXP_UDP_PORT :
5133 case IPF_EXP_TCP_PORT :
5134 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5135 rv |= (state->is_sport == e->ipfe_arg0[i]) ||
5136 (state->is_dport == e->ipfe_arg0[i]);
5140 case IPF_EXP_UDP_SPORT :
5141 case IPF_EXP_TCP_SPORT :
5142 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5143 rv |= (state->is_sport == e->ipfe_arg0[i]);
5147 case IPF_EXP_UDP_DPORT :
5148 case IPF_EXP_TCP_DPORT :
5149 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5150 rv |= (state->is_dport == e->ipfe_arg0[i]);
5154 case IPF_EXP_TCP_STATE :
5155 for (i = 0; !rv && i < e->ipfe_narg; i++) {
5156 rv |= (state->is_state[0] == e->ipfe_arg0[i]) ||
5157 (state->is_state[1] == e->ipfe_arg0[i]);
5161 case IPF_EXP_IDLE_GT :
5162 rv |= (ticks - state->is_touched > e->ipfe_arg0[0]);
5167 * Factor in doing a negative match.
5179 /* ------------------------------------------------------------------------ */
5180 /* Function: ipf_state_settimeout */
5181 /* Returns: int 0 = success, else failure */
5182 /* Parameters: softc(I) - pointer to main soft context */
5183 /* t(I) - pointer to tuneable being changed */
5184 /* p(I) - pointer to the new value */
5186 /* Sets a timeout value for one of the many timeout queues. We find the */
5187 /* correct queue using a somewhat manual process of comparing the timeout */
5188 /* names for each specific value available and calling ipf_apply_timeout on */
5189 /* that queue so that all of the items on it are updated accordingly. */
5190 /* ------------------------------------------------------------------------ */
5192 ipf_state_settimeout(softc, t, p)
5193 struct ipf_main_softc_s *softc;
5197 ipf_state_softc_t *softs = softc->ipf_state_soft;
5200 * In case there is nothing to do...
5202 if (*t->ipft_pint == p->ipftu_int)
5205 if (!strncmp(t->ipft_name, "tcp_", 4))
5206 return ipf_settimeout_tcp(t, p, softs->ipf_state_tcptq);
5208 if (!strcmp(t->ipft_name, "udp_timeout")) {
5209 ipf_apply_timeout(&softs->ipf_state_udptq, p->ipftu_int);
5210 } else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
5211 ipf_apply_timeout(&softs->ipf_state_udpacktq, p->ipftu_int);
5212 } else if (!strcmp(t->ipft_name, "icmp_timeout")) {
5213 ipf_apply_timeout(&softs->ipf_state_icmptq, p->ipftu_int);
5214 } else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
5215 ipf_apply_timeout(&softs->ipf_state_icmpacktq, p->ipftu_int);
5216 } else if (!strcmp(t->ipft_name, "ip_timeout")) {
5217 ipf_apply_timeout(&softs->ipf_state_iptq, p->ipftu_int);
5224 * Update the tuneable being set.
5226 *t->ipft_pint = p->ipftu_int;
5232 /* ------------------------------------------------------------------------ */
5233 /* Function: ipf_state_rehash */
5234 /* Returns: int 0 = success, else failure */
5235 /* Parameters: softc(I) - pointer to main soft context */
5236 /* t(I) - pointer to tuneable being changed */
5237 /* p(I) - pointer to the new value */
5239 /* To change the size of the state hash table at runtime, a new table has */
5240 /* to be allocated and then all of the existing entries put in it, bumping */
5241 /* up the bucketlength for it as we go along. */
5242 /* ------------------------------------------------------------------------ */
5244 ipf_state_rehash(softc, t, p)
5245 ipf_main_softc_t *softc;
5249 ipf_state_softc_t *softs = softc->ipf_state_soft;
5250 ipstate_t **newtab, *is;
5257 newsize = p->ipftu_int;
5259 * In case there is nothing to do...
5261 if (newsize == softs->ipf_state_size)
5264 KMALLOCS(newtab, ipstate_t **, newsize * sizeof(ipstate_t *));
5265 if (newtab == NULL) {
5270 KMALLOCS(bucketlens, u_int *, newsize * sizeof(u_int));
5271 if (bucketlens == NULL) {
5272 KFREES(newtab, newsize * sizeof(*softs->ipf_state_table));
5277 for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
5281 bzero((char *)newtab, newsize * sizeof(ipstate_t *));
5282 bzero((char *)bucketlens, newsize * sizeof(u_int));
5284 WRITE_ENTER(&softc->ipf_state);
5286 if (softs->ipf_state_table != NULL) {
5287 KFREES(softs->ipf_state_table,
5288 softs->ipf_state_size * sizeof(*softs->ipf_state_table));
5290 softs->ipf_state_table = newtab;
5292 if (softs->ipf_state_stats.iss_bucketlen != NULL) {
5293 KFREES(softs->ipf_state_stats.iss_bucketlen,
5294 softs->ipf_state_size * sizeof(u_int));
5296 softs->ipf_state_stats.iss_bucketlen = bucketlens;
5297 softs->ipf_state_maxbucket = maxbucket;
5298 softs->ipf_state_size = newsize;
5301 * Walk through the entire list of state table entries and put them
5302 * in the new state table, somewhere. Because we have a new table,
5303 * we need to restart the counter of how many chains are in use.
5305 softs->ipf_state_stats.iss_inuse = 0;
5306 for (is = softs->ipf_state_list; is != NULL; is = is->is_next) {
5307 is->is_hnext = NULL;
5308 is->is_phnext = NULL;
5309 hv = is->is_hv % softs->ipf_state_size;
5311 if (softs->ipf_state_table[hv] != NULL)
5312 softs->ipf_state_table[hv]->is_phnext = &is->is_hnext;
5314 softs->ipf_state_stats.iss_inuse++;
5315 is->is_phnext = softs->ipf_state_table + hv;
5316 is->is_hnext = softs->ipf_state_table[hv];
5317 softs->ipf_state_table[hv] = is;
5318 softs->ipf_state_stats.iss_bucketlen[hv]++;
5320 RWLOCK_EXIT(&softc->ipf_state);
5326 /* ------------------------------------------------------------------------ */
5327 /* Function: ipf_state_add_tq */
5328 /* Returns: ipftq_t * - NULL = failure, else pointer to new timeout */
5330 /* Parameters: softc(I) - pointer to main soft context */
5331 /* ttl(I) - pointer to the ttl for the new queue */
5333 /* Request a pointer to a timeout queue that has a ttl as given by the */
5334 /* value being passed in. The timeout queue is added tot the list of those */
5335 /* used internally for stateful filtering. */
5336 /* ------------------------------------------------------------------------ */
5338 ipf_state_add_tq(softc, ttl)
5339 ipf_main_softc_t *softc;
5342 ipf_state_softc_t *softs = softc->ipf_state_soft;
5344 return ipf_addtimeoutqueue(softc, &softs->ipf_state_usertq, ttl);
5350 * Display the built up state table rules and mapping entries.
5353 ipf_state_dump(softc, arg)
5354 ipf_main_softc_t *softc;
5357 ipf_state_softc_t *softs = arg;
5360 printf("List of active state sessions:\n");
5361 for (ips = softs->ipf_state_list; ips != NULL; )
5362 ips = printstate(ips, opts & (OPT_DEBUG|OPT_VERBOSE),