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