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