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