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