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