Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / contrib / ipfilter / netinet / ip_state.c
1 /*
2  * Copyright (C) 1995-2002 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * @(#)ip_state.c   1.8 6/5/96 (C) 1993-2000 Darren Reed
7  * @(#)$Id: ip_state.c,v 2.30.2.74 2002/07/27 15:58:10 darrenr Exp $
8  * $FreeBSD: src/sys/contrib/ipfilter/netinet/ip_state.c,v 1.21.2.5 2003/03/01 03:55:54 darrenr Exp $
9  * $DragonFly: src/sys/contrib/ipfilter/netinet/ip_state.c,v 1.2 2003/06/17 04:28:20 dillon Exp $
10  */
11
12 #if defined(__sgi) && (IRIX > 602)
13 # include <sys/ptimers.h>
14 #endif
15 #include <sys/errno.h>
16 #include <sys/types.h>
17 #include <sys/param.h>
18 #include <sys/file.h>
19 #if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
20     defined(_KERNEL)
21 # include "opt_ipfilter_log.h"
22 #endif
23 #if defined(_KERNEL) && defined(__FreeBSD_version) && \
24     (__FreeBSD_version >= 400000) && !defined(KLD_MODULE)
25 #include "opt_inet6.h"
26 #endif
27 #if !defined(_KERNEL) && !defined(KERNEL) && !defined(__KERNEL__)
28 # include <stdio.h>
29 # include <stdlib.h>
30 # include <string.h>
31 #else
32 # ifdef linux
33 #  include <linux/kernel.h>
34 #  include <linux/module.h>
35 # endif
36 #endif
37 #if (defined(KERNEL) || defined(_KERNEL)) && (__FreeBSD_version >= 220000)
38 # include <sys/filio.h>
39 # include <sys/fcntl.h>
40 # if (__FreeBSD_version >= 300000) && !defined(IPFILTER_LKM)
41 #  include "opt_ipfilter.h"
42 # endif
43 #else
44 # include <sys/ioctl.h>
45 #endif
46 #include <sys/time.h>
47 #ifndef linux
48 # include <sys/protosw.h>
49 #endif
50 #include <sys/socket.h>
51 #if (defined(_KERNEL) || defined(KERNEL)) && !defined(linux)
52 # include <sys/systm.h>
53 #endif
54 #if !defined(__SVR4) && !defined(__svr4__)
55 # ifndef linux
56 #  include <sys/mbuf.h>
57 # endif
58 #else
59 # include <sys/filio.h>
60 # include <sys/byteorder.h>
61 # ifdef _KERNEL
62 #  include <sys/dditypes.h>
63 # endif
64 # include <sys/stream.h>
65 # include <sys/kmem.h>
66 #endif
67
68 #include <net/if.h>
69 #ifdef sun
70 # include <net/af.h>
71 #endif
72 #include <net/route.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/tcp.h>
77 #ifndef linux
78 # include <netinet/ip_var.h>
79 # include <netinet/tcp_fsm.h>
80 #endif
81 #include <netinet/udp.h>
82 #include <netinet/ip_icmp.h>
83 #include "netinet/ip_compat.h"
84 #include <netinet/tcpip.h>
85 #include "netinet/ip_fil.h"
86 #include "netinet/ip_nat.h"
87 #include "netinet/ip_frag.h"
88 #include "netinet/ip_state.h"
89 #ifdef  USE_INET6
90 #include <netinet/icmp6.h>
91 #endif
92 #if (__FreeBSD_version >= 300000)
93 # include <sys/malloc.h>
94 # if (defined(_KERNEL) || defined(KERNEL)) && !defined(IPFILTER_LKM)
95 #  include <sys/libkern.h>
96 #  include <sys/systm.h>
97 # endif
98 #endif
99
100 static const char sccsid[] = "@(#)ip_state.c   1.8 6/5/96 (C) 1993-2000 Darren Reed";
101
102 #ifndef MIN
103 # define        MIN(a,b)        (((a)<(b))?(a):(b))
104 #endif
105
106 #define TCP_CLOSE       (TH_FIN|TH_RST)
107
108 static ipstate_t **ips_table = NULL;
109 static int      ips_num = 0;
110 static int      ips_wild = 0;
111 static ips_stat_t ips_stats;
112 #if     (SOLARIS || defined(__sgi)) && defined(_KERNEL)
113 extern  KRWLOCK_T       ipf_state, ipf_mutex;
114 extern  kmutex_t        ipf_rw;
115 #endif
116
117 #ifdef  USE_INET6
118 static frentry_t *fr_checkicmp6matchingstate __P((ip6_t *, fr_info_t *));
119 #endif
120 static int fr_matchsrcdst __P((ipstate_t *, union i6addr, union i6addr,
121                                fr_info_t *, tcphdr_t *));
122 static frentry_t *fr_checkicmpmatchingstate __P((ip_t *, fr_info_t *));
123 static int fr_matchicmpqueryreply __P((int, ipstate_t *, icmphdr_t *, int));
124 static int fr_state_flush __P((int, int));
125 static ips_stat_t *fr_statetstats __P((void));
126 static void fr_delstate __P((ipstate_t *));
127 static int fr_state_remove __P((caddr_t));
128 static void fr_ipsmove __P((ipstate_t **, ipstate_t *, u_int));
129 static int fr_tcpoptions __P((tcphdr_t *));
130 int fr_stputent __P((caddr_t));
131 int fr_stgetent __P((caddr_t));
132 void fr_stinsert __P((ipstate_t *));
133
134
135 #define FIVE_DAYS       (2 * 5 * 86400) /* 5 days: half closed session */
136
137 #define TCP_MSL 240                     /* 2 minutes */
138 u_long  fr_tcpidletimeout = FIVE_DAYS,
139         fr_tcpclosewait = 2 * TCP_MSL,
140         fr_tcplastack = 2 * TCP_MSL,
141         fr_tcptimeout = 2 * TCP_MSL,
142         fr_tcpclosed = 120,
143         fr_tcphalfclosed = 2 * 2 * 3600,    /* 2 hours */
144         fr_udptimeout = 240,
145         fr_udpacktimeout = 24,
146         fr_icmptimeout = 120,
147         fr_icmpacktimeout = 12;
148 int     fr_statemax = IPSTATE_MAX,
149         fr_statesize = IPSTATE_SIZE;
150 int     fr_state_doflush = 0,
151         fr_state_lock = 0;
152 ipstate_t *ips_list = NULL;
153
154 static  int icmpreplytype4[ICMP_MAXTYPE + 1];
155 #ifdef  USE_INET6
156 static  int icmpreplytype6[ICMP6_MAXTYPE + 1];
157 #endif
158
159 int fr_stateinit()
160 {
161         int i;
162
163         KMALLOCS(ips_table, ipstate_t **, fr_statesize * sizeof(ipstate_t *));
164         if (ips_table != NULL)
165                 bzero((char *)ips_table, fr_statesize * sizeof(ipstate_t *));
166         else
167                 return -1;
168
169         /* fill icmp reply type table */
170         for (i = 0; i <= ICMP_MAXTYPE; i++)
171                 icmpreplytype4[i] = -1;
172         icmpreplytype4[ICMP_ECHO] = ICMP_ECHOREPLY;
173         icmpreplytype4[ICMP_TSTAMP] = ICMP_TSTAMPREPLY;
174         icmpreplytype4[ICMP_IREQ] = ICMP_IREQREPLY;
175         icmpreplytype4[ICMP_MASKREQ] = ICMP_MASKREPLY;
176 #ifdef  USE_INET6
177         /* fill icmp reply type table */
178         for (i = 0; i <= ICMP6_MAXTYPE; i++)
179                 icmpreplytype6[i] = -1;
180         icmpreplytype6[ICMP6_ECHO_REQUEST] = ICMP6_ECHO_REPLY;
181         icmpreplytype6[ICMP6_MEMBERSHIP_QUERY] = ICMP6_MEMBERSHIP_REPORT;
182         icmpreplytype6[ICMP6_NI_QUERY] = ICMP6_NI_REPLY;
183         icmpreplytype6[ND_ROUTER_SOLICIT] = ND_ROUTER_ADVERT;
184         icmpreplytype6[ND_NEIGHBOR_SOLICIT] = ND_NEIGHBOR_ADVERT;
185 #endif
186
187         return 0;
188 }
189
190
191 static ips_stat_t *fr_statetstats()
192 {
193         ips_stats.iss_active = ips_num;
194         ips_stats.iss_table = ips_table;
195         ips_stats.iss_list = ips_list;
196         return &ips_stats;
197 }
198
199
200 /*
201  * flush state tables.  two actions currently defined:
202  * which == 0 : flush all state table entries
203  * which == 1 : flush TCP connections which have started to close but are
204  *              stuck for some reason.
205  * which == 2 : flush TCP connections which have been idle for a long time,
206  *              starting at > 4 days idle and working back in successive half-
207  *              days to at most 12 hours old.
208  */
209 static int fr_state_flush(which, proto)
210 int which, proto;
211 {
212         ipstate_t *is, **isp;
213 #if defined(_KERNEL) && !SOLARIS
214         int s;
215 #endif
216         int delete, removed = 0, try;
217
218         SPL_NET(s);
219         for (isp = &ips_list; (is = *isp); ) {
220                 delete = 0;
221
222                 if ((proto != 0) && (is->is_v != proto))
223                         continue;
224
225                 switch (which)
226                 {
227                 case 0 :
228                         delete = 1;
229                         break;
230                 case 1 :
231                 case 2 :
232                         if (is->is_p != IPPROTO_TCP)
233                                 break;
234                         if ((is->is_state[0] != TCPS_ESTABLISHED) ||
235                             (is->is_state[1] != TCPS_ESTABLISHED))
236                                 delete = 1;
237                         break;
238                 }
239
240                 if (delete) {
241                         if (is->is_p == IPPROTO_TCP)
242                                 ips_stats.iss_fin++;
243                         else
244                                 ips_stats.iss_expire++;
245 #ifdef  IPFILTER_LOG
246                         ipstate_log(is, ISL_FLUSH);
247 #endif
248                         fr_delstate(is);
249                         removed++;
250                 } else
251                         isp = &is->is_next;
252         }
253
254         /*
255          * Asked to remove inactive entries, try again if first attempt
256          * failed.  In this case, 86400 is half a day because the counter is
257          * activated every half second.
258          */
259         if ((which == 2) && (removed == 0)) {
260                 try = 86400;    /* half a day */
261                 for (; (try < FIVE_DAYS) && (removed == 0); try += 86400) {
262                         for (isp = &ips_list; (is = *isp); ) {
263                                 delete = 0;
264                                 if ((is->is_p == IPPROTO_TCP) &&
265                                     ((is->is_state[0] == TCPS_ESTABLISHED) ||
266                                      (is->is_state[1] == TCPS_ESTABLISHED)) &&
267                                     (is->is_age < try)) {
268                                         ips_stats.iss_fin++;
269                                         delete = 1;
270                                 } else if ((is->is_p != IPPROTO_TCP) &&
271                                            (is->is_pkts > 1)) {
272                                         ips_stats.iss_expire++;
273                                         delete = 1;
274                                 }
275                                 if (delete) {
276 #ifdef  IPFILTER_LOG
277                                         ipstate_log(is, ISL_FLUSH);
278 #endif
279                                         fr_delstate(is);
280                                         removed++;
281                                 } else
282                                         isp = &is->is_next;
283                         }
284                 }
285         }
286
287         SPL_X(s);
288         return removed;
289 }
290
291
292 static int fr_state_remove(data)
293 caddr_t data;
294 {
295         ipstate_t *sp, st;
296         int error;
297
298         sp = &st;
299         error = IRCOPYPTR(data, (caddr_t)&st, sizeof(st));
300         if (error)
301                 return EFAULT;
302
303         WRITE_ENTER(&ipf_state);
304         for (sp = ips_list; sp; sp = sp->is_next)
305                 if ((sp->is_p == st.is_p) && (sp->is_v == st.is_v) &&
306                     !bcmp((char *)&sp->is_src, (char *)&st.is_src,
307                           sizeof(st.is_src)) &&
308                     !bcmp((char *)&sp->is_dst, (char *)&st.is_dst,
309                           sizeof(st.is_dst)) &&
310                     !bcmp((char *)&sp->is_ps, (char *)&st.is_ps,
311                           sizeof(st.is_ps))) {
312 #ifdef  IPFILTER_LOG
313                         ipstate_log(sp, ISL_REMOVE);
314 #endif
315                         fr_delstate(sp);
316                         RWLOCK_EXIT(&ipf_state);
317                         return 0;
318                 }
319         RWLOCK_EXIT(&ipf_state);
320         return ESRCH;
321 }
322
323
324 int fr_state_ioctl(data, cmd, mode)
325 caddr_t data;
326 #if defined(__NetBSD__) || defined(__OpenBSD__)
327 u_long cmd;
328 #else
329 int cmd;
330 #endif
331 int mode;
332 {
333         int arg, ret, error = 0;
334
335         switch (cmd)
336         {
337         case SIOCDELST :
338                 error = fr_state_remove(data);
339                 break;
340         case SIOCIPFFL :
341                 error = IRCOPY(data, (caddr_t)&arg, sizeof(arg));
342                 if (error)
343                         break;
344                 if (arg == 0 || arg == 1) {
345                         WRITE_ENTER(&ipf_state);
346                         ret = fr_state_flush(arg, 4);
347                         RWLOCK_EXIT(&ipf_state);
348                         error = IWCOPY((caddr_t)&ret, data, sizeof(ret));
349                 } else
350                         error = EINVAL;
351                 break;
352 #ifdef USE_INET6
353         case SIOCIPFL6 :
354                 error = IRCOPY(data, (caddr_t)&arg, sizeof(arg));
355                 if (error)
356                         break;
357                 if (arg == 0 || arg == 1) {
358                         WRITE_ENTER(&ipf_state);
359                         ret = fr_state_flush(arg, 6);
360                         RWLOCK_EXIT(&ipf_state);
361                         error = IWCOPY((caddr_t)&ret, data, sizeof(ret));
362                 } else
363                         error = EINVAL;
364                 break;
365 #endif
366 #ifdef  IPFILTER_LOG
367         case SIOCIPFFB :
368                 if (!(mode & FWRITE))
369                         error = EPERM;
370                 else {
371                         int tmp;
372
373                         tmp = ipflog_clear(IPL_LOGSTATE);
374                         IWCOPY((char *)&tmp, data, sizeof(tmp));
375                 }
376                 break;
377 #endif
378         case SIOCGETFS :
379                 error = IWCOPYPTR((caddr_t)fr_statetstats(), data,
380                                   sizeof(ips_stat_t));
381                 break;
382         case FIONREAD :
383 #ifdef  IPFILTER_LOG
384                 arg = (int)iplused[IPL_LOGSTATE];
385                 error = IWCOPY((caddr_t)&arg, (caddr_t)data, sizeof(arg));
386 #endif
387                 break;
388         case SIOCSTLCK :
389                 error = fr_lock(data, &fr_state_lock);
390                 break;
391         case SIOCSTPUT :
392                 if (!fr_state_lock) {
393                         error = EACCES;
394                         break;
395                 }
396                 error = fr_stputent(data);
397                 break;
398         case SIOCSTGET :
399                 if (!fr_state_lock) {
400                         error = EACCES;
401                         break;
402                 }
403                 error = fr_stgetent(data);
404                 break;
405         default :
406                 error = EINVAL;
407                 break;
408         }
409         return error;
410 }
411
412
413 /*
414  * Copy out state information from the kernel to a user space process.
415  */
416 int fr_stgetent(data)
417 caddr_t data;
418 {
419         register ipstate_t *is, *isn;
420         ipstate_save_t ips;
421         int error;
422
423         error = IRCOPYPTR(data, (caddr_t)&ips, sizeof(ips));
424         if (error)
425                 return error;
426
427         isn = ips.ips_next;
428         if (!isn) {
429                 isn = ips_list;
430                 if (isn == NULL) {
431                         if (ips.ips_next == NULL)
432                                 return ENOENT;
433                         return 0;
434                 }
435         } else {
436                 /*
437                  * Make sure the pointer we're copying from exists in the
438                  * current list of entries.  Security precaution to prevent
439                  * copying of random kernel data.
440                  */
441                 for (is = ips_list; is; is = is->is_next)
442                         if (is == isn)
443                                 break;
444                 if (!is)
445                         return ESRCH;
446         }
447         ips.ips_next = isn->is_next;
448         bcopy((char *)isn, (char *)&ips.ips_is, sizeof(ips.ips_is));
449         if (isn->is_rule)
450                 bcopy((char *)isn->is_rule, (char *)&ips.ips_fr,
451                       sizeof(ips.ips_fr));
452         error = IWCOPYPTR((caddr_t)&ips, data, sizeof(ips));
453         if (error)
454                 error = EFAULT;
455         return error;
456 }
457
458
459 int fr_stputent(data)
460 caddr_t data;
461 {
462         register ipstate_t *is, *isn;
463         ipstate_save_t ips;
464         int error, out, i;
465         frentry_t *fr;
466         char *name;
467
468         error = IRCOPYPTR(data, (caddr_t)&ips, sizeof(ips));
469         if (error)
470                 return error;
471
472         KMALLOC(isn, ipstate_t *);
473         if (isn == NULL)
474                 return ENOMEM;
475
476         bcopy((char *)&ips.ips_is, (char *)isn, sizeof(*isn));
477         fr = isn->is_rule;
478         if (fr != NULL) {
479                 if (isn->is_flags & FI_NEWFR) {
480                         KMALLOC(fr, frentry_t *);
481                         if (fr == NULL) {
482                                 KFREE(isn);
483                                 return ENOMEM;
484                         }
485                         bcopy((char *)&ips.ips_fr, (char *)fr, sizeof(*fr));
486                         out = fr->fr_flags & FR_OUTQUE ? 1 : 0;
487                         isn->is_rule = fr;
488                         ips.ips_is.is_rule = fr;
489
490                         /*
491                          * Look up all the interface names in the rule.
492                          */
493                         for (i = 0; i < 4; i++) {
494                                 name = fr->fr_ifnames[i];
495                                 if ((name[1] == '\0') &&
496                                     ((name[0] == '-') || (name[0] == '*'))) {
497                                         fr->fr_ifas[i] = NULL;
498                                 } else if (*name != '\0') {
499                                         fr->fr_ifas[i] = GETUNIT(name,
500                                                                  fr->fr_v);
501                                         if (fr->fr_ifas[i] == NULL)
502                                                 fr->fr_ifas[i] = (void *)-1;
503                                         else {
504                                                 strncpy(isn->is_ifname[i],
505                                                         IFNAME(fr->fr_ifas[i]),
506                                                         IFNAMSIZ);
507                                         }
508                                 }
509                                 isn->is_ifp[out] = fr->fr_ifas[i];
510                         }
511
512                         /*
513                          * send a copy back to userland of what we ended up
514                          * to allow for verification.
515                          */
516                         error = IWCOPYPTR((caddr_t)&ips, data, sizeof(ips));
517                         if (error) {
518                                 KFREE(isn);
519                                 KFREE(fr);
520                                 return EFAULT;
521                         }
522                 } else {
523                         for (is = ips_list; is; is = is->is_next)
524                                 if (is->is_rule == fr)
525                                         break;
526                         if (!is) {
527                                 KFREE(isn);
528                                 return ESRCH;
529                         }
530                 }
531         }
532         fr_stinsert(isn);
533         return 0;
534 }
535
536
537 /*
538  * Insert a state table entry manually.
539  */
540 void fr_stinsert(is)
541 register ipstate_t *is;
542 {
543         register u_int hv = is->is_hv;
544         char *name;
545         int i;
546
547         MUTEX_INIT(&is->is_lock, "ipf state entry", NULL);
548
549         /*
550          * Look up all the interface names in the state entry.
551          */
552         for (i = 0; i < 4; i++) {
553                 name = is->is_ifname[i];
554                 if ((name[1] == '\0') &&
555                     ((name[0] == '-') || (name[0] == '*'))) {
556                         is->is_ifp[0] = NULL;
557                 } else if (*name != '\0') {
558                         is->is_ifp[i] = GETUNIT(name, is->is_v);
559                         if (is->is_ifp[i] == NULL)
560                                 is->is_ifp[i] = (void *)-1;
561                 }
562         }
563
564
565         /*
566          * add into list table.
567          */
568         if (ips_list)
569                 ips_list->is_pnext = &is->is_next;
570         is->is_pnext = &ips_list;
571         is->is_next = ips_list;
572         ips_list = is;
573         if (ips_table[hv])
574                 ips_table[hv]->is_phnext = &is->is_hnext;
575         else
576                 ips_stats.iss_inuse++;
577         is->is_phnext = ips_table + hv;
578         is->is_hnext = ips_table[hv];
579         ips_table[hv] = is;
580         ips_num++;
581 }
582
583
584 /*
585  * Create a new ipstate structure and hang it off the hash table.
586  */
587 ipstate_t *fr_addstate(ip, fin, stsave, flags)
588 ip_t *ip;
589 fr_info_t *fin;
590 ipstate_t **stsave;
591 u_int flags;
592 {
593         register tcphdr_t *tcp = NULL;
594         register ipstate_t *is;
595         register u_int hv;
596         struct icmp *ic;
597         ipstate_t ips;
598         int out, ws;
599         u_int pass;
600         void *ifp;
601
602         if (fr_state_lock || (fin->fin_off != 0) || (fin->fin_fl & FI_SHORT) ||
603             (fin->fin_misc & FM_BADSTATE))
604                 return NULL;
605         if (ips_num == fr_statemax) {
606                 ips_stats.iss_max++;
607                 fr_state_doflush = 1;
608                 return NULL;
609         }
610         out = fin->fin_out;
611         is = &ips;
612         bzero((char *)is, sizeof(*is));
613         ips.is_age = 1;
614         /*
615          * Copy and calculate...
616          */
617         hv = (is->is_p = fin->fin_fi.fi_p);
618         is->is_src = fin->fin_fi.fi_src;
619         hv += is->is_saddr;
620         is->is_dst = fin->fin_fi.fi_dst;
621         hv += is->is_daddr;
622 #ifdef  USE_INET6
623         if (fin->fin_v == 6) {
624                 if ((is->is_p == IPPROTO_ICMPV6) &&
625                     IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
626                         /*
627                          * So you can do keep state with neighbour discovery.
628                          */
629                         flags |= FI_W_DADDR;
630                         hv -= is->is_daddr;
631                 } else {
632                         hv += is->is_dst.i6[1];
633                         hv += is->is_dst.i6[2];
634                         hv += is->is_dst.i6[3];
635                 }
636                 hv += is->is_src.i6[1];
637                 hv += is->is_src.i6[2];
638                 hv += is->is_src.i6[3];
639         }
640 #endif
641
642         switch (is->is_p)
643         {
644                 int off;
645
646 #ifdef  USE_INET6
647         case IPPROTO_ICMPV6 :
648                 ic = (struct icmp *)fin->fin_dp;
649                 if ((ic->icmp_type & ICMP6_INFOMSG_MASK) == 0)
650                         return NULL;
651
652                 switch (ic->icmp_type)
653                 {
654                 case ICMP6_ECHO_REQUEST :
655                         is->is_icmp.ics_type = ic->icmp_type;
656                         hv += (is->is_icmp.ics_id = ic->icmp_id);
657                         hv += (is->is_icmp.ics_seq = ic->icmp_seq);
658                         break;
659                 case ICMP6_MEMBERSHIP_QUERY :
660                 case ND_ROUTER_SOLICIT :
661                 case ND_NEIGHBOR_SOLICIT :
662                 case ICMP6_NI_QUERY :
663                         is->is_icmp.ics_type = ic->icmp_type;
664                         break;
665                 default :
666                         return NULL;
667                 }
668                 ATOMIC_INCL(ips_stats.iss_icmp);
669                 is->is_age = fr_icmptimeout;
670                 break;
671 #endif
672         case IPPROTO_ICMP :
673                 ic = (struct icmp *)fin->fin_dp;
674
675                 switch (ic->icmp_type)
676                 {
677                 case ICMP_ECHO :
678                 case ICMP_TSTAMP :
679                 case ICMP_IREQ :
680                 case ICMP_MASKREQ :
681                         is->is_icmp.ics_type = ic->icmp_type;
682                         hv += (is->is_icmp.ics_id = ic->icmp_id);
683                         hv += (is->is_icmp.ics_seq = ic->icmp_seq);
684                         break;
685                 default :
686                         return NULL;
687                 }
688                 ATOMIC_INCL(ips_stats.iss_icmp);
689                 is->is_age = fr_icmptimeout;
690                 break;
691         case IPPROTO_TCP :
692                 tcp = (tcphdr_t *)fin->fin_dp;
693
694                 if (tcp->th_flags & TH_RST)
695                         return NULL;
696                 /*
697                  * The endian of the ports doesn't matter, but the ack and
698                  * sequence numbers do as we do mathematics on them later.
699                  */
700                 is->is_sport = htons(fin->fin_data[0]);
701                 is->is_dport = htons(fin->fin_data[1]);
702                 if ((flags & (FI_W_DPORT|FI_W_SPORT)) == 0) {
703                         hv += is->is_sport;
704                         hv += is->is_dport;
705                 }
706                 if ((flags & FI_IGNOREPKT) == 0) {
707                         is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
708                                       (off = (tcp->th_off << 2)) +
709                                       ((tcp->th_flags & TH_SYN) ? 1 : 0) +
710                                       ((tcp->th_flags & TH_FIN) ? 1 : 0);
711                         is->is_maxsend = is->is_send;
712
713                         if ((tcp->th_flags & TH_SYN) &&
714                             ((tcp->th_off << 2) >= (sizeof(*tcp) + 4))) {
715                                 ws = fr_tcpoptions(tcp);
716                                 if (ws >= 0)
717                                         is->is_swscale = ws;
718                         }
719                 }
720
721                 is->is_maxdwin = 1;
722                 is->is_maxswin = ntohs(tcp->th_win);
723                 if (is->is_maxswin == 0)
724                         is->is_maxswin = 1;
725
726                 if ((tcp->th_flags & TH_OPENING) == TH_SYN)
727                         is->is_fsm = 1;
728
729                 /*
730                  * If we're creating state for a starting connection, start the
731                  * timer on it as we'll never see an error if it fails to
732                  * connect.
733                  */
734                 ATOMIC_INCL(ips_stats.iss_tcp);
735                 break;
736
737         case IPPROTO_UDP :
738                 tcp = (tcphdr_t *)fin->fin_dp;
739
740                 is->is_sport = htons(fin->fin_data[0]);
741                 is->is_dport = htons(fin->fin_data[1]);
742                 if ((flags & (FI_W_DPORT|FI_W_SPORT)) == 0) {
743                         hv += is->is_sport;
744                         hv += is->is_dport;
745                 }
746                 ATOMIC_INCL(ips_stats.iss_udp);
747                 is->is_age = fr_udptimeout;
748                 break;
749         default :
750                 is->is_age = fr_udptimeout;
751                 break;
752         }
753
754         KMALLOC(is, ipstate_t *);
755         if (is == NULL) {
756                 ATOMIC_INCL(ips_stats.iss_nomem);
757                 return NULL;
758         }
759         bcopy((char *)&ips, (char *)is, sizeof(*is));
760         hv %= fr_statesize;
761         is->is_hv = hv;
762         is->is_rule = fin->fin_fr;
763         if (is->is_rule != NULL) {
764                 is->is_group = is->is_rule->fr_group;
765                 ATOMIC_INC32(is->is_rule->fr_ref);
766                 pass = is->is_rule->fr_flags;
767                 is->is_frage[0] = is->is_rule->fr_age[0];
768                 is->is_frage[1] = is->is_rule->fr_age[1];
769                 if (is->is_frage[0] != 0)
770                         is->is_age = is->is_frage[0];
771
772                 is->is_ifp[(out << 1) + 1] = is->is_rule->fr_ifas[1];
773                 is->is_ifp[(1 - out) << 1] = is->is_rule->fr_ifas[2];
774                 is->is_ifp[((1 - out) << 1) + 1] = is->is_rule->fr_ifas[3];
775
776                 if (((ifp = is->is_rule->fr_ifas[1]) != NULL) &&
777                     (ifp != (void *)-1))
778                         strncpy(is->is_ifname[(out << 1) + 1],
779                                 IFNAME(ifp), IFNAMSIZ);
780                 if (((ifp = is->is_rule->fr_ifas[2]) != NULL) &&
781                     (ifp != (void *)-1))
782                         strncpy(is->is_ifname[(1 - out) << 1],
783                                 IFNAME(ifp), IFNAMSIZ);
784                 if (((ifp = is->is_rule->fr_ifas[3]) != NULL) &&
785                     (ifp != (void *)-1))
786                         strncpy(is->is_ifname[((1 - out) << 1) + 1],
787                                 IFNAME(ifp), IFNAMSIZ);
788         } else
789                 pass = fr_flags;
790
791         is->is_ifp[out << 1] = fin->fin_ifp;
792         strncpy(is->is_ifname[out << 1], IFNAME(fin->fin_ifp), IFNAMSIZ);
793
794         WRITE_ENTER(&ipf_state);
795
796         is->is_pass = pass;
797         if ((flags & FI_IGNOREPKT) == 0) {
798                 is->is_pkts = 1;
799                 is->is_bytes = fin->fin_dlen + fin->fin_hlen;
800         }
801         /*
802          * We want to check everything that is a property of this packet,
803          * but we don't (automatically) care about it's fragment status as
804          * this may change.
805          */
806         is->is_v = fin->fin_v;
807         is->is_rulen = fin->fin_rule;
808         is->is_opt = fin->fin_fi.fi_optmsk;
809         is->is_optmsk = 0xffffffff;
810         is->is_sec = fin->fin_fi.fi_secmsk;
811         is->is_secmsk = 0xffff;
812         is->is_auth = fin->fin_fi.fi_auth;
813         is->is_authmsk = 0xffff;
814         is->is_flags = fin->fin_fl & FI_CMP;
815         is->is_flags |= FI_CMP << 4;
816         is->is_flags |= flags & (FI_WILDP|FI_WILDA);
817         if (flags & (FI_WILDP|FI_WILDA))
818                 ips_wild++;
819
820         if (pass & FR_LOGFIRST)
821                 is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
822         fr_stinsert(is);
823         is->is_me = stsave;
824         if (is->is_p == IPPROTO_TCP) {
825                 fr_tcp_age(&is->is_age, is->is_state, fin,
826                            0, is->is_fsm); /* 0 = packet from the source */
827         }
828 #ifdef  IPFILTER_LOG
829         ipstate_log(is, ISL_NEW);
830 #endif
831         RWLOCK_EXIT(&ipf_state);
832         fin->fin_rev = IP6NEQ(is->is_dst, fin->fin_fi.fi_dst);
833         if ((fin->fin_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
834                 ipfr_newfrag(ip, fin);
835         return is;
836 }
837
838
839 static int fr_tcpoptions(tcp)
840 tcphdr_t *tcp;
841 {
842         u_char *opt, *last;
843         int wscale;
844
845         opt = (u_char *) (tcp + 1);
846         last = ((u_char *)tcp) + (tcp->th_off << 2);
847
848         /* If we don't find wscale here, we need to clear it */
849         wscale = -2;
850
851         /* Termination condition picked such that opt[0 .. 2] exist */
852         while ((opt < last - 2)  && (*opt != TCPOPT_EOL)) {
853                 switch (*opt) {
854                 case TCPOPT_NOP:
855                         opt++;
856                         continue;
857                 case TCPOPT_WSCALE:
858                         /* Proper length ? */
859                         if (opt[1] == 3) {
860                                 if (opt[2] > 14)
861                                         wscale = 14;
862                                 else
863                                         wscale = opt[2];
864                         }
865                         break;
866                 default:
867                         /* Unknown options must be two bytes+ */
868                         if (opt[1] < 2)
869                                 break;
870                         opt += opt[1];
871                         continue;
872                 }
873                 break;
874         }
875         return wscale;
876 }
877
878
879
880 /*
881  * check to see if a packet with TCP headers fits within the TCP window.
882  * change timeout depending on whether new packet is a SYN-ACK returning for a
883  * SYN or a RST or FIN which indicate time to close up shop.
884  */
885 int fr_tcpstate(is, fin, ip, tcp)
886 register ipstate_t *is;
887 fr_info_t *fin;
888 ip_t *ip;
889 tcphdr_t *tcp;
890 {
891         register tcp_seq seq, ack, end;
892         register int ackskew;
893         tcpdata_t  *fdata, *tdata;
894         u_32_t  win, maxwin;
895         int ret = 0, off;
896         int source;
897         int wscale;
898
899         /*
900          * Find difference between last checked packet and this packet.
901          */
902         source = IP6EQ(fin->fin_fi.fi_src, is->is_src);
903         if (source && (ntohs(is->is_sport) != fin->fin_data[0]))
904                 source = 0;
905         fdata = &is->is_tcp.ts_data[!source];
906         tdata = &is->is_tcp.ts_data[source];
907         off = tcp->th_off << 2;
908         seq = ntohl(tcp->th_seq);
909         ack = ntohl(tcp->th_ack);
910         win = ntohs(tcp->th_win);
911         end = seq + fin->fin_dlen - off +
912                ((tcp->th_flags & TH_SYN) ? 1 : 0) +
913                ((tcp->th_flags & TH_FIN) ? 1 : 0);
914
915
916         if ((tcp->th_flags & TH_SYN) && (off >= sizeof(*tcp) + 4))
917                 wscale = fr_tcpoptions(tcp);
918         else
919                 wscale = -1;
920
921         MUTEX_ENTER(&is->is_lock);
922
923         if (wscale >= 0)
924                 fdata->td_wscale = wscale;
925         else if (wscale == -2)
926                 fdata->td_wscale = tdata->td_wscale = 0;
927         win <<= fdata->td_wscale;
928
929         if ((fdata->td_end == 0) &&
930             (!is->is_fsm || ((tcp->th_flags & TH_OPENING) == TH_OPENING))) {
931                 /*
932                  * Must be a (outgoing) SYN-ACK in reply to a SYN.
933                  */
934                 fdata->td_end = end;
935                 fdata->td_maxwin = 1;
936                 fdata->td_maxend = end + win;
937                 if (win == 0)
938                         fdata->td_maxend++;
939         }
940
941         if (!(tcp->th_flags & TH_ACK)) {  /* Pretend an ack was sent */
942                 ack = tdata->td_end;
943         } else if (((tcp->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
944                    (ack == 0)) {
945                 /* gross hack to get around certain broken tcp stacks */
946                 ack = tdata->td_end;
947         }
948
949         if (seq == end)
950                 seq = end = fdata->td_end;
951
952         maxwin = tdata->td_maxwin;
953         ackskew = tdata->td_end - ack;
954
955 #define SEQ_GE(a,b)     ((int)((a) - (b)) >= 0)
956 #define SEQ_GT(a,b)     ((int)((a) - (b)) > 0)
957         if ((SEQ_GE(fdata->td_maxend, end)) &&
958             (SEQ_GE(seq, fdata->td_end - maxwin)) &&
959 /* XXX what about big packets */
960 #define MAXACKWINDOW 66000
961             (ackskew >= -MAXACKWINDOW) &&
962             (ackskew <= MAXACKWINDOW)) {
963                 /* if ackskew < 0 then this should be due to fragented
964                  * packets. There is no way to know the length of the
965                  * total packet in advance.
966                  * We do know the total length from the fragment cache though.
967                  * Note however that there might be more sessions with
968                  * exactly the same source and destination paramters in the
969                  * state cache (and source and destination is the only stuff
970                  * that is saved in the fragment cache). Note further that
971                  * some TCP connections in the state cache are hashed with
972                  * sport and dport as well which makes it not worthwhile to
973                  * look for them.
974                  * Thus, when ackskew is negative but still seems to belong
975                  * to this session, we bump up the destinations end value.
976                  */
977                 /*
978                  * Nearing end of connection, start timeout.
979                  */
980                 /* source ? 0 : 1 -> !source */
981                 if (fr_tcp_age(&is->is_age, is->is_state, fin, !source,
982                                (int)is->is_fsm) == 0) {
983                         if (ackskew < 0)
984                                 tdata->td_end = ack;
985
986                         /* update max window seen */
987                         if (fdata->td_maxwin < win)
988                                 fdata->td_maxwin = win;
989                         if (SEQ_GT(end, fdata->td_end))
990                                 fdata->td_end = end;
991                         if (SEQ_GE(ack + win, tdata->td_maxend)) {
992                                 tdata->td_maxend = ack + win;
993                                 if (win == 0)
994                                         tdata->td_maxend++;
995                         }
996
997                         ATOMIC_INCL(ips_stats.iss_hits);
998                         ret = 1;
999                 }
1000         }
1001         MUTEX_EXIT(&is->is_lock);
1002         if ((ret == 0) && ((tcp->th_flags & TH_OPENING) != TH_SYN))
1003                 fin->fin_misc |= FM_BADSTATE;
1004         return ret;
1005 }
1006
1007
1008 /*
1009  * Match a state table entry against an IP packet.
1010  */
1011 static int fr_matchsrcdst(is, src, dst, fin, tcp)
1012 ipstate_t *is;
1013 union i6addr src, dst;
1014 fr_info_t *fin;
1015 tcphdr_t *tcp;
1016 {
1017         int ret = 0, rev, out, flags, idx;
1018         u_short sp, dp;
1019         void *ifp;
1020
1021         rev = IP6NEQ(is->is_dst, dst);
1022         ifp = fin->fin_ifp;
1023         out = fin->fin_out;
1024         flags = is->is_flags & (FI_WILDA|FI_WILDP);
1025         sp = 0;
1026         dp = 0;
1027
1028         if (tcp != NULL) {
1029                 flags = is->is_flags;
1030                 sp = tcp->th_sport;
1031                 dp = tcp->th_dport;
1032                 if (!rev) {
1033                         if (!(flags & FI_W_SPORT) && (sp != is->is_sport))
1034                                 rev = 1;
1035                         else if (!(flags & FI_W_DPORT) && (dp != is->is_dport))
1036                                 rev = 1;
1037                 }
1038         }
1039
1040         idx = (out << 1) + rev;
1041
1042         if ((is->is_ifp[idx] == NULL && 
1043              (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) ||
1044             is->is_ifp[idx] == ifp)
1045                 ret = 1;
1046
1047         if (ret == 0)
1048                 return 0;
1049         ret = 0;
1050
1051         if (rev == 0) {
1052                 if ((IP6EQ(is->is_dst, dst) || (flags & FI_W_DADDR)) &&
1053                     (IP6EQ(is->is_src, src) || (flags & FI_W_SADDR)) &&
1054                     (!tcp || ((sp == is->is_sport || flags & FI_W_SPORT) &&
1055                      (dp == is->is_dport || flags & FI_W_DPORT)))) {
1056                         ret = 1;
1057                 }
1058         } else {
1059                 if ((IP6EQ(is->is_dst, src) || (flags & FI_W_DADDR)) &&
1060                     (IP6EQ(is->is_src, dst) || (flags & FI_W_SADDR)) &&
1061                     (!tcp || ((sp == is->is_dport || flags & FI_W_DPORT) &&
1062                      (dp == is->is_sport || flags & FI_W_SPORT)))) {
1063                         ret = 1;
1064                 }
1065         }
1066         if (ret == 0)
1067                 return 0;
1068
1069         /*
1070          * Whether or not this should be here, is questionable, but the aim
1071          * is to get this out of the main line.
1072          */
1073         if (tcp == NULL)
1074                 flags = is->is_flags & (FI_CMP|(FI_CMP<<4));
1075
1076         if (((fin->fin_fl & (flags >> 4)) != (flags & FI_CMP)) ||
1077             (fin->fin_fi.fi_optmsk != is->is_opt) ||
1078             (fin->fin_fi.fi_secmsk != is->is_sec) ||
1079             (fin->fin_fi.fi_auth != is->is_auth))
1080                 return 0;
1081
1082         flags = is->is_flags & (FI_WILDA|FI_WILDP);
1083         if ((flags & (FI_W_SADDR|FI_W_DADDR))) {
1084                 if ((flags & FI_W_SADDR) != 0) {
1085                         if (rev == 0) {
1086                                 is->is_src = fin->fin_fi.fi_src;
1087                         } else {
1088                                 is->is_src = fin->fin_fi.fi_dst;
1089                         }
1090                 } else if ((flags & FI_W_DADDR) != 0) {
1091                         if (rev == 0) {
1092                                 is->is_dst = fin->fin_fi.fi_dst;
1093                         } else {
1094                                 is->is_dst = fin->fin_fi.fi_src;
1095                         }
1096                 }
1097                 is->is_flags &= ~(FI_W_SADDR|FI_W_DADDR);
1098                 if ((is->is_flags & (FI_WILDA|FI_WILDP)) == 0)
1099                         ips_wild--;
1100         }
1101
1102         if ((flags & (FI_W_SPORT|FI_W_DPORT))) {
1103                 if ((flags & FI_W_SPORT) != 0) {
1104                         if (rev == 0) {
1105                                 is->is_sport = sp;
1106                                 is->is_send = htonl(tcp->th_seq);
1107                         } else {
1108                                 is->is_sport = dp;
1109                                 is->is_send = htonl(tcp->th_ack);
1110                         }
1111                         is->is_maxsend = is->is_send + 1;
1112                 } else if ((flags & FI_W_DPORT) != 0) {
1113                         if (rev == 0) {
1114                                 is->is_dport = dp;
1115                                 is->is_dend = htonl(tcp->th_ack);
1116                         } else {
1117                                 is->is_dport = sp;
1118                                 is->is_dend = htonl(tcp->th_seq);
1119                         }
1120                         is->is_maxdend = is->is_dend + 1;
1121                 }
1122                 is->is_flags &= ~(FI_W_SPORT|FI_W_DPORT);
1123                 ips_wild--;
1124         }
1125
1126         ret = -1;
1127
1128         if (is->is_ifp[idx] == NULL &&
1129             (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*'))
1130                 ret = idx;
1131
1132         if (ret >= 0) {
1133                 is->is_ifp[ret] = ifp;
1134                 strncpy(is->is_ifname[ret], IFNAME(ifp),
1135                         sizeof(is->is_ifname[ret]));
1136         }
1137         fin->fin_rev = rev;
1138         return 1;
1139 }
1140
1141 static int fr_matchicmpqueryreply(v, is, icmp, rev)
1142 int v;
1143 ipstate_t *is;
1144 icmphdr_t *icmp;
1145 {
1146         if (v == 4) {
1147                 /*
1148                  * If we matched its type on the way in, then when going out
1149                  * it will still be the same type.
1150                  */
1151                 if ((!rev && (icmp->icmp_type == is->is_type)) ||
1152                     (rev && (icmpreplytype4[is->is_type] == icmp->icmp_type))) {
1153                         if (icmp->icmp_type != ICMP_ECHOREPLY)
1154                                 return 1;
1155                         if ((icmp->icmp_id == is->is_icmp.ics_id) &&
1156                             (icmp->icmp_seq == is->is_icmp.ics_seq))
1157                                 return 1;
1158                 }
1159         }
1160 #ifdef  USE_INET6
1161         else if (is->is_v == 6) {
1162                 if ((!rev && (icmp->icmp_type == is->is_type)) ||
1163                     (rev && (icmpreplytype6[is->is_type] == icmp->icmp_type))) {
1164                         if (icmp->icmp_type != ICMP6_ECHO_REPLY)
1165                                 return 1;
1166                         if ((icmp->icmp_id == is->is_icmp.ics_id) &&
1167                             (icmp->icmp_seq == is->is_icmp.ics_seq))
1168                                 return 1;
1169                 }
1170         }
1171 #endif
1172         return 0;
1173 }
1174
1175 static frentry_t *fr_checkicmpmatchingstate(ip, fin)
1176 ip_t *ip;
1177 fr_info_t *fin;
1178 {
1179         register ipstate_t *is, **isp;
1180         register u_short sport, dport;
1181         register u_char pr;
1182         u_short savelen, ohlen;
1183         union i6addr dst, src;
1184         struct icmp *ic;
1185         icmphdr_t *icmp;
1186         fr_info_t ofin;
1187         int type, len;
1188         tcphdr_t *tcp;
1189         frentry_t *fr;
1190         ip_t *oip;
1191         u_int hv;
1192
1193         /*
1194          * Does it at least have the return (basic) IP header ?
1195          * Only a basic IP header (no options) should be with
1196          * an ICMP error header.
1197          */
1198         if (((ip->ip_v != 4) || (ip->ip_hl != 5)) ||
1199             (fin->fin_plen < ICMPERR_MINPKTLEN))
1200                 return NULL;
1201
1202         ic = (struct icmp *)fin->fin_dp;
1203         type = ic->icmp_type;
1204         /*
1205          * If it's not an error type, then return
1206          */
1207         if ((type != ICMP_UNREACH) && (type != ICMP_SOURCEQUENCH) &&
1208             (type != ICMP_REDIRECT) && (type != ICMP_TIMXCEED) &&
1209             (type != ICMP_PARAMPROB))
1210                 return NULL;
1211
1212         oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
1213         ohlen = oip->ip_hl << 2;
1214         if (fin->fin_plen < ICMPERR_MAXPKTLEN + ohlen - sizeof(*oip))
1215                 return NULL;
1216
1217         /*
1218          * Sanity checks.
1219          */
1220         len = fin->fin_dlen - ICMPERR_ICMPHLEN;
1221         if ((len <= 0) || (ohlen > len))
1222                 return NULL;
1223
1224         /*
1225          * Is the buffer big enough for all of it ?  It's the size of the IP
1226          * header claimed in the encapsulated part which is of concern.  It
1227          * may be too big to be in this buffer but not so big that it's
1228          * outside the ICMP packet, leading to TCP deref's causing problems.
1229          * This is possible because we don't know how big oip_hl is when we
1230          * do the pullup early in fr_check() and thus can't gaurantee it is
1231          * all here now.
1232          */
1233 #ifdef  _KERNEL
1234         {
1235         mb_t *m;
1236
1237 # if SOLARIS
1238         m = fin->fin_qfm;
1239         if ((char *)oip + len > (char *)m->b_wptr)
1240                 return NULL;
1241 # else
1242         m = *(mb_t **)fin->fin_mp;
1243         if ((char *)oip + len > (char *)ip + m->m_len)
1244                 return NULL;
1245 # endif
1246         }
1247 #endif
1248
1249         /*
1250          * in the IPv4 case we must zero the i6addr union otherwise
1251          * the IP6EQ and IP6NEQ macros produce the wrong results because
1252          * of the 'junk' in the unused part of the union
1253          */
1254         bzero((char *)&src, sizeof(src));
1255         bzero((char *)&dst, sizeof(dst));
1256         bzero((char *)&ofin, sizeof(ofin));
1257         ofin.fin_ifp = fin->fin_ifp;
1258         ofin.fin_out = !fin->fin_out;
1259         ofin.fin_v = 4;
1260         fr = NULL;
1261
1262         switch (oip->ip_p)
1263         {
1264         case IPPROTO_ICMP :
1265                 icmp = (icmphdr_t *)((char *)oip + ohlen);
1266
1267                 /*
1268                  * a ICMP error can only be generated as a result of an
1269                  * ICMP query, not as the response on an ICMP error
1270                  *
1271                  * XXX theoretically ICMP_ECHOREP and the other reply's are
1272                  * ICMP query's as well, but adding them here seems strange XXX
1273                  */
1274                  if ((icmp->icmp_type != ICMP_ECHO) &&
1275                      (icmp->icmp_type != ICMP_TSTAMP) &&
1276                      (icmp->icmp_type != ICMP_IREQ) &&
1277                      (icmp->icmp_type != ICMP_MASKREQ))
1278                         return NULL;
1279
1280                 /*
1281                  * perform a lookup of the ICMP packet in the state table
1282                  */
1283                 hv = (pr = oip->ip_p);
1284                 src.in4 = oip->ip_src;
1285                 hv += src.in4.s_addr;
1286                 dst.in4 = oip->ip_dst;
1287                 hv += dst.in4.s_addr;
1288                 hv += icmp->icmp_id;
1289                 hv += icmp->icmp_seq;
1290                 hv %= fr_statesize;
1291
1292                 savelen = oip->ip_len;
1293                 oip->ip_len = len;
1294                 fr_makefrip(ohlen, oip, &ofin);
1295                 oip->ip_len = savelen;
1296
1297                 READ_ENTER(&ipf_state);
1298                 for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1299                         if ((is->is_p == pr) && (is->is_v == 4) &&
1300                             fr_matchsrcdst(is, src, dst, &ofin, NULL) &&
1301                             fr_matchicmpqueryreply(is->is_v, is, icmp, fin->fin_rev)) {
1302                                 ips_stats.iss_hits++;
1303                                 is->is_pkts++;
1304                                 is->is_bytes += ip->ip_len;
1305                                 fr = is->is_rule;
1306                                 break;
1307                         }
1308                 RWLOCK_EXIT(&ipf_state);
1309                 return fr;
1310         
1311         case IPPROTO_TCP :
1312         case IPPROTO_UDP :
1313                 if (fin->fin_plen < ICMPERR_MAXPKTLEN)
1314                         return NULL;
1315                 break;
1316         default :
1317                 return NULL;
1318         }
1319
1320         tcp = (tcphdr_t *)((char *)oip + ohlen);
1321         dport = tcp->th_dport;
1322         sport = tcp->th_sport;
1323
1324         hv = (pr = oip->ip_p);
1325         src.in4 = oip->ip_src;
1326         hv += src.in4.s_addr;
1327         dst.in4 = oip->ip_dst;
1328         hv += dst.in4.s_addr;
1329         hv += dport;
1330         hv += sport;
1331         hv %= fr_statesize;
1332         /*
1333          * we make an fin entry to be able to feed it to
1334          * matchsrcdst note that not all fields are encessary
1335          * but this is the cleanest way. Note further we fill
1336          * in fin_mp such that if someone uses it we'll get
1337          * a kernel panic. fr_matchsrcdst does not use this.
1338          *
1339          * watch out here, as ip is in host order and oip in network
1340          * order. Any change we make must be undone afterwards.
1341          */
1342         savelen = oip->ip_len;
1343         oip->ip_len = len;
1344         fr_makefrip(ohlen, oip, &ofin);
1345         oip->ip_len = savelen;
1346         READ_ENTER(&ipf_state);
1347         for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1348                 /*
1349                  * Only allow this icmp though if the
1350                  * encapsulated packet was allowed through the
1351                  * other way around. Note that the minimal amount
1352                  * of info present does not allow for checking against
1353                  * tcp internals such as seq and ack numbers.
1354                  */
1355                 if ((is->is_p == pr) && (is->is_v == 4) &&
1356                     fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1357                         fr = is->is_rule;
1358                         ips_stats.iss_hits++;
1359                         is->is_pkts++;
1360                         is->is_bytes += fin->fin_plen;
1361                         /*
1362                          * we deliberately do not touch the timeouts
1363                          * for the accompanying state table entry.
1364                          * It remains to be seen if that is correct. XXX
1365                          */
1366                         break;
1367                 }
1368         }
1369         RWLOCK_EXIT(&ipf_state);
1370         return fr;
1371 }
1372
1373
1374 /*
1375  * Move a state hash table entry from its old location at is->is_hv to
1376  * its new location, indexed by hv % fr_statesize.
1377  */
1378 static void fr_ipsmove(isp, is, hv)
1379 ipstate_t **isp, *is;
1380 u_int hv;
1381 {
1382         u_int hvm;
1383
1384         hvm = is->is_hv;
1385         /*
1386          * Remove the hash from the old location...
1387          */
1388         if (is->is_hnext)
1389                 is->is_hnext->is_phnext = isp;
1390         *isp = is->is_hnext;
1391         if (ips_table[hvm] == NULL)
1392                 ips_stats.iss_inuse--;
1393
1394         /*
1395          * ...and put the hash in the new one.
1396          */
1397         hvm = hv % fr_statesize;
1398         is->is_hv = hvm;
1399         isp = &ips_table[hvm];
1400         if (*isp)
1401                 (*isp)->is_phnext = &is->is_hnext;
1402         else
1403                 ips_stats.iss_inuse++;
1404         is->is_phnext = isp;
1405         is->is_hnext = *isp;
1406         *isp = is;
1407 }
1408
1409
1410 /*
1411  * Check if a packet has a registered state.
1412  */
1413 frentry_t *fr_checkstate(ip, fin)
1414 ip_t *ip;
1415 fr_info_t *fin;
1416 {
1417         union i6addr dst, src;
1418         register ipstate_t *is, **isp;
1419         register u_char pr;
1420         u_int hv, hvm, hlen, tryagain, pass, v;
1421         struct icmp *ic;
1422         frentry_t *fr;
1423         tcphdr_t *tcp;
1424         int rev;
1425
1426         if ((ips_list == NULL) || (fin->fin_off != 0) || fr_state_lock ||
1427             (fin->fin_fl & FI_SHORT))
1428                 return NULL;
1429
1430         is = NULL;
1431         hlen = fin->fin_hlen;
1432         tcp = (tcphdr_t *)((char *)ip + hlen);
1433         ic = (struct icmp *)tcp;
1434         hv = (pr = fin->fin_fi.fi_p);
1435         src = fin->fin_fi.fi_src;
1436         dst = fin->fin_fi.fi_dst;
1437         hv += src.in4.s_addr;
1438         hv += dst.in4.s_addr;
1439
1440         /*
1441          * Search the hash table for matching packet header info.
1442          * At the bottom of this switch statement, the following is expected:
1443          * is == NULL, no lock on ipf_state is held.
1444          * is != NULL, a lock on ipf_state is held.
1445          */
1446         v = fin->fin_fi.fi_v;
1447 #ifdef  USE_INET6
1448         if (v == 6) {
1449                 hv += fin->fin_fi.fi_src.i6[1];
1450                 hv += fin->fin_fi.fi_src.i6[2];
1451                 hv += fin->fin_fi.fi_src.i6[3];
1452
1453                 if ((fin->fin_p == IPPROTO_ICMPV6) &&
1454                     IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
1455                         hv -= dst.in4.s_addr;
1456                 } else {
1457                         hv += fin->fin_fi.fi_dst.i6[1];
1458                         hv += fin->fin_fi.fi_dst.i6[2];
1459                         hv += fin->fin_fi.fi_dst.i6[3];
1460                 }
1461         }
1462 #endif
1463
1464         switch (fin->fin_p)
1465         {
1466 #ifdef  USE_INET6
1467         case IPPROTO_ICMPV6 :
1468                 tcp = NULL;
1469                 tryagain = 0;
1470                 if (v == 6) {
1471                         if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
1472                             (ic->icmp_type == ICMP6_ECHO_REPLY)) {
1473                                 hv += ic->icmp_id;
1474                                 hv += ic->icmp_seq;
1475                         }
1476                 }
1477                 READ_ENTER(&ipf_state);
1478 icmp6again:
1479                 hvm = hv % fr_statesize;
1480                 for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1481                         if ((is->is_p == pr) && (is->is_v == v) &&
1482                             fr_matchsrcdst(is, src, dst, fin, NULL) &&
1483                             fr_matchicmpqueryreply(v, is, ic, fin->fin_rev)) {
1484                                 rev = fin->fin_rev;
1485                                 if (is->is_frage[rev] != 0)
1486                                         is->is_age = is->is_frage[rev];
1487                                 else if (rev != 0)
1488                                         is->is_age = fr_icmpacktimeout;
1489                                 else
1490                                         is->is_age = fr_icmptimeout;
1491                                 break;
1492                         }
1493
1494                 if (is != NULL) {
1495                         if (tryagain && !(is->is_flags & FI_W_DADDR)) {
1496                                 hv += fin->fin_fi.fi_src.i6[0];
1497                                 hv += fin->fin_fi.fi_src.i6[1];
1498                                 hv += fin->fin_fi.fi_src.i6[2];
1499                                 hv += fin->fin_fi.fi_src.i6[3];
1500                                 fr_ipsmove(isp, is, hv);
1501                                 MUTEX_DOWNGRADE(&ipf_state);
1502                         }
1503                         break;
1504                 }
1505                 RWLOCK_EXIT(&ipf_state);
1506
1507                 /*
1508                  * No matching icmp state entry. Perhaps this is a
1509                  * response to another state entry.
1510                  */
1511                 if ((ips_wild != 0) && (v == 6) && (tryagain == 0) &&
1512                     !IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_src.in6)) {
1513                         hv -= fin->fin_fi.fi_src.i6[0];
1514                         hv -= fin->fin_fi.fi_src.i6[1];
1515                         hv -= fin->fin_fi.fi_src.i6[2];
1516                         hv -= fin->fin_fi.fi_src.i6[3];
1517                         tryagain = 1;
1518                         WRITE_ENTER(&ipf_state);
1519                         goto icmp6again;
1520                 }
1521
1522                 fr = fr_checkicmp6matchingstate((ip6_t *)ip, fin);
1523                 if (fr)
1524                         return fr;
1525                 break;
1526 #endif
1527         case IPPROTO_ICMP :
1528                 tcp = NULL;
1529                 if (v == 4) {
1530                         hv += ic->icmp_id;
1531                         hv += ic->icmp_seq;
1532                 }
1533                 hvm = hv % fr_statesize;
1534                 READ_ENTER(&ipf_state);
1535                 for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1536                         if ((is->is_p == pr) && (is->is_v == v) &&
1537                             fr_matchsrcdst(is, src, dst, fin, NULL) &&
1538                             fr_matchicmpqueryreply(v, is, ic, fin->fin_rev)) {
1539                                 rev = fin->fin_rev;
1540                                 if (is->is_frage[rev] != 0)
1541                                         is->is_age = is->is_frage[rev];
1542                                 else if (fin->fin_rev)
1543                                         is->is_age = fr_icmpacktimeout;
1544                                 else
1545                                         is->is_age = fr_icmptimeout;
1546                                 break;
1547                         }
1548
1549                 if (is != NULL)
1550                         break;
1551                 RWLOCK_EXIT(&ipf_state);
1552                 /*
1553                  * No matching icmp state entry. Perhaps this is a
1554                  * response to another state entry.
1555                  */
1556                 fr = fr_checkicmpmatchingstate(ip, fin);
1557                 if (fr)
1558                         return fr;
1559                 break;
1560         case IPPROTO_TCP :
1561                 /*
1562                  * Just plain ignore RST flag set with either FIN or SYN.
1563                  */
1564                 if ((tcp->th_flags & TH_RST) &&
1565                     ((tcp->th_flags & (TH_FIN|TH_SYN|TH_RST)) != TH_RST))
1566                         break;
1567         case IPPROTO_UDP :
1568             {
1569                 register u_short dport, sport;
1570
1571                 dport = tcp->th_dport;
1572                 sport = tcp->th_sport;
1573                 tryagain = 0;
1574                 hv += dport;
1575                 hv += sport;
1576                 READ_ENTER(&ipf_state);
1577 retry_tcpudp:
1578                 hvm = hv % fr_statesize;
1579                 for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1580                         if ((is->is_p == pr) && (is->is_v == v) &&
1581                             fr_matchsrcdst(is, src, dst, fin, tcp)) {
1582                                 rev = fin->fin_rev;
1583                                 if ((pr == IPPROTO_TCP)) {
1584                                         if (!fr_tcpstate(is, fin, ip, tcp))
1585                                                 is = NULL;
1586                                 } else if ((pr == IPPROTO_UDP)) {
1587                                         if (is->is_frage[rev] != 0)
1588                                                 is->is_age = is->is_frage[rev];
1589                                         else if (fin->fin_rev)
1590                                                 is->is_age = fr_udpacktimeout;
1591                                         else
1592                                                 is->is_age = fr_udptimeout;
1593                                 }
1594                                 break;
1595                         }
1596                 if (is != NULL) {
1597                         if (tryagain &&
1598                             !(is->is_flags & (FI_WILDP|FI_WILDA))) {
1599                                 hv += dport;
1600                                 hv += sport;
1601                                 fr_ipsmove(isp, is, hv);
1602                                 MUTEX_DOWNGRADE(&ipf_state);
1603                         }
1604                         break;
1605                 }
1606
1607                 RWLOCK_EXIT(&ipf_state);
1608                 if (!tryagain && ips_wild) {
1609                         hv -= dport;
1610                         hv -= sport;
1611                         tryagain = 1;
1612                         WRITE_ENTER(&ipf_state);
1613                         goto retry_tcpudp;
1614                 }
1615                 break;
1616             }
1617         default :
1618                 tcp = NULL;
1619                 hv %= fr_statesize;
1620                 READ_ENTER(&ipf_state);
1621                 for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1622                         if ((is->is_p == pr) && (is->is_v == v) &&
1623                             fr_matchsrcdst(is, src, dst, fin, NULL)) {
1624                                 rev = fin->fin_rev;
1625                                 if (is->is_frage[rev] != 0)
1626                                         is->is_age = is->is_frage[rev];
1627                                 else
1628                                         is->is_age = fr_udptimeout;
1629                                 break;
1630                         }
1631                 }
1632                 if (is == NULL) {
1633                         RWLOCK_EXIT(&ipf_state);
1634                 }
1635                 break;
1636         }
1637
1638         if (is == NULL) {
1639                 ATOMIC_INCL(ips_stats.iss_miss);
1640                 return NULL;
1641         }
1642
1643         MUTEX_ENTER(&is->is_lock);
1644         is->is_bytes += fin->fin_plen;
1645         ips_stats.iss_hits++;
1646         is->is_pkts++;
1647         MUTEX_EXIT(&is->is_lock);
1648         fr = is->is_rule;
1649         fin->fin_rule = is->is_rulen;
1650         if (fr != NULL) {
1651                 fin->fin_group = fr->fr_group;
1652                 fin->fin_icode = fr->fr_icode;
1653         }
1654         fin->fin_fr = fr;
1655         pass = is->is_pass;
1656         RWLOCK_EXIT(&ipf_state);
1657         if ((fin->fin_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
1658                 ipfr_newfrag(ip, fin);
1659 #ifndef _KERNEL
1660         if ((tcp != NULL) && (tcp->th_flags & TCP_CLOSE))
1661                 fr_delstate(is);
1662 #endif
1663         return fr;
1664 }
1665
1666
1667 /*
1668  * Sync. state entries.  If interfaces come or go or just change position,
1669  * this is needed.
1670  */
1671 void ip_statesync(ifp)
1672 void *ifp;
1673 {
1674         register ipstate_t *is;
1675         int i;
1676
1677         WRITE_ENTER(&ipf_state);
1678         for (is = ips_list; is; is = is->is_next) {
1679                 for (i = 0; i < 4; i++) {
1680                         if (is->is_ifp[i] == ifp) {
1681                                 is->is_ifp[i] = GETUNIT(is->is_ifname[i],
1682                                                         is->is_v);
1683                                 if (!is->is_ifp[i])
1684                                         is->is_ifp[i] = (void *)-1;
1685                         }
1686                 }
1687         }
1688         RWLOCK_EXIT(&ipf_state);
1689 }
1690
1691
1692 /*
1693  * Must always be called with fr_ipfstate held as a write lock.
1694  */
1695 static void fr_delstate(is)
1696 ipstate_t *is;
1697 {
1698         frentry_t *fr;
1699
1700         if (is->is_flags & (FI_WILDP|FI_WILDA))
1701                 ips_wild--;
1702         if (is->is_next)
1703                 is->is_next->is_pnext = is->is_pnext;
1704         *is->is_pnext = is->is_next;
1705         if (is->is_hnext)
1706                 is->is_hnext->is_phnext = is->is_phnext;
1707         *is->is_phnext = is->is_hnext;
1708         if (ips_table[is->is_hv] == NULL)
1709                 ips_stats.iss_inuse--;
1710         if (is->is_me)
1711                 *is->is_me = NULL;
1712
1713         fr = is->is_rule;
1714         if (fr != NULL) {
1715                 fr->fr_ref--;
1716                 if (fr->fr_ref == 0) {
1717                         KFREE(fr);
1718                 }
1719         }
1720 #ifdef  _KERNEL
1721         MUTEX_DESTROY(&is->is_lock);
1722 #endif
1723         KFREE(is);
1724         ips_num--;
1725 }
1726
1727
1728 /*
1729  * Free memory in use by all state info. kept.
1730  */
1731 void fr_stateunload()
1732 {
1733         register ipstate_t *is;
1734
1735         WRITE_ENTER(&ipf_state);
1736         while ((is = ips_list))
1737                 fr_delstate(is);
1738         ips_stats.iss_inuse = 0;
1739         ips_num = 0;
1740         RWLOCK_EXIT(&ipf_state);
1741         if (ips_table)
1742                 KFREES(ips_table, fr_statesize * sizeof(ipstate_t *));
1743         ips_table = NULL;
1744 }
1745
1746
1747 /*
1748  * Slowly expire held state for thingslike UDP and ICMP.  Timeouts are set
1749  * in expectation of this being called twice per second.
1750  */
1751 void fr_timeoutstate()
1752 {
1753         register ipstate_t *is, **isp;
1754 #if defined(_KERNEL) && !SOLARIS
1755         int s;
1756 #endif
1757
1758         SPL_NET(s);
1759         WRITE_ENTER(&ipf_state);
1760         for (isp = &ips_list; (is = *isp); )
1761                 if (is->is_age && !--is->is_age) {
1762                         if (is->is_p == IPPROTO_TCP)
1763                                 ips_stats.iss_fin++;
1764                         else
1765                                 ips_stats.iss_expire++;
1766 #ifdef  IPFILTER_LOG
1767                         ipstate_log(is, ISL_EXPIRE);
1768 #endif
1769                         fr_delstate(is);
1770                 } else
1771                         isp = &is->is_next;
1772         if (fr_state_doflush) {
1773                 (void) fr_state_flush(2, 0);
1774                 fr_state_doflush = 0;
1775         }
1776         RWLOCK_EXIT(&ipf_state);
1777         SPL_X(s);
1778 }
1779
1780
1781 /*
1782  * Original idea freom Pradeep Krishnan for use primarily with NAT code.
1783  * (pkrishna@netcom.com)
1784  *
1785  * Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:
1786  *
1787  * - (try to) base state transitions on real evidence only,
1788  *   i.e. packets that are sent and have been received by ipfilter;
1789  *   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.
1790  *
1791  * - deal with half-closed connections correctly;
1792  *
1793  * - store the state of the source in state[0] such that ipfstat
1794  *   displays the state as source/dest instead of dest/source; the calls
1795  *   to fr_tcp_age have been changed accordingly.
1796  *
1797  * Parameters:
1798  *
1799  *    state[0] = state of source (host that initiated connection)
1800  *    state[1] = state of dest   (host that accepted the connection)
1801  *
1802  *    dir == 0 : a packet from source to dest
1803  *    dir == 1 : a packet from dest to source
1804  *
1805  */
1806 int fr_tcp_age(age, state, fin, dir, fsm)
1807 u_long *age;
1808 u_char *state;
1809 fr_info_t *fin;
1810 int dir, fsm;
1811 {
1812         tcphdr_t *tcp = (tcphdr_t *)fin->fin_dp;
1813         u_char flags = tcp->th_flags;
1814         int dlen, ostate;
1815         u_long newage;
1816
1817         ostate = state[1 - dir];
1818
1819         dlen = fin->fin_plen - fin->fin_hlen - (tcp->th_off << 2);
1820
1821         if (flags & TH_RST) {
1822                 if (!(tcp->th_flags & TH_PUSH) && !dlen) {
1823                         *age = fr_tcpclosed;
1824                         state[dir] = TCPS_CLOSED;
1825                 } else {
1826                         *age = fr_tcpclosewait;
1827                         state[dir] = TCPS_CLOSE_WAIT;
1828                 }
1829                 return 0;
1830         }
1831
1832         newage = 0;
1833
1834         switch(state[dir])
1835         {
1836         case TCPS_CLOSED: /* 0 */
1837                 if ((flags & TH_OPENING) == TH_OPENING) {
1838                         /*
1839                          * 'dir' received an S and sends SA in response,
1840                          * CLOSED -> SYN_RECEIVED
1841                          */
1842                         state[dir] = TCPS_SYN_RECEIVED;
1843                         newage = fr_tcptimeout;
1844                 } else if ((flags & TH_OPENING) == TH_SYN) {
1845                         /* 'dir' sent S, CLOSED -> SYN_SENT */
1846                         state[dir] = TCPS_SYN_SENT;
1847                         newage = fr_tcptimeout;
1848                 }
1849                 
1850                 /* 
1851                  * It is apparently possible that a hosts sends two syncs
1852                  * before the remote party is able to respond with a SA. In
1853                  * such a case the remote server sometimes ACK's the second
1854                  * sync, and then responds with a SA. The following code
1855                  * is used to prevent this ack from being blocked.
1856                  *
1857                  * We do not reset the timeout here to fr_tcptimeout because
1858                  * a connection connect timeout does not renew after every
1859                  * packet that is sent.  We need to set newage to something
1860                  * to indicate the packet has passed the check for its flags
1861                  * being valid in the TCP FSM.
1862                  */
1863                 else if ((ostate == TCPS_SYN_SENT) &&
1864                          ((flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK)) {
1865                         newage = *age;
1866                 }
1867
1868                 /*
1869                  * The next piece of code makes it possible to get
1870                  * already established connections into the state table
1871                  * after a restart or reload of the filter rules; this
1872                  * does not work when a strict 'flags S keep state' is
1873                  * used for tcp connections of course, however, use a
1874                  * lower time-out so the state disappears quickly if
1875                  * the other side does not pick it up.
1876                  */
1877                 else if (!fsm &&
1878                          (flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK) {
1879                         /* we saw an A, guess 'dir' is in ESTABLISHED mode */
1880                         if (ostate == TCPS_CLOSED) {
1881                                 state[dir] = TCPS_ESTABLISHED;
1882                                 newage = fr_tcptimeout;
1883                         } else if (ostate == TCPS_ESTABLISHED) {
1884                                 state[dir] = TCPS_ESTABLISHED;
1885                                 newage = fr_tcpidletimeout;
1886                         }
1887                 }
1888                 /*
1889                  * TODO: besides regular ACK packets we can have other
1890                  * packets as well; it is yet to be determined how we
1891                  * should initialize the states in those cases
1892                  */
1893                 break;
1894
1895         case TCPS_LISTEN: /* 1 */
1896                 /* NOT USED */
1897                 break;
1898
1899         case TCPS_SYN_SENT: /* 2 */
1900                 if ((flags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
1901                         /*
1902                          * A retransmitted SYN packet.  We do not reset the
1903                          * timeout here to fr_tcptimeout because a connection
1904                          * connect timeout does not renew after every packet
1905                          * that is sent.  We need to set newage to something
1906                          * to indicate the packet has passed the check for its
1907                          * flags being valid in the TCP FSM.
1908                          */
1909                         newage = *age;
1910                 } else if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1911                         /*
1912                          * We see an A from 'dir' which is in SYN_SENT
1913                          * state: 'dir' sent an A in response to an SA
1914                          * which it received, SYN_SENT -> ESTABLISHED
1915                          */
1916                         state[dir] = TCPS_ESTABLISHED;
1917                         newage = fr_tcpidletimeout;
1918                 } else if (flags & TH_FIN) {
1919                         /*
1920                          * We see an F from 'dir' which is in SYN_SENT
1921                          * state and wants to close its side of the
1922                          * connection; SYN_SENT -> FIN_WAIT_1
1923                          */
1924                         state[dir] = TCPS_FIN_WAIT_1;
1925                         newage = fr_tcpidletimeout; /* or fr_tcptimeout? */
1926                 } else if ((flags & TH_OPENING) == TH_OPENING) {
1927                         /*
1928                          * We see an SA from 'dir' which is already in
1929                          * SYN_SENT state, this means we have a
1930                          * simultaneous open; SYN_SENT -> SYN_RECEIVED
1931                          */
1932                         state[dir] = TCPS_SYN_RECEIVED;
1933                         newage = fr_tcptimeout;
1934                 }
1935                 break;
1936
1937         case TCPS_SYN_RECEIVED: /* 3 */
1938                 if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1939                         /*
1940                          * We see an A from 'dir' which was in SYN_RECEIVED
1941                          * state so it must now be in established state,
1942                          * SYN_RECEIVED -> ESTABLISHED
1943                          */
1944                         state[dir] = TCPS_ESTABLISHED;
1945                         newage = fr_tcpidletimeout;
1946                 } else if ((flags & ~(TH_ECN|TH_CWR)) == TH_OPENING) {
1947                         /*
1948                          * We see an SA from 'dir' which is already in
1949                          * SYN_RECEIVED state.
1950                          */
1951                         newage = fr_tcptimeout;
1952                 } else if (flags & TH_FIN) {
1953                         /*
1954                          * We see an F from 'dir' which is in SYN_RECEIVED
1955                          * state and wants to close its side of the connection;
1956                          * SYN_RECEIVED -> FIN_WAIT_1
1957                          */
1958                         state[dir] = TCPS_FIN_WAIT_1;
1959                         newage = fr_tcpidletimeout;
1960                 }
1961                 break;
1962
1963         case TCPS_ESTABLISHED: /* 4 */
1964                 if (flags & TH_FIN) {
1965                         /*
1966                          * 'dir' closed its side of the connection; this
1967                          * gives us a half-closed connection;
1968                          * ESTABLISHED -> FIN_WAIT_1
1969                          */
1970                         state[dir] = TCPS_FIN_WAIT_1;
1971                         newage = fr_tcphalfclosed;
1972                 } else if (flags & TH_ACK) {
1973                         /* an ACK, should we exclude other flags here? */
1974                         if (ostate == TCPS_FIN_WAIT_1) {
1975                                 /*
1976                                  * We know the other side did an active close,
1977                                  * so we are ACKing the recvd FIN packet (does
1978                                  * the window matching code guarantee this?)
1979                                  * and go into CLOSE_WAIT state; this gives us
1980                                  * a half-closed connection
1981                                  */
1982                                 state[dir] = TCPS_CLOSE_WAIT;
1983                                 newage = fr_tcphalfclosed;
1984                         } else if (ostate < TCPS_CLOSE_WAIT)
1985                                 /*
1986                                  * Still a fully established connection,
1987                                  * reset timeout
1988                                  */
1989                                 newage = fr_tcpidletimeout;
1990                 }
1991                 break;
1992
1993         case TCPS_CLOSE_WAIT: /* 5 */
1994                 if (flags & TH_FIN) {
1995                         /*
1996                          * Application closed and 'dir' sent a FIN, we're now
1997                          * going into LAST_ACK state
1998                          */
1999                         newage  = fr_tcplastack;
2000                         state[dir] = TCPS_LAST_ACK;
2001                 } else {
2002                         /*
2003                          * We remain in CLOSE_WAIT because the other side has
2004                          * closed already and we did not close our side yet;
2005                          * reset timeout
2006                          */
2007                         newage  = fr_tcphalfclosed;
2008                 }
2009                 break;
2010
2011         case TCPS_FIN_WAIT_1: /* 6 */
2012                 if ((flags & TH_ACK) && ostate > TCPS_CLOSE_WAIT) {
2013                         /*
2014                          * If the other side is not active anymore it has sent
2015                          * us a FIN packet that we are ack'ing now with an ACK;
2016                          * this means both sides have now closed the connection
2017                          * and we go into TIME_WAIT
2018                          */
2019                         /*
2020                          * XXX: how do we know we really are ACKing the FIN
2021                          * packet here? does the window code guarantee that?
2022                          */
2023                         state[dir] = TCPS_TIME_WAIT;
2024                         newage = fr_tcptimeout;
2025                 } else
2026                         /*
2027                          * We closed our side of the connection already but the
2028                          * other side is still active (ESTABLISHED/CLOSE_WAIT);
2029                          * continue with this half-closed connection
2030                          */
2031                         newage = fr_tcphalfclosed;
2032                 break;
2033
2034         case TCPS_CLOSING: /* 7 */
2035                 /* NOT USED */
2036                 break;
2037
2038         case TCPS_LAST_ACK: /* 8 */
2039                 if (flags & TH_ACK) {
2040                         if ((flags & TH_PUSH) || dlen)
2041                                 /*
2042                                  * There is still data to be delivered, reset
2043                                  * timeout
2044                                  */
2045                                 newage  = fr_tcplastack;
2046                         else
2047                                 newage = *age;
2048                 }
2049                 /*
2050                  * We cannot detect when we go out of LAST_ACK state to CLOSED
2051                  * because that is based on the reception of ACK packets;
2052                  * ipfilter can only detect that a packet has been sent by a
2053                  * host
2054                  */
2055                 break;
2056
2057         case TCPS_FIN_WAIT_2: /* 9 */
2058                 /* NOT USED */
2059                 break;
2060
2061         case TCPS_TIME_WAIT: /* 10 */
2062                 newage = fr_tcptimeout; /* default 4 mins */
2063                 /* we're in 2MSL timeout now */
2064                 break;
2065         }
2066
2067         if (newage != 0) {
2068                 *age = newage;
2069                 return 0;
2070         }
2071         return -1;
2072 }
2073
2074
2075 #ifdef  IPFILTER_LOG
2076 void ipstate_log(is, type)
2077 struct ipstate *is;
2078 u_int type;
2079 {
2080         struct  ipslog  ipsl;
2081         void *items[1];
2082         size_t sizes[1];
2083         int types[1];
2084
2085         ipsl.isl_type = type;
2086         ipsl.isl_pkts = is->is_pkts;
2087         ipsl.isl_bytes = is->is_bytes;
2088         ipsl.isl_src = is->is_src;
2089         ipsl.isl_dst = is->is_dst;
2090         ipsl.isl_p = is->is_p;
2091         ipsl.isl_v = is->is_v;
2092         ipsl.isl_flags = is->is_flags;
2093         ipsl.isl_rulen = is->is_rulen;
2094         ipsl.isl_group = is->is_group;
2095         if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
2096                 ipsl.isl_sport = is->is_sport;
2097                 ipsl.isl_dport = is->is_dport;
2098                 if (ipsl.isl_p == IPPROTO_TCP) {
2099                         ipsl.isl_state[0] = is->is_state[0];
2100                         ipsl.isl_state[1] = is->is_state[1];
2101                 }
2102         } else if (ipsl.isl_p == IPPROTO_ICMP) {
2103                 ipsl.isl_itype = is->is_icmp.ics_type;
2104         } else if (ipsl.isl_p == IPPROTO_ICMPV6) {
2105                 ipsl.isl_itype = is->is_icmp.ics_type;
2106         } else {
2107                 ipsl.isl_ps.isl_filler[0] = 0;
2108                 ipsl.isl_ps.isl_filler[1] = 0;
2109         }
2110         items[0] = &ipsl;
2111         sizes[0] = sizeof(ipsl);
2112         types[0] = 0;
2113
2114         (void) ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1);
2115 }
2116 #endif
2117
2118
2119 #ifdef  USE_INET6
2120 frentry_t *fr_checkicmp6matchingstate(ip, fin)
2121 ip6_t *ip;
2122 fr_info_t *fin;
2123 {
2124         register ipstate_t *is, **isp;
2125         register u_short sport, dport;
2126         register u_char pr;
2127         struct icmp6_hdr *ic, *oic;
2128         union i6addr dst, src;
2129         u_short savelen;
2130         fr_info_t ofin;
2131         tcphdr_t *tcp;
2132         frentry_t *fr;
2133         ip6_t *oip;
2134         int type;
2135         u_int hv;
2136
2137         /*
2138          * Does it at least have the return (basic) IP header ?
2139          * Only a basic IP header (no options) should be with
2140          * an ICMP error header.
2141          */
2142         if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN))
2143                 return NULL;
2144         ic = (struct icmp6_hdr *)fin->fin_dp;
2145         type = ic->icmp6_type;
2146         /*
2147          * If it's not an error type, then return
2148          */
2149         if ((type != ICMP6_DST_UNREACH) && (type != ICMP6_PACKET_TOO_BIG) &&
2150             (type != ICMP6_TIME_EXCEEDED) && (type != ICMP6_PARAM_PROB))
2151                 return NULL;
2152
2153         oip = (ip6_t *)((char *)ic + ICMPERR_ICMPHLEN);
2154         if (fin->fin_plen < sizeof(*oip))
2155                 return NULL;
2156
2157         if ((oip->ip6_nxt != IPPROTO_TCP) && (oip->ip6_nxt != IPPROTO_UDP) &&
2158             (oip->ip6_nxt != IPPROTO_ICMPV6))
2159                 return NULL;
2160
2161         bzero((char *)&ofin, sizeof(ofin));
2162         ofin.fin_out = !fin->fin_out;
2163         ofin.fin_ifp = fin->fin_ifp;
2164         ofin.fin_v = 6;
2165
2166         if (oip->ip6_nxt == IPPROTO_ICMPV6) {
2167                 oic = (struct icmp6_hdr *)(oip + 1);
2168                 /*
2169                  * a ICMP error can only be generated as a result of an
2170                  * ICMP query, not as the response on an ICMP error
2171                  *
2172                  * XXX theoretically ICMP_ECHOREP and the other reply's are
2173                  * ICMP query's as well, but adding them here seems strange XXX
2174                  */
2175                  if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
2176                         return NULL;
2177
2178                 /*
2179                  * perform a lookup of the ICMP packet in the state table
2180                  */
2181                 hv = (pr = oip->ip6_nxt);
2182                 src.in6 = oip->ip6_src;
2183                 hv += src.in4.s_addr;
2184                 dst.in6 = oip->ip6_dst;
2185                 hv += dst.in4.s_addr;
2186                 hv += oic->icmp6_id;
2187                 hv += oic->icmp6_seq;
2188                 hv %= fr_statesize;
2189
2190                 oip->ip6_plen = ntohs(oip->ip6_plen);
2191                 fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
2192                 oip->ip6_plen = htons(oip->ip6_plen);
2193
2194                 READ_ENTER(&ipf_state);
2195                 for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
2196                         if ((is->is_p == pr) &&
2197                             (oic->icmp6_id == is->is_icmp.ics_id) &&
2198                             (oic->icmp6_seq == is->is_icmp.ics_seq) &&
2199                             fr_matchsrcdst(is, src, dst, &ofin, NULL)) {
2200                                 /*
2201                                  * in the state table ICMP query's are stored
2202                                  * with the type of the corresponding ICMP
2203                                  * response. Correct here
2204                                  */
2205                                 if (((is->is_type == ICMP6_ECHO_REPLY) &&
2206                                      (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
2207                                      (is->is_type - 1 == oic->icmp6_type )) {
2208                                         ips_stats.iss_hits++;
2209                                         is->is_pkts++;
2210                                         is->is_bytes += fin->fin_plen;
2211                                         return is->is_rule;
2212                                 }
2213                         }
2214                 RWLOCK_EXIT(&ipf_state);
2215
2216                 return NULL;
2217         }
2218
2219         tcp = (tcphdr_t *)(oip + 1);
2220         dport = tcp->th_dport;
2221         sport = tcp->th_sport;
2222
2223         hv = (pr = oip->ip6_nxt);
2224         src.in6 = oip->ip6_src;
2225         hv += src.in4.s_addr;
2226         hv += src.i6[1];
2227         hv += src.i6[2];
2228         hv += src.i6[3];
2229         dst.in6 = oip->ip6_dst;
2230         hv += dst.in4.s_addr;
2231         hv += dst.i6[1];
2232         hv += dst.i6[2];
2233         hv += dst.i6[3];
2234         hv += dport;
2235         hv += sport;
2236         hv %= fr_statesize;
2237         /*
2238          * we make an fin entry to be able to feed it to
2239          * matchsrcdst note that not all fields are encessary
2240          * but this is the cleanest way. Note further we fill
2241          * in fin_mp such that if someone uses it we'll get
2242          * a kernel panic. fr_matchsrcdst does not use this.
2243          *
2244          * watch out here, as ip is in host order and oip in network
2245          * order. Any change we make must be undone afterwards.
2246          */
2247         savelen = oip->ip6_plen;
2248         oip->ip6_plen = ip->ip6_plen - sizeof(*ip) - ICMPERR_ICMPHLEN;
2249         fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
2250         oip->ip6_plen = savelen;
2251         READ_ENTER(&ipf_state);
2252         for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
2253                 /*
2254                  * Only allow this icmp though if the
2255                  * encapsulated packet was allowed through the
2256                  * other way around. Note that the minimal amount
2257                  * of info present does not allow for checking against
2258                  * tcp internals such as seq and ack numbers.
2259                  */
2260                 if ((is->is_p == pr) && (is->is_v == 6) &&
2261                     fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
2262                         fr = is->is_rule;
2263                         ips_stats.iss_hits++;
2264                         is->is_pkts++;
2265                         is->is_bytes += fin->fin_plen;
2266                         /*
2267                          * we deliberately do not touch the timeouts
2268                          * for the accompanying state table entry.
2269                          * It remains to be seen if that is correct. XXX
2270                          */
2271                         RWLOCK_EXIT(&ipf_state);
2272                         return fr;
2273                 }
2274         }
2275         RWLOCK_EXIT(&ipf_state);
2276         return NULL;
2277 }
2278 #endif