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