Major cleanup of the base IPFilter:
[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.7 2004/07/28 00:22:37 hmp 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         /*
616          * Copy and calculate...
617          */
618         hv = (is->is_p = fin->fin_fi.fi_p);
619         is->is_src = fin->fin_fi.fi_src;
620         hv += is->is_saddr;
621         is->is_dst = fin->fin_fi.fi_dst;
622         hv += is->is_daddr;
623 #ifdef  USE_INET6
624         if (fin->fin_v == 6) {
625                 if ((is->is_p == IPPROTO_ICMPV6) &&
626                     IN6_IS_ADDR_MULTICAST(&is->is_dst.in6)) {
627                         /*
628                          * So you can do keep state with neighbour discovery.
629                          */
630                         flags |= FI_W_DADDR;
631                         hv -= is->is_daddr;
632                 } else {
633                         hv += is->is_dst.i6[1];
634                         hv += is->is_dst.i6[2];
635                         hv += is->is_dst.i6[3];
636                 }
637                 hv += is->is_src.i6[1];
638                 hv += is->is_src.i6[2];
639                 hv += is->is_src.i6[3];
640         }
641 #endif
642
643         switch (is->is_p)
644         {
645                 int off;
646
647 #ifdef  USE_INET6
648         case IPPROTO_ICMPV6 :
649                 ic = (struct icmp *)fin->fin_dp;
650                 if ((ic->icmp_type & ICMP6_INFOMSG_MASK) == 0)
651                         return NULL;
652
653                 switch (ic->icmp_type)
654                 {
655                 case ICMP6_ECHO_REQUEST :
656                         is->is_icmp.ics_type = ic->icmp_type;
657                         hv += (is->is_icmp.ics_id = ic->icmp_id);
658                         hv += (is->is_icmp.ics_seq = ic->icmp_seq);
659                         break;
660                 case ICMP6_MEMBERSHIP_QUERY :
661                 case ND_ROUTER_SOLICIT :
662                 case ND_NEIGHBOR_SOLICIT :
663                 case ICMP6_NI_QUERY :
664                         is->is_icmp.ics_type = ic->icmp_type;
665                         break;
666                 default :
667                         return NULL;
668                 }
669                 ATOMIC_INCL(ips_stats.iss_icmp);
670                 is->is_age = fr_icmptimeout;
671                 break;
672 #endif
673         case IPPROTO_ICMP :
674                 ic = (struct icmp *)fin->fin_dp;
675
676                 switch (ic->icmp_type)
677                 {
678                 case ICMP_ECHO :
679                 case ICMP_TSTAMP :
680                 case ICMP_IREQ :
681                 case ICMP_MASKREQ :
682                         is->is_icmp.ics_type = ic->icmp_type;
683                         hv += (is->is_icmp.ics_id = ic->icmp_id);
684                         hv += (is->is_icmp.ics_seq = ic->icmp_seq);
685                         break;
686                 default :
687                         return NULL;
688                 }
689                 ATOMIC_INCL(ips_stats.iss_icmp);
690                 is->is_age = fr_icmptimeout;
691                 break;
692         case IPPROTO_TCP :
693                 tcp = (tcphdr_t *)fin->fin_dp;
694
695                 if (tcp->th_flags & TH_RST)
696                         return NULL;
697                 /*
698                  * The endian of the ports doesn't matter, but the ack and
699                  * sequence numbers do as we do mathematics on them later.
700                  */
701                 is->is_sport = htons(fin->fin_data[0]);
702                 is->is_dport = htons(fin->fin_data[1]);
703                 if ((flags & (FI_W_DPORT|FI_W_SPORT)) == 0) {
704                         hv += is->is_sport;
705                         hv += is->is_dport;
706                 }
707                 if ((flags & FI_IGNOREPKT) == 0) {
708                         is->is_send = ntohl(tcp->th_seq) + fin->fin_dlen -
709                                       (off = (tcp->th_off << 2)) +
710                                       ((tcp->th_flags & TH_SYN) ? 1 : 0) +
711                                       ((tcp->th_flags & TH_FIN) ? 1 : 0);
712                         is->is_maxsend = is->is_send;
713
714                         if ((tcp->th_flags & TH_SYN) &&
715                             ((tcp->th_off << 2) >= (sizeof(*tcp) + 4))) {
716                                 ws = fr_tcpoptions(tcp);
717                                 if (ws >= 0)
718                                         is->is_swscale = ws;
719                         }
720                 }
721
722                 is->is_maxdwin = 1;
723                 is->is_maxswin = ntohs(tcp->th_win);
724                 if (is->is_maxswin == 0)
725                         is->is_maxswin = 1;
726
727                 if ((tcp->th_flags & TH_OPENING) == TH_SYN)
728                         is->is_fsm = 1;
729
730                 /*
731                  * If we're creating state for a starting connection, start the
732                  * timer on it as we'll never see an error if it fails to
733                  * connect.
734                  */
735                 ATOMIC_INCL(ips_stats.iss_tcp);
736                 break;
737
738         case IPPROTO_UDP :
739                 tcp = (tcphdr_t *)fin->fin_dp;
740
741                 is->is_sport = htons(fin->fin_data[0]);
742                 is->is_dport = htons(fin->fin_data[1]);
743                 if ((flags & (FI_W_DPORT|FI_W_SPORT)) == 0) {
744                         hv += is->is_sport;
745                         hv += is->is_dport;
746                 }
747                 ATOMIC_INCL(ips_stats.iss_udp);
748                 is->is_age = fr_udptimeout;
749                 break;
750         default :
751                 is->is_age = fr_udptimeout;
752                 break;
753         }
754
755         KMALLOC(is, ipstate_t *);
756         if (is == NULL) {
757                 ATOMIC_INCL(ips_stats.iss_nomem);
758                 return NULL;
759         }
760         bcopy((char *)&ips, (char *)is, sizeof(*is));
761         hv %= fr_statesize;
762         is->is_hv = hv;
763         is->is_rule = fin->fin_fr;
764         if (is->is_rule != NULL) {
765                 is->is_group = is->is_rule->fr_group;
766                 ATOMIC_INC32(is->is_rule->fr_ref);
767                 pass = is->is_rule->fr_flags;
768                 is->is_frage[0] = is->is_rule->fr_age[0];
769                 is->is_frage[1] = is->is_rule->fr_age[1];
770                 if (is->is_frage[0] != 0)
771                         is->is_age = is->is_frage[0];
772
773                 is->is_ifp[(out << 1) + 1] = is->is_rule->fr_ifas[1];
774                 is->is_ifp[(1 - out) << 1] = is->is_rule->fr_ifas[2];
775                 is->is_ifp[((1 - out) << 1) + 1] = is->is_rule->fr_ifas[3];
776
777                 if (((ifp = is->is_rule->fr_ifas[1]) != NULL) &&
778                     (ifp != (void *)-1))
779                         strncpy(is->is_ifname[(out << 1) + 1],
780                                 IFNAME(ifp), IFNAMSIZ);
781                 if (((ifp = is->is_rule->fr_ifas[2]) != NULL) &&
782                     (ifp != (void *)-1))
783                         strncpy(is->is_ifname[(1 - out) << 1],
784                                 IFNAME(ifp), IFNAMSIZ);
785                 if (((ifp = is->is_rule->fr_ifas[3]) != NULL) &&
786                     (ifp != (void *)-1))
787                         strncpy(is->is_ifname[((1 - out) << 1) + 1],
788                                 IFNAME(ifp), IFNAMSIZ);
789         } else
790                 pass = fr_flags;
791
792         is->is_ifp[out << 1] = fin->fin_ifp;
793         strncpy(is->is_ifname[out << 1], IFNAME(fin->fin_ifp), IFNAMSIZ);
794
795         WRITE_ENTER(&ipf_state);
796
797         is->is_pass = pass;
798         if ((flags & FI_IGNOREPKT) == 0) {
799                 is->is_pkts = 1;
800                 is->is_bytes = fin->fin_dlen + fin->fin_hlen;
801         }
802         /*
803          * We want to check everything that is a property of this packet,
804          * but we don't (automatically) care about it's fragment status as
805          * this may change.
806          */
807         is->is_v = fin->fin_v;
808         is->is_rulen = fin->fin_rule;
809         is->is_opt = fin->fin_fi.fi_optmsk;
810         is->is_optmsk = 0xffffffff;
811         is->is_sec = fin->fin_fi.fi_secmsk;
812         is->is_secmsk = 0xffff;
813         is->is_auth = fin->fin_fi.fi_auth;
814         is->is_authmsk = 0xffff;
815         is->is_flags = fin->fin_fl & FI_CMP;
816         is->is_flags |= FI_CMP << 4;
817         is->is_flags |= flags & (FI_WILDP|FI_WILDA);
818         if (flags & (FI_WILDP|FI_WILDA))
819                 ips_wild++;
820
821         if (pass & FR_LOGFIRST)
822                 is->is_pass &= ~(FR_LOGFIRST|FR_LOG);
823         fr_stinsert(is);
824         is->is_me = stsave;
825         if (is->is_p == IPPROTO_TCP) {
826                 fr_tcp_age(&is->is_age, is->is_state, fin,
827                            0, is->is_fsm); /* 0 = packet from the source */
828         }
829 #ifdef  IPFILTER_LOG
830         ipstate_log(is, ISL_NEW);
831 #endif
832         RWLOCK_EXIT(&ipf_state);
833         fin->fin_rev = IP6NEQ(is->is_dst, fin->fin_fi.fi_dst);
834         if ((fin->fin_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
835                 ipfr_newfrag(ip, fin);
836         return is;
837 }
838
839
840 static int fr_tcpoptions(tcp)
841 tcphdr_t *tcp;
842 {
843         u_char *opt, *last;
844         int wscale;
845
846         opt = (u_char *) (tcp + 1);
847         last = ((u_char *)tcp) + (tcp->th_off << 2);
848
849         /* If we don't find wscale here, we need to clear it */
850         wscale = -2;
851
852         /* Termination condition picked such that opt[0 .. 2] exist */
853         while ((opt < last - 2)  && (*opt != TCPOPT_EOL)) {
854                 switch (*opt) {
855                 case TCPOPT_NOP:
856                         opt++;
857                         continue;
858                 case TCPOPT_WSCALE:
859                         /* Proper length ? */
860                         if (opt[1] == 3) {
861                                 if (opt[2] > 14)
862                                         wscale = 14;
863                                 else
864                                         wscale = opt[2];
865                         }
866                         break;
867                 default:
868                         /* Unknown options must be two bytes+ */
869                         if (opt[1] < 2)
870                                 break;
871                         opt += opt[1];
872                         continue;
873                 }
874                 break;
875         }
876         return wscale;
877 }
878
879
880
881 /*
882  * check to see if a packet with TCP headers fits within the TCP window.
883  * change timeout depending on whether new packet is a SYN-ACK returning for a
884  * SYN or a RST or FIN which indicate time to close up shop.
885  */
886 int fr_tcpstate(is, fin, ip, tcp)
887 ipstate_t *is;
888 fr_info_t *fin;
889 ip_t *ip;
890 tcphdr_t *tcp;
891 {
892         tcp_seq seq, ack, end;
893         int ackskew;
894         tcpdata_t  *fdata, *tdata;
895         u_32_t  win, maxwin;
896         int ret = 0, off;
897         int source;
898         int wscale;
899
900         /*
901          * Find difference between last checked packet and this packet.
902          */
903         source = IP6EQ(fin->fin_fi.fi_src, is->is_src);
904         if (source && (ntohs(is->is_sport) != fin->fin_data[0]))
905                 source = 0;
906         fdata = &is->is_tcp.ts_data[!source];
907         tdata = &is->is_tcp.ts_data[source];
908         off = tcp->th_off << 2;
909         seq = ntohl(tcp->th_seq);
910         ack = ntohl(tcp->th_ack);
911         win = ntohs(tcp->th_win);
912         end = seq + fin->fin_dlen - off +
913                ((tcp->th_flags & TH_SYN) ? 1 : 0) +
914                ((tcp->th_flags & TH_FIN) ? 1 : 0);
915
916
917         if ((tcp->th_flags & TH_SYN) && (off >= sizeof(*tcp) + 4))
918                 wscale = fr_tcpoptions(tcp);
919         else
920                 wscale = -1;
921
922         MUTEX_ENTER(&is->is_lock);
923
924         if (wscale >= 0)
925                 fdata->td_wscale = wscale;
926         else if (wscale == -2)
927                 fdata->td_wscale = tdata->td_wscale = 0;
928         if (!(tcp->th_flags & TH_SYN))
929                 win <<= fdata->td_wscale;
930
931         if ((fdata->td_end == 0) &&
932             (!is->is_fsm || ((tcp->th_flags & TH_OPENING) == TH_OPENING))) {
933                 /*
934                  * Must be a (outgoing) SYN-ACK in reply to a SYN.
935                  */
936                 fdata->td_end = end;
937                 fdata->td_maxwin = 1;
938                 fdata->td_maxend = end + win;
939                 if (win == 0)
940                         fdata->td_maxend++;
941         }
942
943         if (!(tcp->th_flags & TH_ACK)) {  /* Pretend an ack was sent */
944                 ack = tdata->td_end;
945         } else if (((tcp->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) &&
946                    (ack == 0)) {
947                 /* gross hack to get around certain broken tcp stacks */
948                 ack = tdata->td_end;
949         }
950
951         if (seq == end)
952                 seq = end = fdata->td_end;
953
954         maxwin = tdata->td_maxwin;
955         ackskew = tdata->td_end - ack;
956
957 #define SEQ_GE(a,b)     ((int)((a) - (b)) >= 0)
958 #define SEQ_GT(a,b)     ((int)((a) - (b)) > 0)
959         if ((SEQ_GE(fdata->td_maxend, end)) &&
960             (SEQ_GE(seq, fdata->td_end - maxwin)) &&
961 /* XXX what about big packets */
962 #define MAXACKWINDOW 66000
963             (-ackskew <= (MAXACKWINDOW << tdata->td_wscale)) &&
964             ( ackskew <= (MAXACKWINDOW << tdata->td_wscale))) {
965
966                 /* if ackskew < 0 then this should be due to fragmented
967                  * packets. There is no way to know the length of the
968                  * total packet in advance.
969                  * We do know the total length from the fragment cache though.
970                  * Note however that there might be more sessions with
971                  * exactly the same source and destination parameters in the
972                  * state cache (and source and destination is the only stuff
973                  * that is saved in the fragment cache). Note further that
974                  * some TCP connections in the state cache are hashed with
975                  * sport and dport as well which makes it not worthwhile to
976                  * look for them.
977                  * Thus, when ackskew is negative but still seems to belong
978                  * to this session, we bump up the destinations end value.
979                  */
980                 /*
981                  * Nearing end of connection, start timeout.
982                  */
983                 /* source ? 0 : 1 -> !source */
984                 if (fr_tcp_age(&is->is_age, is->is_state, fin, !source,
985                                (int)is->is_fsm) == 0) {
986                         if (ackskew < 0)
987                                 tdata->td_end = ack;
988
989                         /* update max window seen */
990                         if (fdata->td_maxwin < win)
991                                 fdata->td_maxwin = win;
992                         if (SEQ_GT(end, fdata->td_end))
993                                 fdata->td_end = end;
994                         if (SEQ_GE(ack + win, tdata->td_maxend)) {
995                                 tdata->td_maxend = ack + win;
996                                 if (win == 0)
997                                         tdata->td_maxend++;
998                         }
999
1000                         ATOMIC_INCL(ips_stats.iss_hits);
1001                         ret = 1;
1002                 }
1003         }
1004         MUTEX_EXIT(&is->is_lock);
1005         if ((ret == 0) && ((tcp->th_flags & TH_OPENING) != TH_SYN))
1006                 fin->fin_misc |= FM_BADSTATE;
1007         return ret;
1008 }
1009
1010
1011 /*
1012  * Match a state table entry against an IP packet.
1013  */
1014 static int fr_matchsrcdst(is, src, dst, fin, tcp)
1015 ipstate_t *is;
1016 union i6addr src, dst;
1017 fr_info_t *fin;
1018 tcphdr_t *tcp;
1019 {
1020         int ret = 0, rev, out, flags, idx;
1021         u_short sp, dp;
1022         void *ifp;
1023
1024         rev = IP6NEQ(is->is_dst, dst);
1025         ifp = fin->fin_ifp;
1026         out = fin->fin_out;
1027         flags = is->is_flags & (FI_WILDA|FI_WILDP);
1028         sp = 0;
1029         dp = 0;
1030
1031         if (tcp != NULL) {
1032                 flags = is->is_flags;
1033                 sp = tcp->th_sport;
1034                 dp = tcp->th_dport;
1035                 if (!rev) {
1036                         if (!(flags & FI_W_SPORT) && (sp != is->is_sport))
1037                                 rev = 1;
1038                         else if (!(flags & FI_W_DPORT) && (dp != is->is_dport))
1039                                 rev = 1;
1040                 }
1041         }
1042
1043         idx = (out << 1) + rev;
1044
1045         if ((is->is_ifp[idx] == NULL && 
1046              (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*')) ||
1047             is->is_ifp[idx] == ifp)
1048                 ret = 1;
1049
1050         if (ret == 0)
1051                 return 0;
1052         ret = 0;
1053
1054         if (rev == 0) {
1055                 if ((IP6EQ(is->is_dst, dst) || (flags & FI_W_DADDR)) &&
1056                     (IP6EQ(is->is_src, src) || (flags & FI_W_SADDR)) &&
1057                     (!tcp || ((sp == is->is_sport || flags & FI_W_SPORT) &&
1058                      (dp == is->is_dport || flags & FI_W_DPORT)))) {
1059                         ret = 1;
1060                 }
1061         } else {
1062                 if ((IP6EQ(is->is_dst, src) || (flags & FI_W_DADDR)) &&
1063                     (IP6EQ(is->is_src, dst) || (flags & FI_W_SADDR)) &&
1064                     (!tcp || ((sp == is->is_dport || flags & FI_W_DPORT) &&
1065                      (dp == is->is_sport || flags & FI_W_SPORT)))) {
1066                         ret = 1;
1067                 }
1068         }
1069         if (ret == 0)
1070                 return 0;
1071
1072         /*
1073          * Whether or not this should be here, is questionable, but the aim
1074          * is to get this out of the main line.
1075          */
1076         if (tcp == NULL)
1077                 flags = is->is_flags & (FI_CMP|(FI_CMP<<4));
1078
1079         if (((fin->fin_fl & (flags >> 4)) != (flags & FI_CMP)) ||
1080             (fin->fin_fi.fi_optmsk != is->is_opt) ||
1081             (fin->fin_fi.fi_secmsk != is->is_sec) ||
1082             (fin->fin_fi.fi_auth != is->is_auth))
1083                 return 0;
1084
1085         flags = is->is_flags & (FI_WILDA|FI_WILDP);
1086         if ((flags & (FI_W_SADDR|FI_W_DADDR))) {
1087                 if ((flags & FI_W_SADDR) != 0) {
1088                         if (rev == 0) {
1089                                 is->is_src = fin->fin_fi.fi_src;
1090                         } else {
1091                                 is->is_src = fin->fin_fi.fi_dst;
1092                         }
1093                 } else if ((flags & FI_W_DADDR) != 0) {
1094                         if (rev == 0) {
1095                                 is->is_dst = fin->fin_fi.fi_dst;
1096                         } else {
1097                                 is->is_dst = fin->fin_fi.fi_src;
1098                         }
1099                 }
1100                 is->is_flags &= ~(FI_W_SADDR|FI_W_DADDR);
1101                 if ((is->is_flags & (FI_WILDA|FI_WILDP)) == 0)
1102                         ips_wild--;
1103         }
1104
1105         if ((flags & (FI_W_SPORT|FI_W_DPORT))) {
1106                 if ((flags & FI_W_SPORT) != 0) {
1107                         if (rev == 0) {
1108                                 is->is_sport = sp;
1109                                 is->is_send = htonl(tcp->th_seq);
1110                         } else {
1111                                 is->is_sport = dp;
1112                                 is->is_send = htonl(tcp->th_ack);
1113                         }
1114                         is->is_maxsend = is->is_send + 1;
1115                 } else if ((flags & FI_W_DPORT) != 0) {
1116                         if (rev == 0) {
1117                                 is->is_dport = dp;
1118                                 is->is_dend = htonl(tcp->th_ack);
1119                         } else {
1120                                 is->is_dport = sp;
1121                                 is->is_dend = htonl(tcp->th_seq);
1122                         }
1123                         is->is_maxdend = is->is_dend + 1;
1124                 }
1125                 is->is_flags &= ~(FI_W_SPORT|FI_W_DPORT);
1126                 ips_wild--;
1127         }
1128
1129         ret = -1;
1130
1131         if (is->is_ifp[idx] == NULL &&
1132             (*is->is_ifname[idx] == '\0' || *is->is_ifname[idx] == '*'))
1133                 ret = idx;
1134
1135         if (ret >= 0) {
1136                 is->is_ifp[ret] = ifp;
1137                 strncpy(is->is_ifname[ret], IFNAME(ifp),
1138                         sizeof(is->is_ifname[ret]));
1139         }
1140         fin->fin_rev = rev;
1141         return 1;
1142 }
1143
1144 static int fr_matchicmpqueryreply(v, is, icmp, rev)
1145 int v;
1146 ipstate_t *is;
1147 icmphdr_t *icmp;
1148 {
1149         if (v == 4) {
1150                 /*
1151                  * If we matched its type on the way in, then when going out
1152                  * it will still be the same type.
1153                  */
1154                 if ((!rev && (icmp->icmp_type == is->is_type)) ||
1155                     (rev && (icmpreplytype4[is->is_type] == icmp->icmp_type))) {
1156                         if (icmp->icmp_type != ICMP_ECHOREPLY)
1157                                 return 1;
1158                         if ((icmp->icmp_id == is->is_icmp.ics_id) &&
1159                             (icmp->icmp_seq == is->is_icmp.ics_seq))
1160                                 return 1;
1161                 }
1162         }
1163 #ifdef  USE_INET6
1164         else if (is->is_v == 6) {
1165                 if ((!rev && (icmp->icmp_type == is->is_type)) ||
1166                     (rev && (icmpreplytype6[is->is_type] == icmp->icmp_type))) {
1167                         if (icmp->icmp_type != ICMP6_ECHO_REPLY)
1168                                 return 1;
1169                         if ((icmp->icmp_id == is->is_icmp.ics_id) &&
1170                             (icmp->icmp_seq == is->is_icmp.ics_seq))
1171                                 return 1;
1172                 }
1173         }
1174 #endif
1175         return 0;
1176 }
1177
1178 static frentry_t *fr_checkicmpmatchingstate(ip, fin)
1179 ip_t *ip;
1180 fr_info_t *fin;
1181 {
1182         ipstate_t *is, **isp;
1183         u_short sport, dport;
1184         u_char  pr;
1185         u_short savelen, ohlen;
1186         union i6addr dst, src;
1187         struct icmp *ic;
1188         icmphdr_t *icmp;
1189         fr_info_t ofin;
1190         int type, len;
1191         tcphdr_t *tcp;
1192         frentry_t *fr;
1193         ip_t *oip;
1194         u_int hv;
1195
1196         /*
1197          * Does it at least have the return (basic) IP header ?
1198          * Only a basic IP header (no options) should be with
1199          * an ICMP error header.
1200          */
1201         if (((ip->ip_v != 4) || (ip->ip_hl != 5)) ||
1202             (fin->fin_plen < ICMPERR_MINPKTLEN))
1203                 return NULL;
1204
1205         ic = (struct icmp *)fin->fin_dp;
1206         type = ic->icmp_type;
1207         /*
1208          * If it's not an error type, then return
1209          */
1210         if ((type != ICMP_UNREACH) && (type != ICMP_SOURCEQUENCH) &&
1211             (type != ICMP_REDIRECT) && (type != ICMP_TIMXCEED) &&
1212             (type != ICMP_PARAMPROB))
1213                 return NULL;
1214
1215         oip = (ip_t *)((char *)ic + ICMPERR_ICMPHLEN);
1216         ohlen = oip->ip_hl << 2;
1217         /*
1218          * Check if the at least the old IP header (with options) and
1219          * 8 bytes of payload is present.
1220          */
1221         if (fin->fin_plen < ICMPERR_MAXPKTLEN + ohlen - sizeof(*oip))
1222                 return NULL;
1223
1224         /*
1225          * Sanity checks.
1226          */
1227         len = fin->fin_dlen - ICMPERR_ICMPHLEN;
1228         if ((len <= 0) || (ohlen > len))
1229                 return NULL;
1230
1231         /*
1232          * Is the buffer big enough for all of it ?  It's the size of the IP
1233          * header claimed in the encapsulated part which is of concern.  It
1234          * may be too big to be in this buffer but not so big that it's
1235          * outside the ICMP packet, leading to TCP deref's causing problems.
1236          * This is possible because we don't know how big oip_hl is when we
1237          * do the pullup early in fr_check() and thus can't guarantee it is
1238          * all here now.
1239          */
1240 #ifdef  _KERNEL
1241         {
1242         mb_t *m;
1243
1244 # if SOLARIS
1245         m = fin->fin_qfm;
1246         if ((char *)oip + len > (char *)m->b_wptr)
1247                 return NULL;
1248 # else
1249         m = *(mb_t **)fin->fin_mp;
1250         if ((char *)oip + len > (char *)ip + m->m_len)
1251                 return NULL;
1252 # endif
1253         }
1254 #endif
1255
1256         /*
1257          * in the IPv4 case we must zero the i6addr union otherwise
1258          * the IP6EQ and IP6NEQ macros produce the wrong results because
1259          * of the 'junk' in the unused part of the union
1260          */
1261         bzero((char *)&src, sizeof(src));
1262         bzero((char *)&dst, sizeof(dst));
1263         bzero((char *)&ofin, sizeof(ofin));
1264         /*
1265          * We make an fin entry to be able to feed it to
1266          * matchsrcdst.  Note that not all fields are encessary
1267          * but this is the cleanest way. Note further that we
1268          * fill in fin_mp such that if someone uses it we'll get
1269          * a kernel panic. fr_matchsrcdst does not use this.
1270          */
1271         ofin.fin_ifp = fin->fin_ifp;
1272         ofin.fin_out = !fin->fin_out;
1273         ofin.fin_mp = NULL;
1274         ofin.fin_v = 4;
1275         /*
1276          * watch out here, as ip is in host order and oip in network
1277          * order. Any change we make must be undone afterwards, like
1278          * oip->ip_off - it is still in network byte order so fix it.
1279          */
1280         savelen = oip->ip_len;
1281         oip->ip_len = len;
1282         oip->ip_off = ntohs(oip->ip_off);
1283         (void) fr_makefrip(ohlen, oip, &ofin);
1284         /*
1285          * Reset the short flag here because in fr_matchsrcdst() the flags
1286          * for the current packet (fin_fl) are compared against * those for
1287          * the existing session.
1288          */
1289         ofin.fin_fl &= ~FI_SHORT;
1290
1291         /*
1292          * Put old values of ip_len and ip_off back as we don't know
1293          * if we have to forward the packet (or process it again.
1294          */
1295         oip->ip_len = savelen;
1296         oip->ip_off = htons(oip->ip_off);
1297
1298 #if SOLARIS
1299         ofin.fin_qfm = NULL;
1300 #endif
1301         fr = NULL;
1302
1303         switch (oip->ip_p)
1304         {
1305         case IPPROTO_ICMP :
1306                 icmp = (icmphdr_t *)((char *)oip + ohlen);
1307
1308                 /*
1309                  * an ICMP error can only be generated as a result of an
1310                  * ICMP query, not as the response on an ICMP error
1311                  *
1312                  * XXX theoretically ICMP_ECHOREP and the other reply's are
1313                  * ICMP query's as well, but adding them here seems strange XXX
1314                  */
1315                  if ((icmp->icmp_type != ICMP_ECHO) &&
1316                      (icmp->icmp_type != ICMP_TSTAMP) &&
1317                      (icmp->icmp_type != ICMP_IREQ) &&
1318                      (icmp->icmp_type != ICMP_MASKREQ))
1319                         return NULL;
1320
1321                 /*
1322                  * perform a lookup of the ICMP packet in the state table
1323                  */
1324                 hv = (pr = oip->ip_p);
1325                 src.in4 = oip->ip_src;
1326                 hv += src.in4.s_addr;
1327                 dst.in4 = oip->ip_dst;
1328                 hv += dst.in4.s_addr;
1329                 hv += icmp->icmp_id;
1330                 hv += icmp->icmp_seq;
1331                 hv %= fr_statesize;
1332
1333                 READ_ENTER(&ipf_state);
1334                 for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
1335                         if ((is->is_p == pr) && (is->is_v == 4) &&
1336                             (is->is_icmppkts < is->is_pkts) &&
1337                             fr_matchsrcdst(is, src, dst, &ofin, NULL) &&
1338                             fr_matchicmpqueryreply(is->is_v, is, icmp,
1339                                                    fin->fin_rev)) {
1340                                 ips_stats.iss_hits++;
1341                                 is->is_icmppkts++;
1342                                 is->is_bytes += ip->ip_len;
1343                                 fr = is->is_rule;
1344                                 break;
1345                         }
1346                 RWLOCK_EXIT(&ipf_state);
1347                 return fr;
1348         
1349         case IPPROTO_TCP :
1350         case IPPROTO_UDP :
1351                 if (fin->fin_plen < ICMPERR_MAXPKTLEN)
1352                         return NULL;
1353                 break;
1354         default :
1355                 return NULL;
1356         }
1357
1358         tcp = (tcphdr_t *)((char *)oip + ohlen);
1359         dport = tcp->th_dport;
1360         sport = tcp->th_sport;
1361
1362         hv = (pr = oip->ip_p);
1363         src.in4 = oip->ip_src;
1364         hv += src.in4.s_addr;
1365         dst.in4 = oip->ip_dst;
1366         hv += dst.in4.s_addr;
1367         hv += dport;
1368         hv += sport;
1369         hv %= fr_statesize;
1370
1371         READ_ENTER(&ipf_state);
1372         for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1373                 /*
1374                  * Only allow this icmp though if the
1375                  * encapsulated packet was allowed through the
1376                  * other way around. Note that the minimal amount
1377                  * of info present does not allow for checking against
1378                  * tcp internals such as seq and ack numbers.  Only the
1379                  * ports are known to be present and can be even if the
1380                  * short flag is set.
1381                  */
1382                 if ((is->is_p == pr) && (is->is_v == 4) &&
1383                     (is->is_icmppkts < is->is_pkts) &&
1384                     fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
1385                         fr = is->is_rule;
1386                         ips_stats.iss_hits++;
1387                         is->is_icmppkts++;
1388                         is->is_bytes += fin->fin_plen;
1389                         /*
1390                          * we deliberately do not touch the timeouts
1391                          * for the accompanying state table entry.
1392                          * It remains to be seen if that is correct. XXX
1393                          */
1394                         break;
1395                 }
1396         }
1397         RWLOCK_EXIT(&ipf_state);
1398         return fr;
1399 }
1400
1401
1402 /*
1403  * Move a state hash table entry from its old location at is->is_hv to
1404  * its new location, indexed by hv % fr_statesize.
1405  */
1406 static void fr_ipsmove(isp, is, hv)
1407 ipstate_t **isp, *is;
1408 u_int hv;
1409 {
1410         u_int hvm;
1411
1412         hvm = is->is_hv;
1413         /*
1414          * Remove the hash from the old location...
1415          */
1416         if (is->is_hnext)
1417                 is->is_hnext->is_phnext = isp;
1418         *isp = is->is_hnext;
1419         if (ips_table[hvm] == NULL)
1420                 ips_stats.iss_inuse--;
1421
1422         /*
1423          * ...and put the hash in the new one.
1424          */
1425         hvm = hv % fr_statesize;
1426         is->is_hv = hvm;
1427         isp = &ips_table[hvm];
1428         if (*isp)
1429                 (*isp)->is_phnext = &is->is_hnext;
1430         else
1431                 ips_stats.iss_inuse++;
1432         is->is_phnext = isp;
1433         is->is_hnext = *isp;
1434         *isp = is;
1435 }
1436
1437
1438 /*
1439  * Check if a packet has a registered state.
1440  */
1441 frentry_t *fr_checkstate(ip, fin)
1442 ip_t *ip;
1443 fr_info_t *fin;
1444 {
1445         union i6addr dst, src;
1446         ipstate_t *is, **isp;
1447         u_char pr;
1448         u_int hv, hvm, hlen, tryagain, pass, v;
1449         struct icmp *ic;
1450         frentry_t *fr;
1451         tcphdr_t *tcp;
1452         int rev;
1453
1454         if ((ips_list == NULL) || (fin->fin_off != 0) || fr_state_lock ||
1455             (fin->fin_fl & FI_SHORT))
1456                 return NULL;
1457
1458         is = NULL;
1459         hlen = fin->fin_hlen;
1460         tcp = (tcphdr_t *)((char *)ip + hlen);
1461         ic = (struct icmp *)tcp;
1462         hv = (pr = fin->fin_fi.fi_p);
1463         src = fin->fin_fi.fi_src;
1464         dst = fin->fin_fi.fi_dst;
1465         hv += src.in4.s_addr;
1466         hv += dst.in4.s_addr;
1467
1468         /*
1469          * Search the hash table for matching packet header info.
1470          * At the bottom of this switch statement, the following is expected:
1471          * is == NULL, no lock on ipf_state is held.
1472          * is != NULL, a lock on ipf_state is held.
1473          */
1474         v = fin->fin_fi.fi_v;
1475 #ifdef  USE_INET6
1476         if (v == 6) {
1477                 hv += fin->fin_fi.fi_src.i6[1];
1478                 hv += fin->fin_fi.fi_src.i6[2];
1479                 hv += fin->fin_fi.fi_src.i6[3];
1480
1481                 if ((fin->fin_p == IPPROTO_ICMPV6) &&
1482                     IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_dst.in6)) {
1483                         hv -= dst.in4.s_addr;
1484                 } else {
1485                         hv += fin->fin_fi.fi_dst.i6[1];
1486                         hv += fin->fin_fi.fi_dst.i6[2];
1487                         hv += fin->fin_fi.fi_dst.i6[3];
1488                 }
1489         }
1490 #endif
1491
1492         switch (fin->fin_p)
1493         {
1494 #ifdef  USE_INET6
1495         case IPPROTO_ICMPV6 :
1496                 tcp = NULL;
1497                 tryagain = 0;
1498                 if (v == 6) {
1499                         if ((ic->icmp_type == ICMP6_ECHO_REQUEST) ||
1500                             (ic->icmp_type == ICMP6_ECHO_REPLY)) {
1501                                 hv += ic->icmp_id;
1502                                 hv += ic->icmp_seq;
1503                         }
1504                 }
1505                 READ_ENTER(&ipf_state);
1506 icmp6again:
1507                 hvm = hv % fr_statesize;
1508                 for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1509                         if ((is->is_p == pr) && (is->is_v == v) &&
1510                             fr_matchsrcdst(is, src, dst, fin, NULL) &&
1511                             fr_matchicmpqueryreply(v, is, ic, fin->fin_rev)) {
1512                                 rev = fin->fin_rev;
1513                                 if (is->is_frage[rev] != 0)
1514                                         is->is_age = is->is_frage[rev];
1515                                 else if (rev != 0)
1516                                         is->is_age = fr_icmpacktimeout;
1517                                 else
1518                                         is->is_age = fr_icmptimeout;
1519                                 break;
1520                         }
1521
1522                 if (is != NULL) {
1523                         if (tryagain && !(is->is_flags & FI_W_DADDR)) {
1524                                 hv += fin->fin_fi.fi_src.i6[0];
1525                                 hv += fin->fin_fi.fi_src.i6[1];
1526                                 hv += fin->fin_fi.fi_src.i6[2];
1527                                 hv += fin->fin_fi.fi_src.i6[3];
1528                                 fr_ipsmove(isp, is, hv);
1529                                 MUTEX_DOWNGRADE(&ipf_state);
1530                         }
1531                         break;
1532                 }
1533                 RWLOCK_EXIT(&ipf_state);
1534
1535                 /*
1536                  * No matching icmp state entry. Perhaps this is a
1537                  * response to another state entry.
1538                  */
1539                 if ((ips_wild != 0) && (v == 6) && (tryagain == 0) &&
1540                     !IN6_IS_ADDR_MULTICAST(&fin->fin_fi.fi_src.in6)) {
1541                         hv -= fin->fin_fi.fi_src.i6[0];
1542                         hv -= fin->fin_fi.fi_src.i6[1];
1543                         hv -= fin->fin_fi.fi_src.i6[2];
1544                         hv -= fin->fin_fi.fi_src.i6[3];
1545                         tryagain = 1;
1546                         WRITE_ENTER(&ipf_state);
1547                         goto icmp6again;
1548                 }
1549
1550                 fr = fr_checkicmp6matchingstate((ip6_t *)ip, fin);
1551                 if (fr)
1552                         return fr;
1553                 break;
1554 #endif
1555         case IPPROTO_ICMP :
1556                 tcp = NULL;
1557                 if (v == 4) {
1558                         hv += ic->icmp_id;
1559                         hv += ic->icmp_seq;
1560                 }
1561                 hvm = hv % fr_statesize;
1562                 READ_ENTER(&ipf_state);
1563                 for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1564                         if ((is->is_p == pr) && (is->is_v == v) &&
1565                             fr_matchsrcdst(is, src, dst, fin, NULL) &&
1566                             fr_matchicmpqueryreply(v, is, ic, fin->fin_rev)) {
1567                                 rev = fin->fin_rev;
1568                                 if (is->is_frage[rev] != 0)
1569                                         is->is_age = is->is_frage[rev];
1570                                 else if (fin->fin_rev)
1571                                         is->is_age = fr_icmpacktimeout;
1572                                 else
1573                                         is->is_age = fr_icmptimeout;
1574                                 break;
1575                         }
1576
1577                 if (is != NULL)
1578                         break;
1579                 RWLOCK_EXIT(&ipf_state);
1580                 /*
1581                  * No matching icmp state entry. Perhaps this is a
1582                  * response to another state entry.
1583                  */
1584                 fr = fr_checkicmpmatchingstate(ip, fin);
1585                 if (fr)
1586                         return fr;
1587                 break;
1588         case IPPROTO_TCP :
1589                 /*
1590                  * Just plain ignore RST flag set with either FIN or SYN.
1591                  */
1592                 if ((tcp->th_flags & TH_RST) &&
1593                     ((tcp->th_flags & (TH_FIN|TH_SYN|TH_RST)) != TH_RST))
1594                         break;
1595         case IPPROTO_UDP :
1596             {
1597                 u_short dport, sport;
1598
1599                 dport = tcp->th_dport;
1600                 sport = tcp->th_sport;
1601                 tryagain = 0;
1602                 hv += dport;
1603                 hv += sport;
1604                 READ_ENTER(&ipf_state);
1605 retry_tcpudp:
1606                 hvm = hv % fr_statesize;
1607                 for (isp = &ips_table[hvm]; (is = *isp); isp = &is->is_hnext)
1608                         if ((is->is_p == pr) && (is->is_v == v) &&
1609                             fr_matchsrcdst(is, src, dst, fin, tcp)) {
1610                                 rev = fin->fin_rev;
1611                                 if ((pr == IPPROTO_TCP)) {
1612                                         if (!fr_tcpstate(is, fin, ip, tcp))
1613                                                 is = NULL;
1614                                 } else if ((pr == IPPROTO_UDP)) {
1615                                         if (is->is_frage[rev] != 0)
1616                                                 is->is_age = is->is_frage[rev];
1617                                         else if (fin->fin_rev)
1618                                                 is->is_age = fr_udpacktimeout;
1619                                         else
1620                                                 is->is_age = fr_udptimeout;
1621                                 }
1622                                 break;
1623                         }
1624                 if (is != NULL) {
1625                         if (tryagain &&
1626                             !(is->is_flags & (FI_WILDP|FI_WILDA))) {
1627                                 hv += dport;
1628                                 hv += sport;
1629                                 fr_ipsmove(isp, is, hv);
1630                                 MUTEX_DOWNGRADE(&ipf_state);
1631                         }
1632                         break;
1633                 }
1634
1635                 RWLOCK_EXIT(&ipf_state);
1636                 if (!tryagain && ips_wild) {
1637                         hv -= dport;
1638                         hv -= sport;
1639                         tryagain = 1;
1640                         WRITE_ENTER(&ipf_state);
1641                         goto retry_tcpudp;
1642                 }
1643                 break;
1644             }
1645         default :
1646                 tcp = NULL;
1647                 hv %= fr_statesize;
1648                 READ_ENTER(&ipf_state);
1649                 for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
1650                         if ((is->is_p == pr) && (is->is_v == v) &&
1651                             fr_matchsrcdst(is, src, dst, fin, NULL)) {
1652                                 rev = fin->fin_rev;
1653                                 if (is->is_frage[rev] != 0)
1654                                         is->is_age = is->is_frage[rev];
1655                                 else
1656                                         is->is_age = fr_udptimeout;
1657                                 break;
1658                         }
1659                 }
1660                 if (is == NULL) {
1661                         RWLOCK_EXIT(&ipf_state);
1662                 }
1663                 break;
1664         }
1665
1666         if (is == NULL) {
1667                 ATOMIC_INCL(ips_stats.iss_miss);
1668                 return NULL;
1669         }
1670
1671         MUTEX_ENTER(&is->is_lock);
1672         is->is_bytes += fin->fin_plen;
1673         ips_stats.iss_hits++;
1674         is->is_pkts++;
1675         MUTEX_EXIT(&is->is_lock);
1676         fr = is->is_rule;
1677         fin->fin_rule = is->is_rulen;
1678         if (fr != NULL) {
1679                 fin->fin_group = fr->fr_group;
1680                 fin->fin_icode = fr->fr_icode;
1681         }
1682         fin->fin_fr = fr;
1683         pass = is->is_pass;
1684         RWLOCK_EXIT(&ipf_state);
1685         if ((fin->fin_fl & FI_FRAG) && (pass & FR_KEEPFRAG))
1686                 ipfr_newfrag(ip, fin);
1687 #ifndef _KERNEL
1688         if ((tcp != NULL) && (tcp->th_flags & TCP_CLOSE))
1689                 fr_delstate(is);
1690 #endif
1691         return fr;
1692 }
1693
1694
1695 /*
1696  * Sync. state entries.  If interfaces come or go or just change position,
1697  * this is needed.
1698  */
1699 void ip_statesync(ifp)
1700 void *ifp;
1701 {
1702         ipstate_t *is;
1703         int i;
1704
1705         WRITE_ENTER(&ipf_state);
1706         for (is = ips_list; is; is = is->is_next) {
1707                 for (i = 0; i < 4; i++) {
1708                         if (is->is_ifp[i] == ifp) {
1709                                 is->is_ifp[i] = GETUNIT(is->is_ifname[i],
1710                                                         is->is_v);
1711                                 if (!is->is_ifp[i])
1712                                         is->is_ifp[i] = (void *)-1;
1713                         }
1714                 }
1715         }
1716         RWLOCK_EXIT(&ipf_state);
1717 }
1718
1719
1720 /*
1721  * Must always be called with fr_ipfstate held as a write lock.
1722  */
1723 static void fr_delstate(is)
1724 ipstate_t *is;
1725 {
1726         frentry_t *fr;
1727
1728         if (is->is_flags & (FI_WILDP|FI_WILDA))
1729                 ips_wild--;
1730         if (is->is_next)
1731                 is->is_next->is_pnext = is->is_pnext;
1732         *is->is_pnext = is->is_next;
1733         if (is->is_hnext)
1734                 is->is_hnext->is_phnext = is->is_phnext;
1735         *is->is_phnext = is->is_hnext;
1736         if (ips_table[is->is_hv] == NULL)
1737                 ips_stats.iss_inuse--;
1738         if (is->is_me)
1739                 *is->is_me = NULL;
1740
1741         fr = is->is_rule;
1742         if (fr != NULL) {
1743                 fr->fr_ref--;
1744                 if (fr->fr_ref == 0) {
1745                         KFREE(fr);
1746                 }
1747         }
1748 #ifdef  _KERNEL
1749         MUTEX_DESTROY(&is->is_lock);
1750 #endif
1751         KFREE(is);
1752         ips_num--;
1753 }
1754
1755
1756 /*
1757  * Free memory in use by all state info. kept.
1758  */
1759 void fr_stateunload()
1760 {
1761         ipstate_t *is;
1762
1763         WRITE_ENTER(&ipf_state);
1764         while ((is = ips_list))
1765                 fr_delstate(is);
1766         ips_stats.iss_inuse = 0;
1767         ips_num = 0;
1768         RWLOCK_EXIT(&ipf_state);
1769         if (ips_table)
1770                 KFREES(ips_table, fr_statesize * sizeof(ipstate_t *));
1771         ips_table = NULL;
1772 }
1773
1774
1775 /*
1776  * Slowly expire held state for thingslike UDP and ICMP.  Timeouts are set
1777  * in expectation of this being called twice per second.
1778  */
1779 void fr_timeoutstate()
1780 {
1781         ipstate_t *is, **isp;
1782 #if defined(_KERNEL) && !SOLARIS
1783         int s;
1784 #endif
1785
1786         SPL_NET(s);
1787         WRITE_ENTER(&ipf_state);
1788         for (isp = &ips_list; (is = *isp); )
1789                 if (is->is_age && !--is->is_age) {
1790                         if (is->is_p == IPPROTO_TCP)
1791                                 ips_stats.iss_fin++;
1792                         else
1793                                 ips_stats.iss_expire++;
1794 #ifdef  IPFILTER_LOG
1795                         ipstate_log(is, ISL_EXPIRE);
1796 #endif
1797                         fr_delstate(is);
1798                 } else
1799                         isp = &is->is_next;
1800         if (fr_state_doflush) {
1801                 (void) fr_state_flush(2, 0);
1802                 fr_state_doflush = 0;
1803         }
1804         RWLOCK_EXIT(&ipf_state);
1805         SPL_X(s);
1806 }
1807
1808
1809 /*
1810  * Original idea freom Pradeep Krishnan for use primarily with NAT code.
1811  * (pkrishna@netcom.com)
1812  *
1813  * Rewritten by Arjan de Vet <Arjan.deVet@adv.iae.nl>, 2000-07-29:
1814  *
1815  * - (try to) base state transitions on real evidence only,
1816  *   i.e. packets that are sent and have been received by ipfilter;
1817  *   diagram 18.12 of TCP/IP volume 1 by W. Richard Stevens was used.
1818  *
1819  * - deal with half-closed connections correctly;
1820  *
1821  * - store the state of the source in state[0] such that ipfstat
1822  *   displays the state as source/dest instead of dest/source; the calls
1823  *   to fr_tcp_age have been changed accordingly.
1824  *
1825  * Parameters:
1826  *
1827  *    state[0] = state of source (host that initiated connection)
1828  *    state[1] = state of dest   (host that accepted the connection)
1829  *
1830  *    dir == 0 : a packet from source to dest
1831  *    dir == 1 : a packet from dest to source
1832  *
1833  */
1834 int fr_tcp_age(age, state, fin, dir, fsm)
1835 u_long *age;
1836 u_char *state;
1837 fr_info_t *fin;
1838 int dir, fsm;
1839 {
1840         tcphdr_t *tcp = (tcphdr_t *)fin->fin_dp;
1841         u_char flags = tcp->th_flags;
1842         int dlen, ostate;
1843         u_long newage;
1844
1845         ostate = state[1 - dir];
1846
1847         dlen = fin->fin_plen - fin->fin_hlen - (tcp->th_off << 2);
1848
1849         if (flags & TH_RST) {
1850                 if (!(tcp->th_flags & TH_PUSH) && !dlen) {
1851                         *age = fr_tcpclosed;
1852                         state[dir] = TCPS_CLOSED;
1853                 } else {
1854                         *age = fr_tcpclosewait;
1855                         state[dir] = TCPS_CLOSE_WAIT;
1856                 }
1857                 return 0;
1858         }
1859
1860         newage = 0;
1861
1862         switch(state[dir])
1863         {
1864         case TCPS_CLOSED: /* 0 */
1865                 if ((flags & TH_OPENING) == TH_OPENING) {
1866                         /*
1867                          * 'dir' received an S and sends SA in response,
1868                          * CLOSED -> SYN_RECEIVED
1869                          */
1870                         state[dir] = TCPS_SYN_RECEIVED;
1871                         newage = fr_tcptimeout;
1872                 } else if ((flags & TH_OPENING) == TH_SYN) {
1873                         /* 'dir' sent S, CLOSED -> SYN_SENT */
1874                         state[dir] = TCPS_SYN_SENT;
1875                         newage = fr_tcptimeout;
1876                 }
1877                 
1878                 /* 
1879                  * It is apparently possible that a hosts sends two syncs
1880                  * before the remote party is able to respond with a SA. In
1881                  * such a case the remote server sometimes ACK's the second
1882                  * sync, and then responds with a SA. The following code
1883                  * is used to prevent this ack from being blocked.
1884                  *
1885                  * We do not reset the timeout here to fr_tcptimeout because
1886                  * a connection connect timeout does not renew after every
1887                  * packet that is sent.  We need to set newage to something
1888                  * to indicate the packet has passed the check for its flags
1889                  * being valid in the TCP FSM.
1890                  */
1891                 else if ((ostate == TCPS_SYN_SENT) &&
1892                          ((flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK)) {
1893                         newage = *age;
1894                 }
1895
1896                 /*
1897                  * The next piece of code makes it possible to get
1898                  * already established connections into the state table
1899                  * after a restart or reload of the filter rules; this
1900                  * does not work when a strict 'flags S keep state' is
1901                  * used for tcp connections of course, however, use a
1902                  * lower time-out so the state disappears quickly if
1903                  * the other side does not pick it up.
1904                  */
1905                 else if (!fsm &&
1906                          (flags & (TH_FIN|TH_SYN|TH_RST|TH_ACK)) == TH_ACK) {
1907                         /* we saw an A, guess 'dir' is in ESTABLISHED mode */
1908                         if (ostate == TCPS_CLOSED) {
1909                                 state[dir] = TCPS_ESTABLISHED;
1910                                 newage = fr_tcptimeout;
1911                         } else if (ostate == TCPS_ESTABLISHED) {
1912                                 state[dir] = TCPS_ESTABLISHED;
1913                                 newage = fr_tcpidletimeout;
1914                         }
1915                 }
1916                 /*
1917                  * TODO: besides regular ACK packets we can have other
1918                  * packets as well; it is yet to be determined how we
1919                  * should initialize the states in those cases
1920                  */
1921                 break;
1922
1923         case TCPS_LISTEN: /* 1 */
1924                 /* NOT USED */
1925                 break;
1926
1927         case TCPS_SYN_SENT: /* 2 */
1928                 if ((flags & ~(TH_ECN|TH_CWR)) == TH_SYN) {
1929                         /*
1930                          * A retransmitted SYN packet.  We do not reset the
1931                          * timeout here to fr_tcptimeout because a connection
1932                          * connect timeout does not renew after every packet
1933                          * that is sent.  We need to set newage to something
1934                          * to indicate the packet has passed the check for its
1935                          * flags being valid in the TCP FSM.
1936                          */
1937                         newage = *age;
1938                 } else if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1939                         /*
1940                          * We see an A from 'dir' which is in SYN_SENT
1941                          * state: 'dir' sent an A in response to an SA
1942                          * which it received, SYN_SENT -> ESTABLISHED
1943                          */
1944                         state[dir] = TCPS_ESTABLISHED;
1945                         newage = fr_tcpidletimeout;
1946                 } else if (flags & TH_FIN) {
1947                         /*
1948                          * We see an F from 'dir' which is in SYN_SENT
1949                          * state and wants to close its side of the
1950                          * connection; SYN_SENT -> FIN_WAIT_1
1951                          */
1952                         state[dir] = TCPS_FIN_WAIT_1;
1953                         newage = fr_tcpidletimeout; /* or fr_tcptimeout? */
1954                 } else if ((flags & TH_OPENING) == TH_OPENING) {
1955                         /*
1956                          * We see an SA from 'dir' which is already in
1957                          * SYN_SENT state, this means we have a
1958                          * simultaneous open; SYN_SENT -> SYN_RECEIVED
1959                          */
1960                         state[dir] = TCPS_SYN_RECEIVED;
1961                         newage = fr_tcptimeout;
1962                 }
1963                 break;
1964
1965         case TCPS_SYN_RECEIVED: /* 3 */
1966                 if ((flags & (TH_SYN|TH_FIN|TH_ACK)) == TH_ACK) {
1967                         /*
1968                          * We see an A from 'dir' which was in SYN_RECEIVED
1969                          * state so it must now be in established state,
1970                          * SYN_RECEIVED -> ESTABLISHED
1971                          */
1972                         state[dir] = TCPS_ESTABLISHED;
1973                         newage = fr_tcpidletimeout;
1974                 } else if ((flags & ~(TH_ECN|TH_CWR)) == TH_OPENING) {
1975                         /*
1976                          * We see an SA from 'dir' which is already in
1977                          * SYN_RECEIVED state.
1978                          */
1979                         newage = fr_tcptimeout;
1980                 } else if (flags & TH_FIN) {
1981                         /*
1982                          * We see an F from 'dir' which is in SYN_RECEIVED
1983                          * state and wants to close its side of the connection;
1984                          * SYN_RECEIVED -> FIN_WAIT_1
1985                          */
1986                         state[dir] = TCPS_FIN_WAIT_1;
1987                         newage = fr_tcpidletimeout;
1988                 }
1989                 break;
1990
1991         case TCPS_ESTABLISHED: /* 4 */
1992                 if (flags & TH_FIN) {
1993                         /*
1994                          * 'dir' closed its side of the connection; this
1995                          * gives us a half-closed connection;
1996                          * ESTABLISHED -> FIN_WAIT_1
1997                          */
1998                         state[dir] = TCPS_FIN_WAIT_1;
1999                         newage = fr_tcphalfclosed;
2000                 } else if (flags & TH_ACK) {
2001                         /* an ACK, should we exclude other flags here? */
2002                         if (ostate == TCPS_FIN_WAIT_1) {
2003                                 /*
2004                                  * We know the other side did an active close,
2005                                  * so we are ACKing the recvd FIN packet (does
2006                                  * the window matching code guarantee this?)
2007                                  * and go into CLOSE_WAIT state; this gives us
2008                                  * a half-closed connection
2009                                  */
2010                                 state[dir] = TCPS_CLOSE_WAIT;
2011                                 newage = fr_tcphalfclosed;
2012                         } else if (ostate < TCPS_CLOSE_WAIT)
2013                                 /*
2014                                  * Still a fully established connection,
2015                                  * reset timeout
2016                                  */
2017                                 newage = fr_tcpidletimeout;
2018                 }
2019                 break;
2020
2021         case TCPS_CLOSE_WAIT: /* 5 */
2022                 if (flags & TH_FIN) {
2023                         /*
2024                          * Application closed and 'dir' sent a FIN, we're now
2025                          * going into LAST_ACK state
2026                          */
2027                         newage  = fr_tcplastack;
2028                         state[dir] = TCPS_LAST_ACK;
2029                 } else {
2030                         /*
2031                          * We remain in CLOSE_WAIT because the other side has
2032                          * closed already and we did not close our side yet;
2033                          * reset timeout
2034                          */
2035                         newage  = fr_tcphalfclosed;
2036                 }
2037                 break;
2038
2039         case TCPS_FIN_WAIT_1: /* 6 */
2040                 if ((flags & TH_ACK) && ostate > TCPS_CLOSE_WAIT) {
2041                         /*
2042                          * If the other side is not active anymore it has sent
2043                          * us a FIN packet that we are ack'ing now with an ACK;
2044                          * this means both sides have now closed the connection
2045                          * and we go into TIME_WAIT
2046                          */
2047                         /*
2048                          * XXX: how do we know we really are ACKing the FIN
2049                          * packet here? does the window code guarantee that?
2050                          */
2051                         state[dir] = TCPS_TIME_WAIT;
2052                         newage = fr_tcptimeout;
2053                 } else
2054                         /*
2055                          * We closed our side of the connection already but the
2056                          * other side is still active (ESTABLISHED/CLOSE_WAIT);
2057                          * continue with this half-closed connection
2058                          */
2059                         newage = fr_tcphalfclosed;
2060                 break;
2061
2062         case TCPS_CLOSING: /* 7 */
2063                 /* NOT USED */
2064                 break;
2065
2066         case TCPS_LAST_ACK: /* 8 */
2067                 if (flags & TH_ACK) {
2068                         if ((flags & TH_PUSH) || dlen)
2069                                 /*
2070                                  * There is still data to be delivered, reset
2071                                  * timeout
2072                                  */
2073                                 newage  = fr_tcplastack;
2074                         else
2075                                 newage = *age;
2076                 }
2077                 /*
2078                  * We cannot detect when we go out of LAST_ACK state to CLOSED
2079                  * because that is based on the reception of ACK packets;
2080                  * ipfilter can only detect that a packet has been sent by a
2081                  * host
2082                  */
2083                 break;
2084
2085         case TCPS_FIN_WAIT_2: /* 9 */
2086                 /* NOT USED */
2087                 break;
2088
2089         case TCPS_TIME_WAIT: /* 10 */
2090                 newage = fr_tcptimeout; /* default 4 mins */
2091                 /* we're in 2MSL timeout now */
2092                 break;
2093         }
2094
2095         if (newage != 0) {
2096                 *age = newage;
2097                 return 0;
2098         }
2099         return -1;
2100 }
2101
2102
2103 #ifdef  IPFILTER_LOG
2104 void ipstate_log(is, type)
2105 struct ipstate *is;
2106 u_int type;
2107 {
2108         struct  ipslog  ipsl;
2109         void *items[1];
2110         size_t sizes[1];
2111         int types[1];
2112
2113         ipsl.isl_type = type;
2114         ipsl.isl_pkts = is->is_pkts + is->is_icmppkts;
2115         ipsl.isl_bytes = is->is_bytes;
2116         ipsl.isl_src = is->is_src;
2117         ipsl.isl_dst = is->is_dst;
2118         ipsl.isl_p = is->is_p;
2119         ipsl.isl_v = is->is_v;
2120         ipsl.isl_flags = is->is_flags;
2121         ipsl.isl_rulen = is->is_rulen;
2122         ipsl.isl_group = is->is_group;
2123         if (ipsl.isl_p == IPPROTO_TCP || ipsl.isl_p == IPPROTO_UDP) {
2124                 ipsl.isl_sport = is->is_sport;
2125                 ipsl.isl_dport = is->is_dport;
2126                 if (ipsl.isl_p == IPPROTO_TCP) {
2127                         ipsl.isl_state[0] = is->is_state[0];
2128                         ipsl.isl_state[1] = is->is_state[1];
2129                 }
2130         } else if (ipsl.isl_p == IPPROTO_ICMP) {
2131                 ipsl.isl_itype = is->is_icmp.ics_type;
2132         } else if (ipsl.isl_p == IPPROTO_ICMPV6) {
2133                 ipsl.isl_itype = is->is_icmp.ics_type;
2134         } else {
2135                 ipsl.isl_ps.isl_filler[0] = 0;
2136                 ipsl.isl_ps.isl_filler[1] = 0;
2137         }
2138         items[0] = &ipsl;
2139         sizes[0] = sizeof(ipsl);
2140         types[0] = 0;
2141
2142         if (ipllog(IPL_LOGSTATE, NULL, items, sizes, types, 1)) {
2143                 ATOMIC_INCL(ips_stats.iss_logged);
2144         } else {
2145                 ATOMIC_INCL(ips_stats.iss_logfail);
2146         }
2147 }
2148 #endif
2149
2150
2151 #ifdef  USE_INET6
2152 frentry_t *fr_checkicmp6matchingstate(ip, fin)
2153 ip6_t *ip;
2154 fr_info_t *fin;
2155 {
2156         ipstate_t *is, **isp;
2157         u_short sport, dport;
2158         u_char  pr;
2159         struct icmp6_hdr *ic, *oic;
2160         union i6addr dst, src;
2161         u_short savelen;
2162         fr_info_t ofin;
2163         tcphdr_t *tcp;
2164         frentry_t *fr;
2165         ip6_t *oip;
2166         int type;
2167         u_int hv;
2168
2169         /*
2170          * Does it at least have the return (basic) IP header ?
2171          * Only a basic IP header (no options) should be with
2172          * an ICMP error header.
2173          */
2174         if ((fin->fin_v != 6) || (fin->fin_plen < ICMP6ERR_MINPKTLEN))
2175                 return NULL;
2176         ic = (struct icmp6_hdr *)fin->fin_dp;
2177         type = ic->icmp6_type;
2178         /*
2179          * If it's not an error type, then return
2180          */
2181         if ((type != ICMP6_DST_UNREACH) && (type != ICMP6_PACKET_TOO_BIG) &&
2182             (type != ICMP6_TIME_EXCEEDED) && (type != ICMP6_PARAM_PROB))
2183                 return NULL;
2184
2185         oip = (ip6_t *)((char *)ic + ICMPERR_ICMPHLEN);
2186         if (fin->fin_plen < sizeof(*oip))
2187                 return NULL;
2188
2189         if ((oip->ip6_nxt != IPPROTO_TCP) && (oip->ip6_nxt != IPPROTO_UDP) &&
2190             (oip->ip6_nxt != IPPROTO_ICMPV6))
2191                 return NULL;
2192
2193         bzero((char *)&ofin, sizeof(ofin));
2194         ofin.fin_out = !fin->fin_out;
2195         ofin.fin_ifp = fin->fin_ifp;
2196         ofin.fin_mp = NULL;
2197         ofin.fin_v = 6;
2198 #if SOLARIS
2199         ofin.fin_qfm = NULL;
2200 #endif
2201         /*
2202          * We make a fin entry to be able to feed it to
2203          * matchsrcdst. Note that not all fields are necessary
2204          * but this is the cleanest way. Note further we fill
2205          * in fin_mp such that if someone uses it we'll get
2206          * a kernel panic. fr_matchsrcdst does not use this.
2207          *
2208          * watch out here, as ip is in host order and oip in network
2209          * order. Any change we make must be undone afterwards.
2210          */
2211         savelen = oip->ip6_plen;
2212         oip->ip6_plen = ip->ip6_plen - sizeof(*ip) - ICMPERR_ICMPHLEN;
2213         fr_makefrip(sizeof(*oip), (ip_t *)oip, &ofin);
2214         oip->ip6_plen = savelen;
2215
2216         if (oip->ip6_nxt == IPPROTO_ICMPV6) {
2217                 oic = (struct icmp6_hdr *)(oip + 1);
2218                 /*
2219                  * an ICMP error can only be generated as a result of an
2220                  * ICMP query, not as the response on an ICMP error
2221                  *
2222                  * XXX theoretically ICMP_ECHOREP and the other reply's are
2223                  * ICMP query's as well, but adding them here seems strange XXX
2224                  */
2225                  if (!(oic->icmp6_type & ICMP6_INFOMSG_MASK))
2226                         return NULL;
2227
2228                 /*
2229                  * perform a lookup of the ICMP packet in the state table
2230                  */
2231                 hv = (pr = oip->ip6_nxt);
2232                 src.in6 = oip->ip6_src;
2233                 hv += src.in4.s_addr;
2234                 dst.in6 = oip->ip6_dst;
2235                 hv += dst.in4.s_addr;
2236                 hv += oic->icmp6_id;
2237                 hv += oic->icmp6_seq;
2238                 hv %= fr_statesize;
2239
2240                 READ_ENTER(&ipf_state);
2241                 for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext)
2242                         if ((is->is_p == pr) &&
2243                             (oic->icmp6_id == is->is_icmp.ics_id) &&
2244                             (oic->icmp6_seq == is->is_icmp.ics_seq) &&
2245                             fr_matchsrcdst(is, src, dst, &ofin, NULL)) {
2246                                 /*
2247                                  * in the state table ICMP query's are stored
2248                                  * with the type of the corresponding ICMP
2249                                  * response. Correct here
2250                                  */
2251                                 if (((is->is_type == ICMP6_ECHO_REPLY) &&
2252                                      (oic->icmp6_type == ICMP6_ECHO_REQUEST)) ||
2253                                      (is->is_type - 1 == oic->icmp6_type )) {
2254                                         ips_stats.iss_hits++;
2255                                         is->is_pkts++;
2256                                         is->is_bytes += fin->fin_plen;
2257                                         return is->is_rule;
2258                                 }
2259                         }
2260                 RWLOCK_EXIT(&ipf_state);
2261
2262                 return NULL;
2263         }
2264
2265         tcp = (tcphdr_t *)(oip + 1);
2266         dport = tcp->th_dport;
2267         sport = tcp->th_sport;
2268
2269         hv = (pr = oip->ip6_nxt);
2270         src.in6 = oip->ip6_src;
2271         hv += src.in4.s_addr;
2272         hv += src.i6[1];
2273         hv += src.i6[2];
2274         hv += src.i6[3];
2275         dst.in6 = oip->ip6_dst;
2276         hv += dst.in4.s_addr;
2277         hv += dst.i6[1];
2278         hv += dst.i6[2];
2279         hv += dst.i6[3];
2280         hv += dport;
2281         hv += sport;
2282         hv %= fr_statesize;
2283
2284         READ_ENTER(&ipf_state);
2285         for (isp = &ips_table[hv]; (is = *isp); isp = &is->is_hnext) {
2286                 /*
2287                  * Only allow this icmp though if the
2288                  * encapsulated packet was allowed through the
2289                  * other way around. Note that the minimal amount
2290                  * of info present does not allow for checking against
2291                  * tcp internals such as seq and ack numbers.
2292                  */
2293                 if ((is->is_p == pr) && (is->is_v == 6) &&
2294                     fr_matchsrcdst(is, src, dst, &ofin, tcp)) {
2295                         fr = is->is_rule;
2296                         ips_stats.iss_hits++;
2297                         is->is_pkts++;
2298                         is->is_bytes += fin->fin_plen;
2299                         /*
2300                          * we deliberately do not touch the timeouts
2301                          * for the accompanying state table entry.
2302                          * It remains to be seen if that is correct. XXX
2303                          */
2304                         RWLOCK_EXIT(&ipf_state);
2305                         return fr;
2306                 }
2307         }
2308         RWLOCK_EXIT(&ipf_state);
2309         return NULL;
2310 }
2311 #endif