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