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