ipsec.c revision 157123
1/*	$FreeBSD: head/sys/netipsec/ipsec.c 157123 2006-03-25 13:38:52Z gnn $	*/
2/*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $	*/
3
4/*-
5 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the project nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/*
34 * IPsec controller part.
35 */
36
37#include "opt_inet.h"
38#include "opt_inet6.h"
39#include "opt_ipsec.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/malloc.h>
44#include <sys/mbuf.h>
45#include <sys/domain.h>
46#include <sys/protosw.h>
47#include <sys/socket.h>
48#include <sys/socketvar.h>
49#include <sys/errno.h>
50#include <sys/time.h>
51#include <sys/kernel.h>
52#include <sys/syslog.h>
53#include <sys/sysctl.h>
54#include <sys/proc.h>
55
56#include <net/if.h>
57#include <net/route.h>
58
59#include <netinet/in.h>
60#include <netinet/in_systm.h>
61#include <netinet/ip.h>
62#include <netinet/ip_var.h>
63#include <netinet/in_var.h>
64#include <netinet/udp.h>
65#include <netinet/udp_var.h>
66#include <netinet/tcp.h>
67#include <netinet/udp.h>
68
69#include <netinet/ip6.h>
70#ifdef INET6
71#include <netinet6/ip6_var.h>
72#endif
73#include <netinet/in_pcb.h>
74#ifdef INET6
75#include <netinet/icmp6.h>
76#endif
77
78#include <netipsec/ipsec.h>
79#ifdef INET6
80#include <netipsec/ipsec6.h>
81#endif
82#include <netipsec/ah_var.h>
83#include <netipsec/esp_var.h>
84#include <netipsec/ipcomp.h>		/*XXX*/
85#include <netipsec/ipcomp_var.h>
86
87#include <netipsec/key.h>
88#include <netipsec/keydb.h>
89#include <netipsec/key_debug.h>
90
91#include <netipsec/xform.h>
92
93#include <machine/in_cksum.h>
94
95#define IPSEC_DEBUG
96#ifdef IPSEC_DEBUG
97int ipsec_debug = 1;
98#else
99int ipsec_debug = 0;
100#endif
101
102/* NB: name changed so netstat doesn't use it */
103struct newipsecstat newipsecstat;
104int ip4_ah_offsetmask = 0;	/* maybe IP_DF? */
105int ip4_ipsec_dfbit = 0;	/* DF bit on encap. 0: clear 1: set 2: copy */
106int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
107int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
108int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
109int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
110struct secpolicy ip4_def_policy;
111int ip4_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
112int ip4_esp_randpad = -1;
113/*
114 * Crypto support requirements:
115 *
116 *  1	require hardware support
117 * -1	require software support
118 *  0	take anything
119 */
120int	crypto_support = 0;
121
122SYSCTL_DECL(_net_inet_ipsec);
123
124/* net.inet.ipsec */
125SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
126	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
127SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
128	CTLFLAG_RW, &ip4_esp_trans_deflev,	0, "");
129SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
130	CTLFLAG_RW, &ip4_esp_net_deflev,	0, "");
131SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
132	CTLFLAG_RW, &ip4_ah_trans_deflev,	0, "");
133SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
134	CTLFLAG_RW, &ip4_ah_net_deflev,	0, "");
135SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
136	ah_cleartos, CTLFLAG_RW,	&ah_cleartos,	0, "");
137SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
138	ah_offsetmask, CTLFLAG_RW,	&ip4_ah_offsetmask,	0, "");
139SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
140	dfbit, CTLFLAG_RW,	&ip4_ipsec_dfbit,	0, "");
141SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
142	ecn, CTLFLAG_RW,	&ip4_ipsec_ecn,	0, "");
143SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
144	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
145SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
146	esp_randpad, CTLFLAG_RW,	&ip4_esp_randpad,	0, "");
147SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
148	crypto_support,	CTLFLAG_RW,	&crypto_support,0, "");
149SYSCTL_STRUCT(_net_inet_ipsec, OID_AUTO,
150	ipsecstats,	CTLFLAG_RD,	&newipsecstat,	newipsecstat, "");
151
152#ifdef INET6
153int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
154int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
155int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
156int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
157int ip6_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
158int ip6_esp_randpad = -1;
159
160SYSCTL_DECL(_net_inet6_ipsec6);
161
162/* net.inet6.ipsec6 */
163#ifdef COMPAT_KAME
164SYSCTL_OID(_net_inet6_ipsec6, IPSECCTL_STATS, stats, CTLFLAG_RD,
165	0,0, compat_ipsecstats_sysctl, "S", "");
166#endif /* COMPAT_KAME */
167SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
168	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
169SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
170	CTLFLAG_RW, &ip6_esp_trans_deflev,	0, "");
171SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
172	CTLFLAG_RW, &ip6_esp_net_deflev,	0, "");
173SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
174	CTLFLAG_RW, &ip6_ah_trans_deflev,	0, "");
175SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
176	CTLFLAG_RW, &ip6_ah_net_deflev,	0, "");
177SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
178	ecn, CTLFLAG_RW,	&ip6_ipsec_ecn,	0, "");
179SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
180	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
181SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
182	esp_randpad, CTLFLAG_RW,	&ip6_esp_randpad,	0, "");
183#endif /* INET6 */
184
185static int ipsec4_setspidx_inpcb __P((struct mbuf *, struct inpcb *pcb));
186#ifdef INET6
187static int ipsec6_setspidx_in6pcb __P((struct mbuf *, struct in6pcb *pcb));
188#endif
189static int ipsec_setspidx __P((struct mbuf *, struct secpolicyindex *, int));
190static void ipsec4_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
191static int ipsec4_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
192#ifdef INET6
193static void ipsec6_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
194static int ipsec6_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
195#endif
196static void ipsec_delpcbpolicy __P((struct inpcbpolicy *));
197static struct secpolicy *ipsec_deepcopy_policy __P((struct secpolicy *src));
198static int ipsec_set_policy __P((struct secpolicy **pcb_sp,
199	int optname, caddr_t request, size_t len, int priv));
200static int ipsec_get_policy __P((struct secpolicy *pcb_sp, struct mbuf **mp));
201static void vshiftl __P((unsigned char *, int, int));
202static size_t ipsec_hdrsiz __P((struct secpolicy *));
203
204MALLOC_DEFINE(M_IPSEC_INPCB, "inpcbpolicy", "inpcb-resident ipsec policy");
205
206/*
207 * Return a held reference to the default SP.
208 */
209static struct secpolicy *
210key_allocsp_default(const char* where, int tag)
211{
212	struct secpolicy *sp;
213
214	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
215		printf("DP key_allocsp_default from %s:%u\n", where, tag));
216
217	sp = &ip4_def_policy;
218	if (sp->policy != IPSEC_POLICY_DISCARD &&
219	    sp->policy != IPSEC_POLICY_NONE) {
220		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
221		    sp->policy, IPSEC_POLICY_NONE));
222		sp->policy = IPSEC_POLICY_NONE;
223	}
224	key_addref(sp);
225
226	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
227		printf("DP key_allocsp_default returns SP:%p (%u)\n",
228			sp, sp->refcnt));
229	return sp;
230}
231#define	KEY_ALLOCSP_DEFAULT() \
232	key_allocsp_default(__FILE__, __LINE__)
233
234/*
235 * For OUTBOUND packet having a socket. Searching SPD for packet,
236 * and return a pointer to SP.
237 * OUT:	NULL:	no apropreate SP found, the following value is set to error.
238 *		0	: bypass
239 *		EACCES	: discard packet.
240 *		ENOENT	: ipsec_acquire() in progress, maybe.
241 *		others	: error occured.
242 *	others:	a pointer to SP
243 *
244 * NOTE: IPv6 mapped adddress concern is implemented here.
245 */
246struct secpolicy *
247ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir)
248{
249	struct secpolicy *sp;
250
251	IPSEC_ASSERT(tdbi != NULL, ("null tdbi"));
252	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
253		("invalid direction %u", dir));
254
255	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
256	if (sp == NULL)			/*XXX????*/
257		sp = KEY_ALLOCSP_DEFAULT();
258	IPSEC_ASSERT(sp != NULL, ("null SP"));
259	return sp;
260}
261
262/*
263 * For OUTBOUND packet having a socket. Searching SPD for packet,
264 * and return a pointer to SP.
265 * OUT:	NULL:	no apropreate SP found, the following value is set to error.
266 *		0	: bypass
267 *		EACCES	: discard packet.
268 *		ENOENT	: ipsec_acquire() in progress, maybe.
269 *		others	: error occured.
270 *	others:	a pointer to SP
271 *
272 * NOTE: IPv6 mapped adddress concern is implemented here.
273 */
274struct secpolicy *
275ipsec_getpolicybysock(m, dir, inp, error)
276	struct mbuf *m;
277	u_int dir;
278	struct inpcb *inp;
279	int *error;
280{
281	struct inpcbpolicy *pcbsp = NULL;
282	struct secpolicy *currsp = NULL;	/* policy on socket */
283	struct secpolicy *sp;
284
285	IPSEC_ASSERT(m != NULL, ("null mbuf"));
286	IPSEC_ASSERT(inp != NULL, ("null inpcb"));
287	IPSEC_ASSERT(error != NULL, ("null error"));
288	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
289		("invalid direction %u", dir));
290
291	/* set spidx in pcb */
292	if (inp->inp_vflag & INP_IPV6PROTO) {
293#ifdef INET6
294		*error = ipsec6_setspidx_in6pcb(m, inp);
295		pcbsp = inp->in6p_sp;
296#else
297		*error = EINVAL;		/* should not happen */
298#endif
299	} else {
300		*error = ipsec4_setspidx_inpcb(m, inp);
301		pcbsp = inp->inp_sp;
302	}
303	if (*error)
304		return NULL;
305
306	IPSEC_ASSERT(pcbsp != NULL, ("null pcbsp"));
307	switch (dir) {
308	case IPSEC_DIR_INBOUND:
309		currsp = pcbsp->sp_in;
310		break;
311	case IPSEC_DIR_OUTBOUND:
312		currsp = pcbsp->sp_out;
313		break;
314	}
315	IPSEC_ASSERT(currsp != NULL, ("null currsp"));
316
317	if (pcbsp->priv) {			/* when privilieged socket */
318		switch (currsp->policy) {
319		case IPSEC_POLICY_BYPASS:
320		case IPSEC_POLICY_IPSEC:
321			key_addref(currsp);
322			sp = currsp;
323			break;
324
325		case IPSEC_POLICY_ENTRUST:
326			/* look for a policy in SPD */
327			sp = KEY_ALLOCSP(&currsp->spidx, dir);
328			if (sp == NULL)		/* no SP found */
329				sp = KEY_ALLOCSP_DEFAULT();
330			break;
331
332		default:
333			ipseclog((LOG_ERR, "%s: Invalid policy for PCB %d\n",
334				__func__, currsp->policy));
335			*error = EINVAL;
336			return NULL;
337		}
338	} else {				/* unpriv, SPD has policy */
339		sp = KEY_ALLOCSP(&currsp->spidx, dir);
340		if (sp == NULL) {		/* no SP found */
341			switch (currsp->policy) {
342			case IPSEC_POLICY_BYPASS:
343				ipseclog((LOG_ERR, "%s: Illegal policy for "
344					"non-priviliged defined %d\n",
345					__func__, currsp->policy));
346				*error = EINVAL;
347				return NULL;
348
349			case IPSEC_POLICY_ENTRUST:
350				sp = KEY_ALLOCSP_DEFAULT();
351				break;
352
353			case IPSEC_POLICY_IPSEC:
354				key_addref(currsp);
355				sp = currsp;
356				break;
357
358			default:
359				ipseclog((LOG_ERR, "%s: Invalid policy for "
360					"PCB %d\n", __func__, currsp->policy));
361				*error = EINVAL;
362				return NULL;
363			}
364		}
365	}
366	IPSEC_ASSERT(sp != NULL,
367		("null SP (priv %u policy %u", pcbsp->priv, currsp->policy));
368	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
369		printf("DP %s (priv %u policy %u) allocate SP:%p (refcnt %u)\n",
370			__func__, pcbsp->priv, currsp->policy, sp, sp->refcnt));
371	return sp;
372}
373
374/*
375 * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
376 * and return a pointer to SP.
377 * OUT:	positive: a pointer to the entry for security policy leaf matched.
378 *	NULL:	no apropreate SP found, the following value is set to error.
379 *		0	: bypass
380 *		EACCES	: discard packet.
381 *		ENOENT	: ipsec_acquire() in progress, maybe.
382 *		others	: error occured.
383 */
384struct secpolicy *
385ipsec_getpolicybyaddr(m, dir, flag, error)
386	struct mbuf *m;
387	u_int dir;
388	int flag;
389	int *error;
390{
391	struct secpolicyindex spidx;
392	struct secpolicy *sp;
393
394	IPSEC_ASSERT(m != NULL, ("null mbuf"));
395	IPSEC_ASSERT(error != NULL, ("null error"));
396	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
397		("invalid direction %u", dir));
398
399	sp = NULL;
400	if (key_havesp(dir)) {
401		/* Make an index to look for a policy. */
402		*error = ipsec_setspidx(m, &spidx,
403					(flag & IP_FORWARDING) ? 0 : 1);
404		if (*error != 0) {
405			DPRINTF(("%s: setpidx failed, dir %u flag %u\n",
406				__func__, dir, flag));
407			return NULL;
408		}
409		spidx.dir = dir;
410
411		sp = KEY_ALLOCSP(&spidx, dir);
412	}
413	if (sp == NULL)			/* no SP found, use system default */
414		sp = KEY_ALLOCSP_DEFAULT();
415	IPSEC_ASSERT(sp != NULL, ("null SP"));
416	return sp;
417}
418
419struct secpolicy *
420ipsec4_checkpolicy(m, dir, flag, error, inp)
421	struct mbuf *m;
422	u_int dir, flag;
423	int *error;
424	struct inpcb *inp;
425{
426	struct secpolicy *sp;
427
428	*error = 0;
429	if (inp == NULL)
430		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
431	else
432		sp = ipsec_getpolicybysock(m, dir, inp, error);
433	if (sp == NULL) {
434		IPSEC_ASSERT(*error != 0, ("getpolicy failed w/o error"));
435		newipsecstat.ips_out_inval++;
436		return NULL;
437	}
438	IPSEC_ASSERT(*error == 0, ("sp w/ error set to %u", *error));
439	switch (sp->policy) {
440	case IPSEC_POLICY_ENTRUST:
441	default:
442		printf("%s: invalid policy %u\n", __func__, sp->policy);
443		/* fall thru... */
444	case IPSEC_POLICY_DISCARD:
445		newipsecstat.ips_out_polvio++;
446		*error = -EINVAL;	/* packet is discarded by caller */
447		break;
448	case IPSEC_POLICY_BYPASS:
449	case IPSEC_POLICY_NONE:
450		KEY_FREESP(&sp);
451		sp = NULL;		/* NB: force NULL result */
452		break;
453	case IPSEC_POLICY_IPSEC:
454		if (sp->req == NULL)	/* acquire an SA */
455			*error = key_spdacquire(sp);
456		break;
457	}
458	if (*error != 0) {
459		KEY_FREESP(&sp);
460		sp = NULL;
461	}
462	return sp;
463}
464
465static int
466ipsec4_setspidx_inpcb(m, pcb)
467	struct mbuf *m;
468	struct inpcb *pcb;
469{
470	int error;
471
472	IPSEC_ASSERT(pcb != NULL, ("null pcb"));
473	IPSEC_ASSERT(pcb->inp_sp != NULL, ("null inp_sp"));
474	IPSEC_ASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
475		("null sp_in || sp_out"));
476
477	error = ipsec_setspidx(m, &pcb->inp_sp->sp_in->spidx, 1);
478	if (error == 0) {
479		pcb->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
480		pcb->inp_sp->sp_out->spidx = pcb->inp_sp->sp_in->spidx;
481		pcb->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
482	} else {
483		bzero(&pcb->inp_sp->sp_in->spidx,
484			sizeof (pcb->inp_sp->sp_in->spidx));
485		bzero(&pcb->inp_sp->sp_out->spidx,
486			sizeof (pcb->inp_sp->sp_in->spidx));
487	}
488	return error;
489}
490
491#ifdef INET6
492static int
493ipsec6_setspidx_in6pcb(m, pcb)
494	struct mbuf *m;
495	struct in6pcb *pcb;
496{
497	struct secpolicyindex *spidx;
498	int error;
499
500	IPSEC_ASSERT(pcb != NULL, ("null pcb"));
501	IPSEC_ASSERT(pcb->in6p_sp != NULL, ("null inp_sp"));
502	IPSEC_ASSERT(pcb->in6p_sp->sp_out != NULL && pcb->in6p_sp->sp_in != NULL,
503		("null sp_in || sp_out"));
504
505	bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
506	bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
507
508	spidx = &pcb->in6p_sp->sp_in->spidx;
509	error = ipsec_setspidx(m, spidx, 1);
510	if (error)
511		goto bad;
512	spidx->dir = IPSEC_DIR_INBOUND;
513
514	spidx = &pcb->in6p_sp->sp_out->spidx;
515	error = ipsec_setspidx(m, spidx, 1);
516	if (error)
517		goto bad;
518	spidx->dir = IPSEC_DIR_OUTBOUND;
519
520	return 0;
521
522bad:
523	bzero(&pcb->in6p_sp->sp_in->spidx, sizeof(*spidx));
524	bzero(&pcb->in6p_sp->sp_out->spidx, sizeof(*spidx));
525	return error;
526}
527#endif
528
529/*
530 * configure security policy index (src/dst/proto/sport/dport)
531 * by looking at the content of mbuf.
532 * the caller is responsible for error recovery (like clearing up spidx).
533 */
534static int
535ipsec_setspidx(m, spidx, needport)
536	struct mbuf *m;
537	struct secpolicyindex *spidx;
538	int needport;
539{
540	struct ip *ip = NULL;
541	struct ip ipbuf;
542	u_int v;
543	struct mbuf *n;
544	int len;
545	int error;
546
547	IPSEC_ASSERT(m != NULL, ("null mbuf"));
548
549	/*
550	 * validate m->m_pkthdr.len.  we see incorrect length if we
551	 * mistakenly call this function with inconsistent mbuf chain
552	 * (like 4.4BSD tcp/udp processing).  XXX should we panic here?
553	 */
554	len = 0;
555	for (n = m; n; n = n->m_next)
556		len += n->m_len;
557	if (m->m_pkthdr.len != len) {
558		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
559			printf("%s: pkthdr len(%d) mismatch (%d), ignored.\n",
560				__func__, len, m->m_pkthdr.len));
561		return EINVAL;
562	}
563
564	if (m->m_pkthdr.len < sizeof(struct ip)) {
565		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
566			printf("%s: pkthdr len(%d) too small (v4), ignored.\n",
567			    __func__, m->m_pkthdr.len));
568		return EINVAL;
569	}
570
571	if (m->m_len >= sizeof(*ip))
572		ip = mtod(m, struct ip *);
573	else {
574		m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
575		ip = &ipbuf;
576	}
577#ifdef _IP_VHL
578	v = _IP_VHL_V(ip->ip_vhl);
579#else
580	v = ip->ip_v;
581#endif
582	switch (v) {
583	case 4:
584		error = ipsec4_setspidx_ipaddr(m, spidx);
585		if (error)
586			return error;
587		ipsec4_get_ulp(m, spidx, needport);
588		return 0;
589#ifdef INET6
590	case 6:
591		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
592			KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
593				printf("%s: pkthdr len(%d) too small (v6), "
594				"ignored\n", __func__, m->m_pkthdr.len));
595			return EINVAL;
596		}
597		error = ipsec6_setspidx_ipaddr(m, spidx);
598		if (error)
599			return error;
600		ipsec6_get_ulp(m, spidx, needport);
601		return 0;
602#endif
603	default:
604		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
605			printf("%s: " "unknown IP version %u, ignored.\n",
606				__func__, v));
607		return EINVAL;
608	}
609}
610
611static void
612ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
613{
614	u_int8_t nxt;
615	int off;
616
617	/* sanity check */
618	IPSEC_ASSERT(m != NULL, ("null mbuf"));
619	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),("packet too short"));
620
621	/* NB: ip_input() flips it into host endian XXX need more checking */
622	if (m->m_len < sizeof (struct ip)) {
623		struct ip *ip = mtod(m, struct ip *);
624		if (ip->ip_off & (IP_MF | IP_OFFMASK))
625			goto done;
626#ifdef _IP_VHL
627		off = _IP_VHL_HL(ip->ip_vhl) << 2;
628#else
629		off = ip->ip_hl << 2;
630#endif
631		nxt = ip->ip_p;
632	} else {
633		struct ip ih;
634
635		m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
636		if (ih.ip_off & (IP_MF | IP_OFFMASK))
637			goto done;
638#ifdef _IP_VHL
639		off = _IP_VHL_HL(ih.ip_vhl) << 2;
640#else
641		off = ih.ip_hl << 2;
642#endif
643		nxt = ih.ip_p;
644	}
645
646	while (off < m->m_pkthdr.len) {
647		struct ip6_ext ip6e;
648		struct tcphdr th;
649		struct udphdr uh;
650
651		switch (nxt) {
652		case IPPROTO_TCP:
653			spidx->ul_proto = nxt;
654			if (!needport)
655				goto done_proto;
656			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
657				goto done;
658			m_copydata(m, off, sizeof (th), (caddr_t) &th);
659			spidx->src.sin.sin_port = th.th_sport;
660			spidx->dst.sin.sin_port = th.th_dport;
661			return;
662		case IPPROTO_UDP:
663			spidx->ul_proto = nxt;
664			if (!needport)
665				goto done_proto;
666			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
667				goto done;
668			m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
669			spidx->src.sin.sin_port = uh.uh_sport;
670			spidx->dst.sin.sin_port = uh.uh_dport;
671			return;
672		case IPPROTO_AH:
673			if (off + sizeof(ip6e) > m->m_pkthdr.len)
674				goto done;
675			/* XXX sigh, this works but is totally bogus */
676			m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
677			off += (ip6e.ip6e_len + 2) << 2;
678			nxt = ip6e.ip6e_nxt;
679			break;
680		case IPPROTO_ICMP:
681		default:
682			/* XXX intermediate headers??? */
683			spidx->ul_proto = nxt;
684			goto done_proto;
685		}
686	}
687done:
688	spidx->ul_proto = IPSEC_ULPROTO_ANY;
689done_proto:
690	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
691	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
692}
693
694/* assumes that m is sane */
695static int
696ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
697{
698	static const struct sockaddr_in template = {
699		sizeof (struct sockaddr_in),
700		AF_INET,
701		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
702	};
703
704	spidx->src.sin = template;
705	spidx->dst.sin = template;
706
707	if (m->m_len < sizeof (struct ip)) {
708		m_copydata(m, offsetof(struct ip, ip_src),
709			   sizeof (struct  in_addr),
710			   (caddr_t) &spidx->src.sin.sin_addr);
711		m_copydata(m, offsetof(struct ip, ip_dst),
712			   sizeof (struct  in_addr),
713			   (caddr_t) &spidx->dst.sin.sin_addr);
714	} else {
715		struct ip *ip = mtod(m, struct ip *);
716		spidx->src.sin.sin_addr = ip->ip_src;
717		spidx->dst.sin.sin_addr = ip->ip_dst;
718	}
719
720	spidx->prefs = sizeof(struct in_addr) << 3;
721	spidx->prefd = sizeof(struct in_addr) << 3;
722
723	return 0;
724}
725
726#ifdef INET6
727static void
728ipsec6_get_ulp(m, spidx, needport)
729	struct mbuf *m;
730	struct secpolicyindex *spidx;
731	int needport;
732{
733	int off, nxt;
734	struct tcphdr th;
735	struct udphdr uh;
736
737	/* sanity check */
738	if (m == NULL)
739		panic("%s: NULL pointer was passed.\n", __func__);
740
741	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
742		printf("%s:\n", __func__); kdebug_mbuf(m));
743
744	/* set default */
745	spidx->ul_proto = IPSEC_ULPROTO_ANY;
746	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
747	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
748
749	nxt = -1;
750	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
751	if (off < 0 || m->m_pkthdr.len < off)
752		return;
753
754	switch (nxt) {
755	case IPPROTO_TCP:
756		spidx->ul_proto = nxt;
757		if (!needport)
758			break;
759		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
760			break;
761		m_copydata(m, off, sizeof(th), (caddr_t)&th);
762		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
763		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
764		break;
765	case IPPROTO_UDP:
766		spidx->ul_proto = nxt;
767		if (!needport)
768			break;
769		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
770			break;
771		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
772		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
773		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
774		break;
775	case IPPROTO_ICMPV6:
776	default:
777		/* XXX intermediate headers??? */
778		spidx->ul_proto = nxt;
779		break;
780	}
781}
782
783/* assumes that m is sane */
784static int
785ipsec6_setspidx_ipaddr(m, spidx)
786	struct mbuf *m;
787	struct secpolicyindex *spidx;
788{
789	struct ip6_hdr *ip6 = NULL;
790	struct ip6_hdr ip6buf;
791	struct sockaddr_in6 *sin6;
792
793	if (m->m_len >= sizeof(*ip6))
794		ip6 = mtod(m, struct ip6_hdr *);
795	else {
796		m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
797		ip6 = &ip6buf;
798	}
799
800	sin6 = (struct sockaddr_in6 *)&spidx->src;
801	bzero(sin6, sizeof(*sin6));
802	sin6->sin6_family = AF_INET6;
803	sin6->sin6_len = sizeof(struct sockaddr_in6);
804	bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
805	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
806		sin6->sin6_addr.s6_addr16[1] = 0;
807		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
808	}
809	spidx->prefs = sizeof(struct in6_addr) << 3;
810
811	sin6 = (struct sockaddr_in6 *)&spidx->dst;
812	bzero(sin6, sizeof(*sin6));
813	sin6->sin6_family = AF_INET6;
814	sin6->sin6_len = sizeof(struct sockaddr_in6);
815	bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
816	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
817		sin6->sin6_addr.s6_addr16[1] = 0;
818		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
819	}
820	spidx->prefd = sizeof(struct in6_addr) << 3;
821
822	return 0;
823}
824#endif
825
826static void
827ipsec_delpcbpolicy(p)
828	struct inpcbpolicy *p;
829{
830	free(p, M_IPSEC_INPCB);
831}
832
833/* initialize policy in PCB */
834int
835ipsec_init_policy(so, pcb_sp)
836	struct socket *so;
837	struct inpcbpolicy **pcb_sp;
838{
839	struct inpcbpolicy *new;
840
841	/* sanity check. */
842	if (so == NULL || pcb_sp == NULL)
843		panic("%s: NULL pointer was passed.\n", __func__);
844
845	new = (struct inpcbpolicy *) malloc(sizeof(struct inpcbpolicy),
846					    M_IPSEC_INPCB, M_NOWAIT|M_ZERO);
847	if (new == NULL) {
848		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
849		return ENOBUFS;
850	}
851
852	new->priv = IPSEC_IS_PRIVILEGED_SO(so);
853
854	if ((new->sp_in = KEY_NEWSP()) == NULL) {
855		ipsec_delpcbpolicy(new);
856		return ENOBUFS;
857	}
858	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
859	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
860
861	if ((new->sp_out = KEY_NEWSP()) == NULL) {
862		KEY_FREESP(&new->sp_in);
863		ipsec_delpcbpolicy(new);
864		return ENOBUFS;
865	}
866	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
867	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
868
869	*pcb_sp = new;
870
871	return 0;
872}
873
874/* copy old ipsec policy into new */
875int
876ipsec_copy_policy(old, new)
877	struct inpcbpolicy *old, *new;
878{
879	struct secpolicy *sp;
880
881	sp = ipsec_deepcopy_policy(old->sp_in);
882	if (sp) {
883		KEY_FREESP(&new->sp_in);
884		new->sp_in = sp;
885	} else
886		return ENOBUFS;
887
888	sp = ipsec_deepcopy_policy(old->sp_out);
889	if (sp) {
890		KEY_FREESP(&new->sp_out);
891		new->sp_out = sp;
892	} else
893		return ENOBUFS;
894
895	new->priv = old->priv;
896
897	return 0;
898}
899
900struct ipsecrequest *
901ipsec_newisr(void)
902{
903	struct ipsecrequest *p;
904
905	p = malloc(sizeof(struct ipsecrequest), M_IPSEC_SR, M_NOWAIT|M_ZERO);
906	if (p != NULL)
907		IPSECREQUEST_LOCK_INIT(p);
908	return p;
909}
910
911void
912ipsec_delisr(struct ipsecrequest *p)
913{
914	IPSECREQUEST_LOCK_DESTROY(p);
915	free(p, M_IPSEC_SR);
916}
917
918/* deep-copy a policy in PCB */
919static struct secpolicy *
920ipsec_deepcopy_policy(src)
921	struct secpolicy *src;
922{
923	struct ipsecrequest *newchain = NULL;
924	struct ipsecrequest *p;
925	struct ipsecrequest **q;
926	struct ipsecrequest *r;
927	struct secpolicy *dst;
928
929	if (src == NULL)
930		return NULL;
931	dst = KEY_NEWSP();
932	if (dst == NULL)
933		return NULL;
934
935	/*
936	 * deep-copy IPsec request chain.  This is required since struct
937	 * ipsecrequest is not reference counted.
938	 */
939	q = &newchain;
940	for (p = src->req; p; p = p->next) {
941		*q = ipsec_newisr();
942		if (*q == NULL)
943			goto fail;
944		(*q)->saidx.proto = p->saidx.proto;
945		(*q)->saidx.mode = p->saidx.mode;
946		(*q)->level = p->level;
947		(*q)->saidx.reqid = p->saidx.reqid;
948
949		bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
950		bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
951
952		(*q)->sp = dst;
953
954		q = &((*q)->next);
955	}
956
957	dst->req = newchain;
958	dst->state = src->state;
959	dst->policy = src->policy;
960	/* do not touch the refcnt fields */
961
962	return dst;
963
964fail:
965	for (p = newchain; p; p = r) {
966		r = p->next;
967		ipsec_delisr(p);
968		p = NULL;
969	}
970	return NULL;
971}
972
973/* set policy and ipsec request if present. */
974static int
975ipsec_set_policy(pcb_sp, optname, request, len, priv)
976	struct secpolicy **pcb_sp;
977	int optname;
978	caddr_t request;
979	size_t len;
980	int priv;
981{
982	struct sadb_x_policy *xpl;
983	struct secpolicy *newsp = NULL;
984	int error;
985
986	/* sanity check. */
987	if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL)
988		return EINVAL;
989	if (len < sizeof(*xpl))
990		return EINVAL;
991	xpl = (struct sadb_x_policy *)request;
992
993	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
994		printf("%s: passed policy\n", __func__);
995		kdebug_sadb_x_policy((struct sadb_ext *)xpl));
996
997	/* check policy type */
998	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
999	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
1000	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
1001		return EINVAL;
1002
1003	/* check privileged socket */
1004	if (priv == 0 && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS)
1005		return EACCES;
1006
1007	/* allocation new SP entry */
1008	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1009		return error;
1010
1011	newsp->state = IPSEC_SPSTATE_ALIVE;
1012
1013	/* clear old SP and set new SP */
1014	KEY_FREESP(pcb_sp);
1015	*pcb_sp = newsp;
1016	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1017		printf("%s: new policy\n", __func__);
1018		kdebug_secpolicy(newsp));
1019
1020	return 0;
1021}
1022
1023static int
1024ipsec_get_policy(pcb_sp, mp)
1025	struct secpolicy *pcb_sp;
1026	struct mbuf **mp;
1027{
1028
1029	/* sanity check. */
1030	if (pcb_sp == NULL || mp == NULL)
1031		return EINVAL;
1032
1033	*mp = key_sp2msg(pcb_sp);
1034	if (!*mp) {
1035		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
1036		return ENOBUFS;
1037	}
1038
1039	(*mp)->m_type = MT_DATA;
1040	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1041		printf("%s:\n", __func__); kdebug_mbuf(*mp));
1042
1043	return 0;
1044}
1045
1046int
1047ipsec4_set_policy(inp, optname, request, len, priv)
1048	struct inpcb *inp;
1049	int optname;
1050	caddr_t request;
1051	size_t len;
1052	int priv;
1053{
1054	struct sadb_x_policy *xpl;
1055	struct secpolicy **pcb_sp;
1056
1057	/* sanity check. */
1058	if (inp == NULL || request == NULL)
1059		return EINVAL;
1060	if (len < sizeof(*xpl))
1061		return EINVAL;
1062	xpl = (struct sadb_x_policy *)request;
1063
1064	/* select direction */
1065	switch (xpl->sadb_x_policy_dir) {
1066	case IPSEC_DIR_INBOUND:
1067		pcb_sp = &inp->inp_sp->sp_in;
1068		break;
1069	case IPSEC_DIR_OUTBOUND:
1070		pcb_sp = &inp->inp_sp->sp_out;
1071		break;
1072	default:
1073		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1074			xpl->sadb_x_policy_dir));
1075		return EINVAL;
1076	}
1077
1078	return ipsec_set_policy(pcb_sp, optname, request, len, priv);
1079}
1080
1081int
1082ipsec4_get_policy(inp, request, len, mp)
1083	struct inpcb *inp;
1084	caddr_t request;
1085	size_t len;
1086	struct mbuf **mp;
1087{
1088	struct sadb_x_policy *xpl;
1089	struct secpolicy *pcb_sp;
1090
1091	/* sanity check. */
1092	if (inp == NULL || request == NULL || mp == NULL)
1093		return EINVAL;
1094	IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp"));
1095	if (len < sizeof(*xpl))
1096		return EINVAL;
1097	xpl = (struct sadb_x_policy *)request;
1098
1099	/* select direction */
1100	switch (xpl->sadb_x_policy_dir) {
1101	case IPSEC_DIR_INBOUND:
1102		pcb_sp = inp->inp_sp->sp_in;
1103		break;
1104	case IPSEC_DIR_OUTBOUND:
1105		pcb_sp = inp->inp_sp->sp_out;
1106		break;
1107	default:
1108		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1109			xpl->sadb_x_policy_dir));
1110		return EINVAL;
1111	}
1112
1113	return ipsec_get_policy(pcb_sp, mp);
1114}
1115
1116/* delete policy in PCB */
1117int
1118ipsec4_delete_pcbpolicy(inp)
1119	struct inpcb *inp;
1120{
1121	IPSEC_ASSERT(inp != NULL, ("null inp"));
1122
1123	if (inp->inp_sp == NULL)
1124		return 0;
1125
1126	if (inp->inp_sp->sp_in != NULL)
1127		KEY_FREESP(&inp->inp_sp->sp_in);
1128
1129	if (inp->inp_sp->sp_out != NULL)
1130		KEY_FREESP(&inp->inp_sp->sp_out);
1131
1132	ipsec_delpcbpolicy(inp->inp_sp);
1133	inp->inp_sp = NULL;
1134
1135	return 0;
1136}
1137
1138#ifdef INET6
1139int
1140ipsec6_set_policy(in6p, optname, request, len, priv)
1141	struct in6pcb *in6p;
1142	int optname;
1143	caddr_t request;
1144	size_t len;
1145	int priv;
1146{
1147	struct sadb_x_policy *xpl;
1148	struct secpolicy **pcb_sp;
1149
1150	/* sanity check. */
1151	if (in6p == NULL || request == NULL)
1152		return EINVAL;
1153	if (len < sizeof(*xpl))
1154		return EINVAL;
1155	xpl = (struct sadb_x_policy *)request;
1156
1157	/* select direction */
1158	switch (xpl->sadb_x_policy_dir) {
1159	case IPSEC_DIR_INBOUND:
1160		pcb_sp = &in6p->in6p_sp->sp_in;
1161		break;
1162	case IPSEC_DIR_OUTBOUND:
1163		pcb_sp = &in6p->in6p_sp->sp_out;
1164		break;
1165	default:
1166		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1167			xpl->sadb_x_policy_dir));
1168		return EINVAL;
1169	}
1170
1171	return ipsec_set_policy(pcb_sp, optname, request, len, priv);
1172}
1173
1174int
1175ipsec6_get_policy(in6p, request, len, mp)
1176	struct in6pcb *in6p;
1177	caddr_t request;
1178	size_t len;
1179	struct mbuf **mp;
1180{
1181	struct sadb_x_policy *xpl;
1182	struct secpolicy *pcb_sp;
1183
1184	/* sanity check. */
1185	if (in6p == NULL || request == NULL || mp == NULL)
1186		return EINVAL;
1187	IPSEC_ASSERT(in6p->in6p_sp != NULL, ("null in6p_sp"));
1188	if (len < sizeof(*xpl))
1189		return EINVAL;
1190	xpl = (struct sadb_x_policy *)request;
1191
1192	/* select direction */
1193	switch (xpl->sadb_x_policy_dir) {
1194	case IPSEC_DIR_INBOUND:
1195		pcb_sp = in6p->in6p_sp->sp_in;
1196		break;
1197	case IPSEC_DIR_OUTBOUND:
1198		pcb_sp = in6p->in6p_sp->sp_out;
1199		break;
1200	default:
1201		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1202			xpl->sadb_x_policy_dir));
1203		return EINVAL;
1204	}
1205
1206	return ipsec_get_policy(pcb_sp, mp);
1207}
1208
1209int
1210ipsec6_delete_pcbpolicy(in6p)
1211	struct in6pcb *in6p;
1212{
1213	IPSEC_ASSERT(in6p != NULL, ("null in6p"));
1214
1215	if (in6p->in6p_sp == NULL)
1216		return 0;
1217
1218	if (in6p->in6p_sp->sp_in != NULL)
1219		KEY_FREESP(&in6p->in6p_sp->sp_in);
1220
1221	if (in6p->in6p_sp->sp_out != NULL)
1222		KEY_FREESP(&in6p->in6p_sp->sp_out);
1223
1224	ipsec_delpcbpolicy(in6p->in6p_sp);
1225	in6p->in6p_sp = NULL;
1226
1227	return 0;
1228}
1229#endif
1230
1231/*
1232 * return current level.
1233 * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1234 */
1235u_int
1236ipsec_get_reqlevel(isr)
1237	struct ipsecrequest *isr;
1238{
1239	u_int level = 0;
1240	u_int esp_trans_deflev, esp_net_deflev;
1241	u_int ah_trans_deflev, ah_net_deflev;
1242
1243	IPSEC_ASSERT(isr != NULL && isr->sp != NULL, ("null argument"));
1244	IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1245		("af family mismatch, src %u, dst %u",
1246		 isr->sp->spidx.src.sa.sa_family,
1247		 isr->sp->spidx.dst.sa.sa_family));
1248
1249/* XXX note that we have ipseclog() expanded here - code sync issue */
1250#define IPSEC_CHECK_DEFAULT(lev) \
1251	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE	      \
1252			&& (lev) != IPSEC_LEVEL_UNIQUE)			      \
1253		? (ipsec_debug						      \
1254			? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
1255				(lev), IPSEC_LEVEL_REQUIRE)		      \
1256			: 0),						      \
1257			(lev) = IPSEC_LEVEL_REQUIRE,			      \
1258			(lev)						      \
1259		: (lev))
1260
1261	/* set default level */
1262	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1263#ifdef INET
1264	case AF_INET:
1265		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1266		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1267		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1268		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1269		break;
1270#endif
1271#ifdef INET6
1272	case AF_INET6:
1273		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1274		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1275		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1276		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1277		break;
1278#endif /* INET6 */
1279	default:
1280		panic("%s: unknown af %u",
1281			__func__, isr->sp->spidx.src.sa.sa_family);
1282	}
1283
1284#undef IPSEC_CHECK_DEFAULT
1285
1286	/* set level */
1287	switch (isr->level) {
1288	case IPSEC_LEVEL_DEFAULT:
1289		switch (isr->saidx.proto) {
1290		case IPPROTO_ESP:
1291			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1292				level = esp_net_deflev;
1293			else
1294				level = esp_trans_deflev;
1295			break;
1296		case IPPROTO_AH:
1297			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1298				level = ah_net_deflev;
1299			else
1300				level = ah_trans_deflev;
1301			break;
1302		case IPPROTO_IPCOMP:
1303			/*
1304			 * we don't really care, as IPcomp document says that
1305			 * we shouldn't compress small packets
1306			 */
1307			level = IPSEC_LEVEL_USE;
1308			break;
1309		default:
1310			panic("%s: Illegal protocol defined %u\n", __func__,
1311				isr->saidx.proto);
1312		}
1313		break;
1314
1315	case IPSEC_LEVEL_USE:
1316	case IPSEC_LEVEL_REQUIRE:
1317		level = isr->level;
1318		break;
1319	case IPSEC_LEVEL_UNIQUE:
1320		level = IPSEC_LEVEL_REQUIRE;
1321		break;
1322
1323	default:
1324		panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
1325	}
1326
1327	return level;
1328}
1329
1330/*
1331 * Check security policy requirements against the actual
1332 * packet contents.  Return one if the packet should be
1333 * reject as "invalid"; otherwiser return zero to have the
1334 * packet treated as "valid".
1335 *
1336 * OUT:
1337 *	0: valid
1338 *	1: invalid
1339 */
1340int
1341ipsec_in_reject(struct secpolicy *sp, struct mbuf *m)
1342{
1343	struct ipsecrequest *isr;
1344	int need_auth;
1345
1346	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1347		printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
1348
1349	/* check policy */
1350	switch (sp->policy) {
1351	case IPSEC_POLICY_DISCARD:
1352		return 1;
1353	case IPSEC_POLICY_BYPASS:
1354	case IPSEC_POLICY_NONE:
1355		return 0;
1356	}
1357
1358	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1359		("invalid policy %u", sp->policy));
1360
1361	/* XXX should compare policy against ipsec header history */
1362
1363	need_auth = 0;
1364	for (isr = sp->req; isr != NULL; isr = isr->next) {
1365		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1366			continue;
1367		switch (isr->saidx.proto) {
1368		case IPPROTO_ESP:
1369			if ((m->m_flags & M_DECRYPTED) == 0) {
1370				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1371				    printf("%s: ESP m_flags:%x\n", __func__,
1372					    m->m_flags));
1373				return 1;
1374			}
1375
1376			if (!need_auth &&
1377			    isr->sav != NULL &&
1378			    isr->sav->tdb_authalgxform != NULL &&
1379			    (m->m_flags & M_AUTHIPDGM) == 0) {
1380				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1381				    printf("%s: ESP/AH m_flags:%x\n", __func__,
1382					    m->m_flags));
1383				return 1;
1384			}
1385			break;
1386		case IPPROTO_AH:
1387			need_auth = 1;
1388			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1389				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1390				    printf("%s: AH m_flags:%x\n", __func__,
1391					    m->m_flags));
1392				return 1;
1393			}
1394			break;
1395		case IPPROTO_IPCOMP:
1396			/*
1397			 * we don't really care, as IPcomp document
1398			 * says that we shouldn't compress small
1399			 * packets, IPComp policy should always be
1400			 * treated as being in "use" level.
1401			 */
1402			break;
1403		}
1404	}
1405	return 0;		/* valid */
1406}
1407
1408/*
1409 * Check AH/ESP integrity.
1410 * This function is called from tcp_input(), udp_input(),
1411 * and {ah,esp}4_input for tunnel mode
1412 */
1413int
1414ipsec4_in_reject(m, inp)
1415	struct mbuf *m;
1416	struct inpcb *inp;
1417{
1418	struct secpolicy *sp;
1419	int error;
1420	int result;
1421
1422	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1423
1424	/* get SP for this packet.
1425	 * When we are called from ip_forward(), we call
1426	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1427	 */
1428	if (inp == NULL)
1429		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1430	else
1431		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1432
1433	if (sp != NULL) {
1434		result = ipsec_in_reject(sp, m);
1435		if (result)
1436			newipsecstat.ips_in_polvio++;
1437		KEY_FREESP(&sp);
1438	} else {
1439		result = 0;	/* XXX should be panic ?
1440				 * -> No, there may be error. */
1441	}
1442	return result;
1443}
1444
1445#ifdef INET6
1446/*
1447 * Check AH/ESP integrity.
1448 * This function is called from tcp6_input(), udp6_input(),
1449 * and {ah,esp}6_input for tunnel mode
1450 */
1451int
1452ipsec6_in_reject(m, inp)
1453	struct mbuf *m;
1454	struct inpcb *inp;
1455{
1456	struct secpolicy *sp = NULL;
1457	int error;
1458	int result;
1459
1460	/* sanity check */
1461	if (m == NULL)
1462		return 0;	/* XXX should be panic ? */
1463
1464	/* get SP for this packet.
1465	 * When we are called from ip_forward(), we call
1466	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1467	 */
1468	if (inp == NULL)
1469		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1470	else
1471		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1472
1473	if (sp != NULL) {
1474		result = ipsec_in_reject(sp, m);
1475		if (result)
1476			newipsecstat.ips_in_polvio++;
1477		KEY_FREESP(&sp);
1478	} else {
1479		result = 0;
1480	}
1481	return result;
1482}
1483#endif
1484
1485/*
1486 * compute the byte size to be occupied by IPsec header.
1487 * in case it is tunneled, it includes the size of outer IP header.
1488 * NOTE: SP passed is free in this function.
1489 */
1490static size_t
1491ipsec_hdrsiz(struct secpolicy *sp)
1492{
1493	struct ipsecrequest *isr;
1494	size_t siz;
1495
1496	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1497		printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
1498
1499	switch (sp->policy) {
1500	case IPSEC_POLICY_DISCARD:
1501	case IPSEC_POLICY_BYPASS:
1502	case IPSEC_POLICY_NONE:
1503		return 0;
1504	}
1505
1506	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1507		("invalid policy %u", sp->policy));
1508
1509	siz = 0;
1510	for (isr = sp->req; isr != NULL; isr = isr->next) {
1511		size_t clen = 0;
1512
1513		switch (isr->saidx.proto) {
1514		case IPPROTO_ESP:
1515			clen = esp_hdrsiz(isr->sav);
1516			break;
1517		case IPPROTO_AH:
1518			clen = ah_hdrsiz(isr->sav);
1519			break;
1520		case IPPROTO_IPCOMP:
1521			clen = sizeof(struct ipcomp);
1522			break;
1523		}
1524
1525		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1526			switch (isr->saidx.dst.sa.sa_family) {
1527			case AF_INET:
1528				clen += sizeof(struct ip);
1529				break;
1530#ifdef INET6
1531			case AF_INET6:
1532				clen += sizeof(struct ip6_hdr);
1533				break;
1534#endif
1535			default:
1536				ipseclog((LOG_ERR, "%s: unknown AF %d in "
1537				    "IPsec tunnel SA\n", __func__,
1538				    ((struct sockaddr *)&isr->saidx.dst)->sa_family));
1539				break;
1540			}
1541		}
1542		siz += clen;
1543	}
1544
1545	return siz;
1546}
1547
1548/* This function is called from ip_forward() and ipsec4_hdrsize_tcp(). */
1549size_t
1550ipsec4_hdrsiz(m, dir, inp)
1551	struct mbuf *m;
1552	u_int dir;
1553	struct inpcb *inp;
1554{
1555	struct secpolicy *sp;
1556	int error;
1557	size_t size;
1558
1559	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1560
1561	/* get SP for this packet.
1562	 * When we are called from ip_forward(), we call
1563	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1564	 */
1565	if (inp == NULL)
1566		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1567	else
1568		sp = ipsec_getpolicybysock(m, dir, inp, &error);
1569
1570	if (sp != NULL) {
1571		size = ipsec_hdrsiz(sp);
1572		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1573			printf("%s: size:%lu.\n", __func__,
1574				(unsigned long)size));
1575
1576		KEY_FREESP(&sp);
1577	} else {
1578		size = 0;	/* XXX should be panic ? */
1579	}
1580	return size;
1581}
1582
1583#ifdef INET6
1584/* This function is called from ipsec6_hdrsize_tcp(),
1585 * and maybe from ip6_forward.()
1586 */
1587size_t
1588ipsec6_hdrsiz(m, dir, in6p)
1589	struct mbuf *m;
1590	u_int dir;
1591	struct in6pcb *in6p;
1592{
1593	struct secpolicy *sp;
1594	int error;
1595	size_t size;
1596
1597	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1598	IPSEC_ASSERT(in6p == NULL || in6p->in6p_socket != NULL,
1599		("socket w/o inpcb"));
1600
1601	/* get SP for this packet */
1602	/* XXX Is it right to call with IP_FORWARDING. */
1603	if (in6p == NULL)
1604		sp = ipsec_getpolicybyaddr(m, dir, IP_FORWARDING, &error);
1605	else
1606		sp = ipsec_getpolicybysock(m, dir, in6p, &error);
1607
1608	if (sp == NULL)
1609		return 0;
1610	size = ipsec_hdrsiz(sp);
1611	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1612		printf("%s: size:%lu.\n", __func__, (unsigned long)size));
1613	KEY_FREESP(&sp);
1614
1615	return size;
1616}
1617#endif /*INET6*/
1618
1619/*
1620 * Check the variable replay window.
1621 * ipsec_chkreplay() performs replay check before ICV verification.
1622 * ipsec_updatereplay() updates replay bitmap.  This must be called after
1623 * ICV verification (it also performs replay check, which is usually done
1624 * beforehand).
1625 * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1626 *
1627 * based on RFC 2401.
1628 */
1629int
1630ipsec_chkreplay(seq, sav)
1631	u_int32_t seq;
1632	struct secasvar *sav;
1633{
1634	const struct secreplay *replay;
1635	u_int32_t diff;
1636	int fr;
1637	u_int32_t wsizeb;	/* constant: bits of window size */
1638	int frlast;		/* constant: last frame */
1639
1640	IPSEC_SPLASSERT_SOFTNET(__func__);
1641
1642	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1643	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1644
1645	replay = sav->replay;
1646
1647	if (replay->wsize == 0)
1648		return 1;	/* no need to check replay. */
1649
1650	/* constant */
1651	frlast = replay->wsize - 1;
1652	wsizeb = replay->wsize << 3;
1653
1654	/* sequence number of 0 is invalid */
1655	if (seq == 0)
1656		return 0;
1657
1658	/* first time is always okay */
1659	if (replay->count == 0)
1660		return 1;
1661
1662	if (seq > replay->lastseq) {
1663		/* larger sequences are okay */
1664		return 1;
1665	} else {
1666		/* seq is equal or less than lastseq. */
1667		diff = replay->lastseq - seq;
1668
1669		/* over range to check, i.e. too old or wrapped */
1670		if (diff >= wsizeb)
1671			return 0;
1672
1673		fr = frlast - diff / 8;
1674
1675		/* this packet already seen ? */
1676		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1677			return 0;
1678
1679		/* out of order but good */
1680		return 1;
1681	}
1682}
1683
1684/*
1685 * check replay counter whether to update or not.
1686 * OUT:	0:	OK
1687 *	1:	NG
1688 */
1689int
1690ipsec_updatereplay(seq, sav)
1691	u_int32_t seq;
1692	struct secasvar *sav;
1693{
1694	struct secreplay *replay;
1695	u_int32_t diff;
1696	int fr;
1697	u_int32_t wsizeb;	/* constant: bits of window size */
1698	int frlast;		/* constant: last frame */
1699
1700	IPSEC_SPLASSERT_SOFTNET(__func__);
1701
1702	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1703	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1704
1705	replay = sav->replay;
1706
1707	if (replay->wsize == 0)
1708		goto ok;	/* no need to check replay. */
1709
1710	/* constant */
1711	frlast = replay->wsize - 1;
1712	wsizeb = replay->wsize << 3;
1713
1714	/* sequence number of 0 is invalid */
1715	if (seq == 0)
1716		return 1;
1717
1718	/* first time */
1719	if (replay->count == 0) {
1720		replay->lastseq = seq;
1721		bzero(replay->bitmap, replay->wsize);
1722		(replay->bitmap)[frlast] = 1;
1723		goto ok;
1724	}
1725
1726	if (seq > replay->lastseq) {
1727		/* seq is larger than lastseq. */
1728		diff = seq - replay->lastseq;
1729
1730		/* new larger sequence number */
1731		if (diff < wsizeb) {
1732			/* In window */
1733			/* set bit for this packet */
1734			vshiftl(replay->bitmap, diff, replay->wsize);
1735			(replay->bitmap)[frlast] |= 1;
1736		} else {
1737			/* this packet has a "way larger" */
1738			bzero(replay->bitmap, replay->wsize);
1739			(replay->bitmap)[frlast] = 1;
1740		}
1741		replay->lastseq = seq;
1742
1743		/* larger is good */
1744	} else {
1745		/* seq is equal or less than lastseq. */
1746		diff = replay->lastseq - seq;
1747
1748		/* over range to check, i.e. too old or wrapped */
1749		if (diff >= wsizeb)
1750			return 1;
1751
1752		fr = frlast - diff / 8;
1753
1754		/* this packet already seen ? */
1755		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1756			return 1;
1757
1758		/* mark as seen */
1759		(replay->bitmap)[fr] |= (1 << (diff % 8));
1760
1761		/* out of order but good */
1762	}
1763
1764ok:
1765	if (replay->count == ~0) {
1766
1767		/* set overflow flag */
1768		replay->overflow++;
1769
1770		/* don't increment, no more packets accepted */
1771		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
1772			return 1;
1773
1774		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1775		    __func__, replay->overflow, ipsec_logsastr(sav)));
1776	}
1777
1778	replay->count++;
1779
1780	return 0;
1781}
1782
1783/*
1784 * shift variable length buffer to left.
1785 * IN:	bitmap: pointer to the buffer
1786 * 	nbit:	the number of to shift.
1787 *	wsize:	buffer size (bytes).
1788 */
1789static void
1790vshiftl(bitmap, nbit, wsize)
1791	unsigned char *bitmap;
1792	int nbit, wsize;
1793{
1794	int s, j, i;
1795	unsigned char over;
1796
1797	for (j = 0; j < nbit; j += 8) {
1798		s = (nbit - j < 8) ? (nbit - j): 8;
1799		bitmap[0] <<= s;
1800		for (i = 1; i < wsize; i++) {
1801			over = (bitmap[i] >> (8 - s));
1802			bitmap[i] <<= s;
1803			bitmap[i-1] |= over;
1804		}
1805	}
1806
1807	return;
1808}
1809
1810/* Return a printable string for the IPv4 address. */
1811static char *
1812inet_ntoa4(struct in_addr ina)
1813{
1814	static char buf[4][4 * sizeof "123" + 4];
1815	unsigned char *ucp = (unsigned char *) &ina;
1816	static int i = 3;
1817
1818	i = (i + 1) % 4;
1819	sprintf(buf[i], "%d.%d.%d.%d", ucp[0] & 0xff, ucp[1] & 0xff,
1820	    ucp[2] & 0xff, ucp[3] & 0xff);
1821	return (buf[i]);
1822}
1823
1824/* Return a printable string for the address. */
1825char *
1826ipsec_address(union sockaddr_union* sa)
1827{
1828	switch (sa->sa.sa_family) {
1829#if INET
1830	case AF_INET:
1831		return inet_ntoa4(sa->sin.sin_addr);
1832#endif /* INET */
1833
1834#if INET6
1835	case AF_INET6:
1836		return ip6_sprintf(&sa->sin6.sin6_addr);
1837#endif /* INET6 */
1838
1839	default:
1840		return "(unknown address family)";
1841	}
1842}
1843
1844const char *
1845ipsec_logsastr(sav)
1846	struct secasvar *sav;
1847{
1848	static char buf[256];
1849	char *p;
1850	struct secasindex *saidx = &sav->sah->saidx;
1851
1852	IPSEC_ASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
1853		("address family mismatch"));
1854
1855	p = buf;
1856	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
1857	while (p && *p)
1858		p++;
1859	/* NB: only use ipsec_address on one address at a time */
1860	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
1861		ipsec_address(&saidx->src));
1862	while (p && *p)
1863		p++;
1864	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
1865		ipsec_address(&saidx->dst));
1866
1867	return buf;
1868}
1869
1870void
1871ipsec_dumpmbuf(m)
1872	struct mbuf *m;
1873{
1874	int totlen;
1875	int i;
1876	u_char *p;
1877
1878	totlen = 0;
1879	printf("---\n");
1880	while (m) {
1881		p = mtod(m, u_char *);
1882		for (i = 0; i < m->m_len; i++) {
1883			printf("%02x ", p[i]);
1884			totlen++;
1885			if (totlen % 16 == 0)
1886				printf("\n");
1887		}
1888		m = m->m_next;
1889	}
1890	if (totlen % 16 != 0)
1891		printf("\n");
1892	printf("---\n");
1893}
1894
1895static void
1896ipsec_attach(void)
1897{
1898	SECPOLICY_LOCK_INIT(&ip4_def_policy);
1899	ip4_def_policy.refcnt = 1;			/* NB: disallow free */
1900}
1901SYSINIT(ipsec, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST, ipsec_attach, NULL)
1902
1903
1904/* XXX this stuff doesn't belong here... */
1905
1906static	struct xformsw* xforms = NULL;
1907
1908/*
1909 * Register a transform; typically at system startup.
1910 */
1911void
1912xform_register(struct xformsw* xsp)
1913{
1914	xsp->xf_next = xforms;
1915	xforms = xsp;
1916}
1917
1918/*
1919 * Initialize transform support in an sav.
1920 */
1921int
1922xform_init(struct secasvar *sav, int xftype)
1923{
1924	struct xformsw *xsp;
1925
1926	if (sav->tdb_xform != NULL)	/* previously initialized */
1927		return 0;
1928	for (xsp = xforms; xsp; xsp = xsp->xf_next)
1929		if (xsp->xf_type == xftype)
1930			return (*xsp->xf_init)(sav, xsp);
1931	return EINVAL;
1932}
1933