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