ipsec.c revision 111396
1/*	$FreeBSD: head/sys/netipsec/ipsec.c 111396 2003-02-24 02:06:02Z jlemon $	*/
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#include <net/net_osdep.h>
96
97#ifdef IPSEC_DEBUG
98int ipsec_debug = 1;
99#else
100int ipsec_debug = 0;
101#endif
102
103/* NB: name changed so netstat doesn't use it */
104struct newipsecstat newipsecstat;
105int ip4_ah_offsetmask = 0;	/* maybe IP_DF? */
106int ip4_ipsec_dfbit = 0;	/* DF bit on encap. 0: clear 1: set 2: copy */
107int ip4_esp_trans_deflev = IPSEC_LEVEL_USE;
108int ip4_esp_net_deflev = IPSEC_LEVEL_USE;
109int ip4_ah_trans_deflev = IPSEC_LEVEL_USE;
110int ip4_ah_net_deflev = IPSEC_LEVEL_USE;
111struct secpolicy ip4_def_policy;
112int ip4_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
113int ip4_esp_randpad = -1;
114/*
115 * Crypto support requirements:
116 *
117 *  1	require hardware support
118 * -1	require software support
119 *  0	take anything
120 */
121int	crypto_support = 0;
122
123SYSCTL_DECL(_net_inet_ipsec);
124
125/* net.inet.ipsec */
126SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_POLICY,
127	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
128SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
129	CTLFLAG_RW, &ip4_esp_trans_deflev,	0, "");
130SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
131	CTLFLAG_RW, &ip4_esp_net_deflev,	0, "");
132SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
133	CTLFLAG_RW, &ip4_ah_trans_deflev,	0, "");
134SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
135	CTLFLAG_RW, &ip4_ah_net_deflev,	0, "");
136SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS,
137	ah_cleartos, CTLFLAG_RW,	&ah_cleartos,	0, "");
138SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_OFFSETMASK,
139	ah_offsetmask, CTLFLAG_RW,	&ip4_ah_offsetmask,	0, "");
140SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT,
141	dfbit, CTLFLAG_RW,	&ip4_ipsec_dfbit,	0, "");
142SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN,
143	ecn, CTLFLAG_RW,	&ip4_ipsec_ecn,	0, "");
144SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEBUG,
145	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
146SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ESP_RANDPAD,
147	esp_randpad, CTLFLAG_RW,	&ip4_esp_randpad,	0, "");
148SYSCTL_INT(_net_inet_ipsec, OID_AUTO,
149	crypto_support,	CTLFLAG_RW,	&crypto_support,0, "");
150SYSCTL_STRUCT(_net_inet_ipsec, OID_AUTO,
151	ipsecstats,	CTLFLAG_RD,	&newipsecstat,	newipsecstat, "");
152
153#ifdef INET6
154int ip6_esp_trans_deflev = IPSEC_LEVEL_USE;
155int ip6_esp_net_deflev = IPSEC_LEVEL_USE;
156int ip6_ah_trans_deflev = IPSEC_LEVEL_USE;
157int ip6_ah_net_deflev = IPSEC_LEVEL_USE;
158int ip6_ipsec_ecn = 0;		/* ECN ignore(-1)/forbidden(0)/allowed(1) */
159int ip6_esp_randpad = -1;
160
161SYSCTL_DECL(_net_inet6_ipsec6);
162
163/* net.inet6.ipsec6 */
164#ifdef COMPAT_KAME
165SYSCTL_OID(_net_inet6_ipsec6, IPSECCTL_STATS, stats, CTLFLAG_RD,
166	0,0, compat_ipsecstats_sysctl, "S", "");
167#endif /* COMPAT_KAME */
168SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY,
169	def_policy, CTLFLAG_RW,	&ip4_def_policy.policy,	0, "");
170SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
171	CTLFLAG_RW, &ip6_esp_trans_deflev,	0, "");
172SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
173	CTLFLAG_RW, &ip6_esp_net_deflev,	0, "");
174SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
175	CTLFLAG_RW, &ip6_ah_trans_deflev,	0, "");
176SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
177	CTLFLAG_RW, &ip6_ah_net_deflev,	0, "");
178SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN,
179	ecn, CTLFLAG_RW,	&ip6_ipsec_ecn,	0, "");
180SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEBUG,
181	debug, CTLFLAG_RW,	&ipsec_debug,	0, "");
182SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ESP_RANDPAD,
183	esp_randpad, CTLFLAG_RW,	&ip6_esp_randpad,	0, "");
184#endif /* INET6 */
185
186static int ipsec4_setspidx_inpcb __P((struct mbuf *, struct inpcb *pcb));
187#ifdef INET6
188static int ipsec6_setspidx_in6pcb __P((struct mbuf *, struct in6pcb *pcb));
189#endif
190static int ipsec_setspidx __P((struct mbuf *, struct secpolicyindex *, int));
191static void ipsec4_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
192static int ipsec4_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
193#ifdef INET6
194static void ipsec6_get_ulp __P((struct mbuf *m, struct secpolicyindex *, int));
195static int ipsec6_setspidx_ipaddr __P((struct mbuf *, struct secpolicyindex *));
196#endif
197static void ipsec_delpcbpolicy __P((struct inpcbpolicy *));
198static struct secpolicy *ipsec_deepcopy_policy __P((struct secpolicy *src));
199static int ipsec_set_policy __P((struct secpolicy **pcb_sp,
200	int optname, caddr_t request, size_t len, int priv));
201static int ipsec_get_policy __P((struct secpolicy *pcb_sp, struct mbuf **mp));
202static void vshiftl __P((unsigned char *, int, int));
203static size_t ipsec_hdrsiz __P((struct secpolicy *));
204
205/*
206 * Return a held reference to the default SP.
207 */
208static struct secpolicy *
209key_allocsp_default(const char* where, int tag)
210{
211	struct secpolicy *sp;
212
213	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
214		printf("DP key_allocsp_default from %s:%u\n", where, tag));
215
216	sp = &ip4_def_policy;
217	if (sp->policy != IPSEC_POLICY_DISCARD &&
218	    sp->policy != IPSEC_POLICY_NONE) {
219		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
220		    sp->policy, IPSEC_POLICY_NONE));
221		sp->policy = IPSEC_POLICY_NONE;
222	}
223	sp->refcnt++;
224
225	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
226		printf("DP key_allocsp_default returns SP:%p (%u)\n",
227			sp, sp->refcnt));
228	return sp;
229}
230#define	KEY_ALLOCSP_DEFAULT() \
231	key_allocsp_default(__FILE__, __LINE__)
232
233/*
234 * For OUTBOUND packet having a socket. Searching SPD for packet,
235 * and return a pointer to SP.
236 * OUT:	NULL:	no apropreate SP found, the following value is set to error.
237 *		0	: bypass
238 *		EACCES	: discard packet.
239 *		ENOENT	: ipsec_acquire() in progress, maybe.
240 *		others	: error occured.
241 *	others:	a pointer to SP
242 *
243 * NOTE: IPv6 mapped adddress concern is implemented here.
244 */
245struct secpolicy *
246ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir)
247{
248	struct secpolicy *sp;
249
250	KASSERT(tdbi != NULL, ("ipsec_getpolicy: null tdbi"));
251	KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
252		("ipsec_getpolicy: invalid direction %u", dir));
253
254	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
255	if (sp == NULL)			/*XXX????*/
256		sp = KEY_ALLOCSP_DEFAULT();
257	KASSERT(sp != NULL, ("ipsec_getpolicy: null SP"));
258	return sp;
259}
260
261/*
262 * For OUTBOUND packet having a socket. Searching SPD for packet,
263 * and return a pointer to SP.
264 * OUT:	NULL:	no apropreate SP found, the following value is set to error.
265 *		0	: bypass
266 *		EACCES	: discard packet.
267 *		ENOENT	: ipsec_acquire() in progress, maybe.
268 *		others	: error occured.
269 *	others:	a pointer to SP
270 *
271 * NOTE: IPv6 mapped adddress concern is implemented here.
272 */
273struct secpolicy *
274ipsec_getpolicybysock(m, dir, inp, error)
275	struct mbuf *m;
276	u_int dir;
277	struct inpcb *inp;
278	int *error;
279{
280	struct inpcbpolicy *pcbsp = NULL;
281	struct secpolicy *currsp = NULL;	/* policy on socket */
282	struct secpolicy *sp;
283
284	KASSERT(m != NULL, ("ipsec_getpolicybysock: null mbuf"));
285	KASSERT(inp != NULL, ("ipsec_getpolicybysock: null inpcb"));
286	KASSERT(error != NULL, ("ipsec_getpolicybysock: null error"));
287	KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
288		("ipsec_getpolicybysock: invalid direction %u", dir));
289
290	/* set spidx in pcb */
291	if (inp->inp_vflag & INP_IPV6PROTO) {
292		*error = ipsec6_setspidx_in6pcb(m, inp);
293		pcbsp = inp->in6p_sp;
294	} else {
295		*error = ipsec4_setspidx_inpcb(m, inp);
296		pcbsp = inp->inp_sp;
297	}
298	if (*error)
299		return NULL;
300
301	KASSERT(pcbsp != NULL, ("ipsec_getpolicybysock: null pcbsp"));
302	switch (dir) {
303	case IPSEC_DIR_INBOUND:
304		currsp = pcbsp->sp_in;
305		break;
306	case IPSEC_DIR_OUTBOUND:
307		currsp = pcbsp->sp_out;
308		break;
309	}
310	KASSERT(currsp != NULL, ("ipsec_getpolicybysock: null currsp"));
311
312	if (pcbsp->priv) {			/* when privilieged socket */
313		switch (currsp->policy) {
314		case IPSEC_POLICY_BYPASS:
315		case IPSEC_POLICY_IPSEC:
316			currsp->refcnt++;
317			sp = currsp;
318			break;
319
320		case IPSEC_POLICY_ENTRUST:
321			/* look for a policy in SPD */
322			sp = KEY_ALLOCSP(&currsp->spidx, dir);
323			if (sp == NULL)		/* no SP found */
324				sp = KEY_ALLOCSP_DEFAULT();
325			break;
326
327		default:
328			ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
329			      "Invalid policy for PCB %d\n", currsp->policy));
330			*error = EINVAL;
331			return NULL;
332		}
333	} else {				/* unpriv, SPD has policy */
334		sp = KEY_ALLOCSP(&currsp->spidx, dir);
335		if (sp == NULL) {		/* no SP found */
336			switch (currsp->policy) {
337			case IPSEC_POLICY_BYPASS:
338				ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
339				       "Illegal policy for non-priviliged defined %d\n",
340					currsp->policy));
341				*error = EINVAL;
342				return NULL;
343
344			case IPSEC_POLICY_ENTRUST:
345				sp = KEY_ALLOCSP_DEFAULT();
346				break;
347
348			case IPSEC_POLICY_IPSEC:
349				currsp->refcnt++;
350				sp = currsp;
351				break;
352
353			default:
354				ipseclog((LOG_ERR, "ipsec_getpolicybysock: "
355				   "Invalid policy for PCB %d\n", currsp->policy));
356				*error = EINVAL;
357				return NULL;
358			}
359		}
360	}
361	KASSERT(sp != NULL,
362		("ipsec_getpolicybysock: null SP (priv %u policy %u",
363		 pcbsp->priv, currsp->policy));
364	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
365		printf("DP ipsec_getpolicybysock (priv %u policy %u) allocates "
366		       "SP:%p (refcnt %u)\n", pcbsp->priv, currsp->policy,
367		       sp, sp->refcnt));
368	return sp;
369}
370
371/*
372 * For FORWADING packet or OUTBOUND without a socket. Searching SPD for packet,
373 * and return a pointer to SP.
374 * OUT:	positive: a pointer to the entry for security policy leaf matched.
375 *	NULL:	no apropreate SP found, the following value is set to error.
376 *		0	: bypass
377 *		EACCES	: discard packet.
378 *		ENOENT	: ipsec_acquire() in progress, maybe.
379 *		others	: error occured.
380 */
381struct secpolicy *
382ipsec_getpolicybyaddr(m, dir, flag, error)
383	struct mbuf *m;
384	u_int dir;
385	int flag;
386	int *error;
387{
388	struct secpolicyindex spidx;
389	struct secpolicy *sp;
390
391	KASSERT(m != NULL, ("ipsec_getpolicybyaddr: null mbuf"));
392	KASSERT(error != NULL, ("ipsec_getpolicybyaddr: null error"));
393	KASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
394		("ipsec4_getpolicybaddr: invalid direction %u", dir));
395
396	sp = NULL;
397	if (key_havesp(dir)) {
398		/* Make an index to look for a policy. */
399		*error = ipsec_setspidx(m, &spidx,
400					(flag & IP_FORWARDING) ? 0 : 1);
401		if (*error != 0) {
402			DPRINTF(("ipsec_getpolicybyaddr: setpidx failed,"
403				" dir %u flag %u\n", dir, flag));
404			bzero(&spidx, sizeof (spidx));
405			return NULL;
406		}
407		spidx.dir = dir;
408
409		sp = KEY_ALLOCSP(&spidx, dir);
410	}
411	if (sp == NULL)			/* no SP found, use system default */
412		sp = KEY_ALLOCSP_DEFAULT();
413	KASSERT(sp != NULL, ("ipsec_getpolicybyaddr: null SP"));
414	return sp;
415}
416
417struct secpolicy *
418ipsec4_checkpolicy(m, dir, flag, error, inp)
419	struct mbuf *m;
420	u_int dir, flag;
421	int *error;
422	struct inpcb *inp;
423{
424	struct secpolicy *sp;
425
426	*error = 0;
427	if (inp == NULL)
428		sp = ipsec_getpolicybyaddr(m, dir, flag, error);
429	else
430		sp = ipsec_getpolicybysock(m, dir, inp, error);
431	if (sp == NULL) {
432		KASSERT(*error != 0,
433			("ipsec4_checkpolicy: getpolicy failed w/o error"));
434		newipsecstat.ips_out_inval++;
435		return NULL;
436	}
437	KASSERT(*error == 0,
438		("ipsec4_checkpolicy: sp w/ error set to %u", *error));
439	switch (sp->policy) {
440	case IPSEC_POLICY_ENTRUST:
441	default:
442		printf("ipsec4_checkpolicy: invalid policy %u\n", 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	KASSERT(pcb != NULL, ("ipsec4_setspidx_inpcb: null pcb"));
473	KASSERT(pcb->inp_sp != NULL, ("ipsec4_setspidx_inpcb: null inp_sp"));
474	KASSERT(pcb->inp_sp->sp_out != NULL && pcb->inp_sp->sp_in != NULL,
475		("ipsec4_setspidx_inpcb: 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	KASSERT(pcb != NULL, ("ipsec6_setspidx_in6pcb: null pcb"));
501	KASSERT(pcb->in6p_sp != NULL, ("ipsec6_setspidx_in6pcb: null inp_sp"));
502	KASSERT(pcb->in6p_sp->sp_out != NULL && pcb->in6p_sp->sp_in != NULL,
503		("ipsec6_setspidx_in6pcb: 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	KASSERT(m != NULL, ("ipsec_setspidx: 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("ipsec_setspidx: "
560			       "total of m_len(%d) != pkthdr.len(%d), "
561			       "ignored.\n",
562				len, m->m_pkthdr.len));
563		return EINVAL;
564	}
565
566	if (m->m_pkthdr.len < sizeof(struct ip)) {
567		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
568			printf("ipsec_setspidx: "
569			    "pkthdr.len(%d) < sizeof(struct ip), ignored.\n",
570			    m->m_pkthdr.len));
571		return EINVAL;
572	}
573
574	if (m->m_len >= sizeof(*ip))
575		ip = mtod(m, struct ip *);
576	else {
577		m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
578		ip = &ipbuf;
579	}
580#ifdef _IP_VHL
581	v = _IP_VHL_V(ip->ip_vhl);
582#else
583	v = ip->ip_v;
584#endif
585	switch (v) {
586	case 4:
587		error = ipsec4_setspidx_ipaddr(m, spidx);
588		if (error)
589			return error;
590		ipsec4_get_ulp(m, spidx, needport);
591		return 0;
592#ifdef INET6
593	case 6:
594		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
595			KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
596				printf("ipsec_setspidx: "
597				    "pkthdr.len(%d) < sizeof(struct ip6_hdr), "
598				    "ignored.\n", m->m_pkthdr.len));
599			return EINVAL;
600		}
601		error = ipsec6_setspidx_ipaddr(m, spidx);
602		if (error)
603			return error;
604		ipsec6_get_ulp(m, spidx, needport);
605		return 0;
606#endif
607	default:
608		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
609			printf("ipsec_setspidx: "
610			    "unknown IP version %u, ignored.\n", v));
611		return EINVAL;
612	}
613}
614
615static void
616ipsec4_get_ulp(struct mbuf *m, struct secpolicyindex *spidx, int needport)
617{
618	u_int8_t nxt;
619	int off;
620
621	/* sanity check */
622	KASSERT(m != NULL, ("ipsec4_get_ulp: null mbuf"));
623	KASSERT(m->m_pkthdr.len >= sizeof(struct ip),
624		("ipsec4_get_ulp: packet too short"));
625
626	/* NB: ip_input() flips it into host endian XXX need more checking */
627	if (m->m_len < sizeof (struct ip)) {
628		struct ip *ip = mtod(m, struct ip *);
629		if (ip->ip_off & (IP_MF | IP_OFFMASK))
630			goto done;
631#ifdef _IP_VHL
632		off = _IP_VHL_HL(ip->ip_vhl) << 2;
633#else
634		off = ip->ip_hl << 2;
635#endif
636		nxt = ip->ip_p;
637	} else {
638		struct ip ih;
639
640		m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
641		if (ih.ip_off & (IP_MF | IP_OFFMASK))
642			goto done;
643#ifdef _IP_VHL
644		off = _IP_VHL_HL(ih.ip_vhl) << 2;
645#else
646		off = ih.ip_hl << 2;
647#endif
648		nxt = ih.ip_p;
649	}
650
651	while (off < m->m_pkthdr.len) {
652		struct ip6_ext ip6e;
653		struct tcphdr th;
654		struct udphdr uh;
655
656		switch (nxt) {
657		case IPPROTO_TCP:
658			spidx->ul_proto = nxt;
659			if (!needport)
660				goto done_proto;
661			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
662				goto done;
663			m_copydata(m, off, sizeof (th), (caddr_t) &th);
664			spidx->src.sin.sin_port = th.th_sport;
665			spidx->dst.sin.sin_port = th.th_dport;
666			return;
667		case IPPROTO_UDP:
668			spidx->ul_proto = nxt;
669			if (!needport)
670				goto done_proto;
671			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
672				goto done;
673			m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
674			spidx->src.sin.sin_port = uh.uh_sport;
675			spidx->dst.sin.sin_port = uh.uh_dport;
676			return;
677		case IPPROTO_AH:
678			if (m->m_pkthdr.len > off + sizeof(ip6e))
679				goto done;
680			/* XXX sigh, this works but is totally bogus */
681			m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
682			off += (ip6e.ip6e_len + 2) << 2;
683			nxt = ip6e.ip6e_nxt;
684			break;
685		case IPPROTO_ICMP:
686		default:
687			/* XXX intermediate headers??? */
688			spidx->ul_proto = nxt;
689			goto done_proto;
690		}
691	}
692done:
693	spidx->ul_proto = IPSEC_ULPROTO_ANY;
694done_proto:
695	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
696	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
697}
698
699/* assumes that m is sane */
700static int
701ipsec4_setspidx_ipaddr(struct mbuf *m, struct secpolicyindex *spidx)
702{
703	static const struct sockaddr_in template = {
704		sizeof (struct sockaddr_in),
705		AF_INET,
706		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
707	};
708
709	spidx->src.sin = template;
710	spidx->dst.sin = template;
711
712	if (m->m_len < sizeof (struct ip)) {
713		m_copydata(m, offsetof(struct ip, ip_src),
714			   sizeof (struct  in_addr),
715			   (caddr_t) &spidx->src.sin.sin_addr);
716		m_copydata(m, offsetof(struct ip, ip_dst),
717			   sizeof (struct  in_addr),
718			   (caddr_t) &spidx->dst.sin.sin_addr);
719	} else {
720		struct ip *ip = mtod(m, struct ip *);
721		spidx->src.sin.sin_addr = ip->ip_src;
722		spidx->dst.sin.sin_addr = ip->ip_dst;
723	}
724
725	spidx->prefs = sizeof(struct in_addr) << 3;
726	spidx->prefd = sizeof(struct in_addr) << 3;
727
728	return 0;
729}
730
731#ifdef INET6
732static void
733ipsec6_get_ulp(m, spidx, needport)
734	struct mbuf *m;
735	struct secpolicyindex *spidx;
736	int needport;
737{
738	int off, nxt;
739	struct tcphdr th;
740	struct udphdr uh;
741
742	/* sanity check */
743	if (m == NULL)
744		panic("ipsec6_get_ulp: NULL pointer was passed.\n");
745
746	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
747		printf("ipsec6_get_ulp:\n"); kdebug_mbuf(m));
748
749	/* set default */
750	spidx->ul_proto = IPSEC_ULPROTO_ANY;
751	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
752	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
753
754	nxt = -1;
755	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
756	if (off < 0 || m->m_pkthdr.len < off)
757		return;
758
759	switch (nxt) {
760	case IPPROTO_TCP:
761		spidx->ul_proto = nxt;
762		if (!needport)
763			break;
764		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
765			break;
766		m_copydata(m, off, sizeof(th), (caddr_t)&th);
767		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
768		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
769		break;
770	case IPPROTO_UDP:
771		spidx->ul_proto = nxt;
772		if (!needport)
773			break;
774		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
775			break;
776		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
777		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
778		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
779		break;
780	case IPPROTO_ICMPV6:
781	default:
782		/* XXX intermediate headers??? */
783		spidx->ul_proto = nxt;
784		break;
785	}
786}
787
788/* assumes that m is sane */
789static int
790ipsec6_setspidx_ipaddr(m, spidx)
791	struct mbuf *m;
792	struct secpolicyindex *spidx;
793{
794	struct ip6_hdr *ip6 = NULL;
795	struct ip6_hdr ip6buf;
796	struct sockaddr_in6 *sin6;
797
798	if (m->m_len >= sizeof(*ip6))
799		ip6 = mtod(m, struct ip6_hdr *);
800	else {
801		m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
802		ip6 = &ip6buf;
803	}
804
805	sin6 = (struct sockaddr_in6 *)&spidx->src;
806	bzero(sin6, sizeof(*sin6));
807	sin6->sin6_family = AF_INET6;
808	sin6->sin6_len = sizeof(struct sockaddr_in6);
809	bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
810	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
811		sin6->sin6_addr.s6_addr16[1] = 0;
812		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
813	}
814	spidx->prefs = sizeof(struct in6_addr) << 3;
815
816	sin6 = (struct sockaddr_in6 *)&spidx->dst;
817	bzero(sin6, sizeof(*sin6));
818	sin6->sin6_family = AF_INET6;
819	sin6->sin6_len = sizeof(struct sockaddr_in6);
820	bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
821	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
822		sin6->sin6_addr.s6_addr16[1] = 0;
823		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
824	}
825	spidx->prefd = sizeof(struct in6_addr) << 3;
826
827	return 0;
828}
829#endif
830
831static void
832ipsec_delpcbpolicy(p)
833	struct inpcbpolicy *p;
834{
835	free(p, M_SECA);
836}
837
838/* initialize policy in PCB */
839int
840ipsec_init_policy(so, pcb_sp)
841	struct socket *so;
842	struct inpcbpolicy **pcb_sp;
843{
844	struct inpcbpolicy *new;
845
846	/* sanity check. */
847	if (so == NULL || pcb_sp == NULL)
848		panic("ipsec_init_policy: NULL pointer was passed.\n");
849
850	new = (struct inpcbpolicy *) malloc(sizeof(struct inpcbpolicy),
851					    M_SECA, M_NOWAIT|M_ZERO);
852	if (new == NULL) {
853		ipseclog((LOG_DEBUG, "ipsec_init_policy: No more memory.\n"));
854		return ENOBUFS;
855	}
856
857	if (so->so_cred != 0 && so->so_cred->cr_uid == 0)
858		new->priv = 1;
859	else
860		new->priv = 0;
861
862	if ((new->sp_in = KEY_NEWSP()) == NULL) {
863		ipsec_delpcbpolicy(new);
864		return ENOBUFS;
865	}
866	new->sp_in->state = IPSEC_SPSTATE_ALIVE;
867	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
868
869	if ((new->sp_out = KEY_NEWSP()) == NULL) {
870		KEY_FREESP(&new->sp_in);
871		ipsec_delpcbpolicy(new);
872		return ENOBUFS;
873	}
874	new->sp_out->state = IPSEC_SPSTATE_ALIVE;
875	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
876
877	*pcb_sp = new;
878
879	return 0;
880}
881
882/* copy old ipsec policy into new */
883int
884ipsec_copy_policy(old, new)
885	struct inpcbpolicy *old, *new;
886{
887	struct secpolicy *sp;
888
889	sp = ipsec_deepcopy_policy(old->sp_in);
890	if (sp) {
891		KEY_FREESP(&new->sp_in);
892		new->sp_in = sp;
893	} else
894		return ENOBUFS;
895
896	sp = ipsec_deepcopy_policy(old->sp_out);
897	if (sp) {
898		KEY_FREESP(&new->sp_out);
899		new->sp_out = sp;
900	} else
901		return ENOBUFS;
902
903	new->priv = old->priv;
904
905	return 0;
906}
907
908/* deep-copy a policy in PCB */
909static struct secpolicy *
910ipsec_deepcopy_policy(src)
911	struct secpolicy *src;
912{
913	struct ipsecrequest *newchain = NULL;
914	struct ipsecrequest *p;
915	struct ipsecrequest **q;
916	struct ipsecrequest *r;
917	struct secpolicy *dst;
918
919	if (src == NULL)
920		return NULL;
921	dst = KEY_NEWSP();
922	if (dst == NULL)
923		return NULL;
924
925	/*
926	 * deep-copy IPsec request chain.  This is required since struct
927	 * ipsecrequest is not reference counted.
928	 */
929	q = &newchain;
930	for (p = src->req; p; p = p->next) {
931		*q = (struct ipsecrequest *)malloc(sizeof(struct ipsecrequest),
932			M_SECA, M_NOWAIT);
933		if (*q == NULL)
934			goto fail;
935		bzero(*q, sizeof(**q));
936		(*q)->next = NULL;
937
938		(*q)->saidx.proto = p->saidx.proto;
939		(*q)->saidx.mode = p->saidx.mode;
940		(*q)->level = p->level;
941		(*q)->saidx.reqid = p->saidx.reqid;
942
943		bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
944		bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
945
946		(*q)->sav = NULL;
947		(*q)->sp = dst;
948
949		q = &((*q)->next);
950	}
951
952	dst->req = newchain;
953	dst->state = src->state;
954	dst->policy = src->policy;
955	/* do not touch the refcnt fields */
956
957	return dst;
958
959fail:
960	for (p = newchain; p; p = r) {
961		r = p->next;
962		free(p, M_SECA);
963		p = NULL;
964	}
965	return NULL;
966}
967
968/* set policy and ipsec request if present. */
969static int
970ipsec_set_policy(pcb_sp, optname, request, len, priv)
971	struct secpolicy **pcb_sp;
972	int optname;
973	caddr_t request;
974	size_t len;
975	int priv;
976{
977	struct sadb_x_policy *xpl;
978	struct secpolicy *newsp = NULL;
979	int error;
980
981	/* sanity check. */
982	if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL)
983		return EINVAL;
984	if (len < sizeof(*xpl))
985		return EINVAL;
986	xpl = (struct sadb_x_policy *)request;
987
988	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
989		printf("ipsec_set_policy: passed policy\n");
990		kdebug_sadb_x_policy((struct sadb_ext *)xpl));
991
992	/* check policy type */
993	/* ipsec_set_policy() accepts IPSEC, ENTRUST and BYPASS. */
994	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
995	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
996		return EINVAL;
997
998	/* check privileged socket */
999	if (priv == 0 && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS)
1000		return EACCES;
1001
1002	/* allocation new SP entry */
1003	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1004		return error;
1005
1006	newsp->state = IPSEC_SPSTATE_ALIVE;
1007
1008	/* clear old SP and set new SP */
1009	KEY_FREESP(pcb_sp);
1010	*pcb_sp = newsp;
1011	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1012		printf("ipsec_set_policy: new policy\n");
1013		kdebug_secpolicy(newsp));
1014
1015	return 0;
1016}
1017
1018static int
1019ipsec_get_policy(pcb_sp, mp)
1020	struct secpolicy *pcb_sp;
1021	struct mbuf **mp;
1022{
1023
1024	/* sanity check. */
1025	if (pcb_sp == NULL || mp == NULL)
1026		return EINVAL;
1027
1028	*mp = key_sp2msg(pcb_sp);
1029	if (!*mp) {
1030		ipseclog((LOG_DEBUG, "ipsec_get_policy: No more memory.\n"));
1031		return ENOBUFS;
1032	}
1033
1034	(*mp)->m_type = MT_DATA;
1035	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1036		printf("ipsec_get_policy:\n");
1037		kdebug_mbuf(*mp));
1038
1039	return 0;
1040}
1041
1042int
1043ipsec4_set_policy(inp, optname, request, len, priv)
1044	struct inpcb *inp;
1045	int optname;
1046	caddr_t request;
1047	size_t len;
1048	int priv;
1049{
1050	struct sadb_x_policy *xpl;
1051	struct secpolicy **pcb_sp;
1052
1053	/* sanity check. */
1054	if (inp == NULL || request == NULL)
1055		return EINVAL;
1056	if (len < sizeof(*xpl))
1057		return EINVAL;
1058	xpl = (struct sadb_x_policy *)request;
1059
1060	/* select direction */
1061	switch (xpl->sadb_x_policy_dir) {
1062	case IPSEC_DIR_INBOUND:
1063		pcb_sp = &inp->inp_sp->sp_in;
1064		break;
1065	case IPSEC_DIR_OUTBOUND:
1066		pcb_sp = &inp->inp_sp->sp_out;
1067		break;
1068	default:
1069		ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
1070			xpl->sadb_x_policy_dir));
1071		return EINVAL;
1072	}
1073
1074	return ipsec_set_policy(pcb_sp, optname, request, len, priv);
1075}
1076
1077int
1078ipsec4_get_policy(inp, request, len, mp)
1079	struct inpcb *inp;
1080	caddr_t request;
1081	size_t len;
1082	struct mbuf **mp;
1083{
1084	struct sadb_x_policy *xpl;
1085	struct secpolicy *pcb_sp;
1086
1087	/* sanity check. */
1088	if (inp == NULL || request == NULL || mp == NULL)
1089		return EINVAL;
1090	KASSERT(inp->inp_sp != NULL, ("ipsec4_get_policy: null inp_sp"));
1091	if (len < sizeof(*xpl))
1092		return EINVAL;
1093	xpl = (struct sadb_x_policy *)request;
1094
1095	/* select direction */
1096	switch (xpl->sadb_x_policy_dir) {
1097	case IPSEC_DIR_INBOUND:
1098		pcb_sp = inp->inp_sp->sp_in;
1099		break;
1100	case IPSEC_DIR_OUTBOUND:
1101		pcb_sp = inp->inp_sp->sp_out;
1102		break;
1103	default:
1104		ipseclog((LOG_ERR, "ipsec4_set_policy: invalid direction=%u\n",
1105			xpl->sadb_x_policy_dir));
1106		return EINVAL;
1107	}
1108
1109	return ipsec_get_policy(pcb_sp, mp);
1110}
1111
1112/* delete policy in PCB */
1113int
1114ipsec4_delete_pcbpolicy(inp)
1115	struct inpcb *inp;
1116{
1117	KASSERT(inp != NULL, ("ipsec4_delete_pcbpolicy: null inp"));
1118
1119	if (inp->inp_sp == NULL)
1120		return 0;
1121
1122	if (inp->inp_sp->sp_in != NULL)
1123		KEY_FREESP(&inp->inp_sp->sp_in);
1124
1125	if (inp->inp_sp->sp_out != NULL)
1126		KEY_FREESP(&inp->inp_sp->sp_out);
1127
1128	ipsec_delpcbpolicy(inp->inp_sp);
1129	inp->inp_sp = NULL;
1130
1131	return 0;
1132}
1133
1134#ifdef INET6
1135int
1136ipsec6_set_policy(in6p, optname, request, len, priv)
1137	struct in6pcb *in6p;
1138	int optname;
1139	caddr_t request;
1140	size_t len;
1141	int priv;
1142{
1143	struct sadb_x_policy *xpl;
1144	struct secpolicy **pcb_sp;
1145
1146	/* sanity check. */
1147	if (in6p == NULL || request == NULL)
1148		return EINVAL;
1149	if (len < sizeof(*xpl))
1150		return EINVAL;
1151	xpl = (struct sadb_x_policy *)request;
1152
1153	/* select direction */
1154	switch (xpl->sadb_x_policy_dir) {
1155	case IPSEC_DIR_INBOUND:
1156		pcb_sp = &in6p->in6p_sp->sp_in;
1157		break;
1158	case IPSEC_DIR_OUTBOUND:
1159		pcb_sp = &in6p->in6p_sp->sp_out;
1160		break;
1161	default:
1162		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1163			xpl->sadb_x_policy_dir));
1164		return EINVAL;
1165	}
1166
1167	return ipsec_set_policy(pcb_sp, optname, request, len, priv);
1168}
1169
1170int
1171ipsec6_get_policy(in6p, request, len, mp)
1172	struct in6pcb *in6p;
1173	caddr_t request;
1174	size_t len;
1175	struct mbuf **mp;
1176{
1177	struct sadb_x_policy *xpl;
1178	struct secpolicy *pcb_sp;
1179
1180	/* sanity check. */
1181	if (in6p == NULL || request == NULL || mp == NULL)
1182		return EINVAL;
1183	KASSERT(in6p->in6p_sp != NULL, ("ipsec6_get_policy: null in6p_sp"));
1184	if (len < sizeof(*xpl))
1185		return EINVAL;
1186	xpl = (struct sadb_x_policy *)request;
1187
1188	/* select direction */
1189	switch (xpl->sadb_x_policy_dir) {
1190	case IPSEC_DIR_INBOUND:
1191		pcb_sp = in6p->in6p_sp->sp_in;
1192		break;
1193	case IPSEC_DIR_OUTBOUND:
1194		pcb_sp = in6p->in6p_sp->sp_out;
1195		break;
1196	default:
1197		ipseclog((LOG_ERR, "ipsec6_set_policy: invalid direction=%u\n",
1198			xpl->sadb_x_policy_dir));
1199		return EINVAL;
1200	}
1201
1202	return ipsec_get_policy(pcb_sp, mp);
1203}
1204
1205int
1206ipsec6_delete_pcbpolicy(in6p)
1207	struct in6pcb *in6p;
1208{
1209	KASSERT(in6p != NULL, ("ipsec6_delete_pcbpolicy: null in6p"));
1210
1211	if (in6p->in6p_sp == NULL)
1212		return 0;
1213
1214	if (in6p->in6p_sp->sp_in != NULL)
1215		KEY_FREESP(&in6p->in6p_sp->sp_in);
1216
1217	if (in6p->in6p_sp->sp_out != NULL)
1218		KEY_FREESP(&in6p->in6p_sp->sp_out);
1219
1220	ipsec_delpcbpolicy(in6p->in6p_sp);
1221	in6p->in6p_sp = NULL;
1222
1223	return 0;
1224}
1225#endif
1226
1227/*
1228 * return current level.
1229 * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1230 */
1231u_int
1232ipsec_get_reqlevel(isr)
1233	struct ipsecrequest *isr;
1234{
1235	u_int level = 0;
1236	u_int esp_trans_deflev, esp_net_deflev;
1237	u_int ah_trans_deflev, ah_net_deflev;
1238
1239	KASSERT(isr != NULL && isr->sp != NULL,
1240		("ipsec_get_reqlevel: null argument"));
1241	KASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1242		("ipsec_get_reqlevel: af family mismatch, src %u, dst %u",
1243		 isr->sp->spidx.src.sa.sa_family,
1244		 isr->sp->spidx.dst.sa.sa_family));
1245
1246/* XXX note that we have ipseclog() expanded here - code sync issue */
1247#define IPSEC_CHECK_DEFAULT(lev) \
1248	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE	      \
1249			&& (lev) != IPSEC_LEVEL_UNIQUE)			      \
1250		? (ipsec_debug						      \
1251			? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
1252				(lev), IPSEC_LEVEL_REQUIRE)		      \
1253			: 0),						      \
1254			(lev) = IPSEC_LEVEL_REQUIRE,			      \
1255			(lev)						      \
1256		: (lev))
1257
1258	/* set default level */
1259	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1260#ifdef INET
1261	case AF_INET:
1262		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_trans_deflev);
1263		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip4_esp_net_deflev);
1264		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_trans_deflev);
1265		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip4_ah_net_deflev);
1266		break;
1267#endif
1268#ifdef INET6
1269	case AF_INET6:
1270		esp_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_trans_deflev);
1271		esp_net_deflev = IPSEC_CHECK_DEFAULT(ip6_esp_net_deflev);
1272		ah_trans_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_trans_deflev);
1273		ah_net_deflev = IPSEC_CHECK_DEFAULT(ip6_ah_net_deflev);
1274		break;
1275#endif /* INET6 */
1276	default:
1277		panic("key_get_reqlevel: unknown af %u",
1278			isr->sp->spidx.src.sa.sa_family);
1279	}
1280
1281#undef IPSEC_CHECK_DEFAULT
1282
1283	/* set level */
1284	switch (isr->level) {
1285	case IPSEC_LEVEL_DEFAULT:
1286		switch (isr->saidx.proto) {
1287		case IPPROTO_ESP:
1288			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1289				level = esp_net_deflev;
1290			else
1291				level = esp_trans_deflev;
1292			break;
1293		case IPPROTO_AH:
1294			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1295				level = ah_net_deflev;
1296			else
1297				level = ah_trans_deflev;
1298		case IPPROTO_IPCOMP:
1299			/*
1300			 * we don't really care, as IPcomp document says that
1301			 * we shouldn't compress small packets
1302			 */
1303			level = IPSEC_LEVEL_USE;
1304			break;
1305		default:
1306			panic("ipsec_get_reqlevel: "
1307				"Illegal protocol defined %u\n",
1308				isr->saidx.proto);
1309		}
1310		break;
1311
1312	case IPSEC_LEVEL_USE:
1313	case IPSEC_LEVEL_REQUIRE:
1314		level = isr->level;
1315		break;
1316	case IPSEC_LEVEL_UNIQUE:
1317		level = IPSEC_LEVEL_REQUIRE;
1318		break;
1319
1320	default:
1321		panic("ipsec_get_reqlevel: Illegal IPsec level %u\n",
1322			isr->level);
1323	}
1324
1325	return level;
1326}
1327
1328/*
1329 * Check security policy requirements against the actual
1330 * packet contents.  Return one if the packet should be
1331 * reject as "invalid"; otherwiser return zero to have the
1332 * packet treated as "valid".
1333 *
1334 * OUT:
1335 *	0: valid
1336 *	1: invalid
1337 */
1338int
1339ipsec_in_reject(struct secpolicy *sp, struct mbuf *m)
1340{
1341	struct ipsecrequest *isr;
1342	int need_auth;
1343
1344	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1345		printf("ipsec_in_reject: using SP\n");
1346		kdebug_secpolicy(sp));
1347
1348	/* check policy */
1349	switch (sp->policy) {
1350	case IPSEC_POLICY_DISCARD:
1351		return 1;
1352	case IPSEC_POLICY_BYPASS:
1353	case IPSEC_POLICY_NONE:
1354		return 0;
1355	}
1356
1357	KASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1358		("ipsec_in_reject: invalid policy %u", sp->policy));
1359
1360	/* XXX should compare policy against ipsec header history */
1361
1362	need_auth = 0;
1363	for (isr = sp->req; isr != NULL; isr = isr->next) {
1364		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1365			continue;
1366		switch (isr->saidx.proto) {
1367		case IPPROTO_ESP:
1368			if ((m->m_flags & M_DECRYPTED) == 0) {
1369				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1370				    printf("ipsec_in_reject: ESP m_flags:%x\n",
1371					    m->m_flags));
1372				return 1;
1373			}
1374
1375			if (!need_auth &&
1376			    isr->sav != NULL &&
1377			    isr->sav->tdb_authalgxform != NULL &&
1378			    (m->m_flags & M_AUTHIPDGM) == 0) {
1379				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1380				    printf("ipsec_in_reject: ESP/AH m_flags:%x\n",
1381					    m->m_flags));
1382				return 1;
1383			}
1384			break;
1385		case IPPROTO_AH:
1386			need_auth = 1;
1387			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1388				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1389				    printf("ipsec_in_reject: AH m_flags:%x\n",
1390					    m->m_flags));
1391				return 1;
1392			}
1393			break;
1394		case IPPROTO_IPCOMP:
1395			/*
1396			 * we don't really care, as IPcomp document
1397			 * says that we shouldn't compress small
1398			 * packets, IPComp policy should always be
1399			 * treated as being in "use" level.
1400			 */
1401			break;
1402		}
1403	}
1404	return 0;		/* valid */
1405}
1406
1407/*
1408 * Check AH/ESP integrity.
1409 * This function is called from tcp_input(), udp_input(),
1410 * and {ah,esp}4_input for tunnel mode
1411 */
1412int
1413ipsec4_in_reject(m, inp)
1414	struct mbuf *m;
1415	struct inpcb *inp;
1416{
1417	struct secpolicy *sp;
1418	int error;
1419	int result;
1420
1421	KASSERT(m != NULL, ("ipsec4_in_reject_so: null mbuf"));
1422
1423	/* get SP for this packet.
1424	 * When we are called from ip_forward(), we call
1425	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1426	 */
1427	if (inp == NULL)
1428		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1429	else
1430		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1431
1432	if (sp != NULL) {
1433		result = ipsec_in_reject(sp, m);
1434		if (result)
1435			newipsecstat.ips_in_polvio++;
1436		KEY_FREESP(&sp);
1437	} else {
1438		result = 0;	/* XXX should be panic ?
1439				 * -> No, there may be error. */
1440	}
1441	return result;
1442}
1443
1444#ifdef INET6
1445/*
1446 * Check AH/ESP integrity.
1447 * This function is called from tcp6_input(), udp6_input(),
1448 * and {ah,esp}6_input for tunnel mode
1449 */
1450int
1451ipsec6_in_reject(m, inp)
1452	struct mbuf *m;
1453	struct inpcb *inp;
1454{
1455	struct secpolicy *sp = NULL;
1456	int error;
1457	int result;
1458
1459	/* sanity check */
1460	if (m == NULL)
1461		return 0;	/* XXX should be panic ? */
1462
1463	/* get SP for this packet.
1464	 * When we are called from ip_forward(), we call
1465	 * ipsec_getpolicybyaddr() with IP_FORWARDING flag.
1466	 */
1467	if (inp == NULL)
1468		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, IP_FORWARDING, &error);
1469	else
1470		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1471
1472	if (sp != NULL) {
1473		result = ipsec_in_reject(sp, m);
1474		if (result)
1475			newipsecstat.ips_in_polvio++;
1476		KEY_FREESP(&sp);
1477	} else {
1478		result = 0;
1479	}
1480	return result;
1481}
1482#endif
1483
1484/*
1485 * compute the byte size to be occupied by IPsec header.
1486 * in case it is tunneled, it includes the size of outer IP header.
1487 * NOTE: SP passed is free in this function.
1488 */
1489static size_t
1490ipsec_hdrsiz(struct secpolicy *sp)
1491{
1492	struct ipsecrequest *isr;
1493	size_t siz;
1494
1495	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1496		printf("ipsec_hdrsiz: using SP\n");
1497		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	KASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1507		("ipsec_hdrsiz: 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, "ipsec_hdrsiz: "
1537				    "unknown AF %d in IPsec tunnel SA\n",
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	KASSERT(m != NULL, ("ipsec4_hdrsiz: 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("ipsec4_hdrsiz: size:%lu.\n",
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	KASSERT(m != NULL, ("ipsec6_hdrsiz: null mbuf"));
1598	KASSERT(in6p == NULL || in6p->in6p_socket != NULL,
1599		("ipsec6_hdrsize: 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("ipsec6_hdrsiz: size:%lu.\n", (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#if 0
1641	SPLASSERT(net, "ipsec_chkreplay");
1642#endif
1643
1644	KASSERT(sav != NULL, ("ipsec_chkreplay: Null SA"));
1645	KASSERT(sav->replay != NULL, ("ipsec_chkreplay: Null replay state"));
1646
1647	replay = sav->replay;
1648
1649	if (replay->wsize == 0)
1650		return 1;	/* no need to check replay. */
1651
1652	/* constant */
1653	frlast = replay->wsize - 1;
1654	wsizeb = replay->wsize << 3;
1655
1656	/* sequence number of 0 is invalid */
1657	if (seq == 0)
1658		return 0;
1659
1660	/* first time is always okay */
1661	if (replay->count == 0)
1662		return 1;
1663
1664	if (seq > replay->lastseq) {
1665		/* larger sequences are okay */
1666		return 1;
1667	} else {
1668		/* seq is equal or less than lastseq. */
1669		diff = replay->lastseq - seq;
1670
1671		/* over range to check, i.e. too old or wrapped */
1672		if (diff >= wsizeb)
1673			return 0;
1674
1675		fr = frlast - diff / 8;
1676
1677		/* this packet already seen ? */
1678		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1679			return 0;
1680
1681		/* out of order but good */
1682		return 1;
1683	}
1684}
1685
1686/*
1687 * check replay counter whether to update or not.
1688 * OUT:	0:	OK
1689 *	1:	NG
1690 */
1691int
1692ipsec_updatereplay(seq, sav)
1693	u_int32_t seq;
1694	struct secasvar *sav;
1695{
1696	struct secreplay *replay;
1697	u_int32_t diff;
1698	int fr;
1699	u_int32_t wsizeb;	/* constant: bits of window size */
1700	int frlast;		/* constant: last frame */
1701
1702#if 0
1703	SPLASSERT(net, "ipsec_updatereplay");
1704#endif
1705
1706	KASSERT(sav != NULL, ("ipsec_updatereplay: Null SA"));
1707	KASSERT(sav->replay != NULL, ("ipsec_updatereplay: Null replay state"));
1708
1709	replay = sav->replay;
1710
1711	if (replay->wsize == 0)
1712		goto ok;	/* no need to check replay. */
1713
1714	/* constant */
1715	frlast = replay->wsize - 1;
1716	wsizeb = replay->wsize << 3;
1717
1718	/* sequence number of 0 is invalid */
1719	if (seq == 0)
1720		return 1;
1721
1722	/* first time */
1723	if (replay->count == 0) {
1724		replay->lastseq = seq;
1725		bzero(replay->bitmap, replay->wsize);
1726		(replay->bitmap)[frlast] = 1;
1727		goto ok;
1728	}
1729
1730	if (seq > replay->lastseq) {
1731		/* seq is larger than lastseq. */
1732		diff = seq - replay->lastseq;
1733
1734		/* new larger sequence number */
1735		if (diff < wsizeb) {
1736			/* In window */
1737			/* set bit for this packet */
1738			vshiftl(replay->bitmap, diff, replay->wsize);
1739			(replay->bitmap)[frlast] |= 1;
1740		} else {
1741			/* this packet has a "way larger" */
1742			bzero(replay->bitmap, replay->wsize);
1743			(replay->bitmap)[frlast] = 1;
1744		}
1745		replay->lastseq = seq;
1746
1747		/* larger is good */
1748	} else {
1749		/* seq is equal or less than lastseq. */
1750		diff = replay->lastseq - seq;
1751
1752		/* over range to check, i.e. too old or wrapped */
1753		if (diff >= wsizeb)
1754			return 1;
1755
1756		fr = frlast - diff / 8;
1757
1758		/* this packet already seen ? */
1759		if ((replay->bitmap)[fr] & (1 << (diff % 8)))
1760			return 1;
1761
1762		/* mark as seen */
1763		(replay->bitmap)[fr] |= (1 << (diff % 8));
1764
1765		/* out of order but good */
1766	}
1767
1768ok:
1769	if (replay->count == ~0) {
1770
1771		/* set overflow flag */
1772		replay->overflow++;
1773
1774		/* don't increment, no more packets accepted */
1775		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
1776			return 1;
1777
1778		ipseclog((LOG_WARNING, "replay counter made %d cycle. %s\n",
1779		    replay->overflow, ipsec_logsastr(sav)));
1780	}
1781
1782	replay->count++;
1783
1784	return 0;
1785}
1786
1787/*
1788 * shift variable length bunffer to left.
1789 * IN:	bitmap: pointer to the buffer
1790 * 	nbit:	the number of to shift.
1791 *	wsize:	buffer size (bytes).
1792 */
1793static void
1794vshiftl(bitmap, nbit, wsize)
1795	unsigned char *bitmap;
1796	int nbit, wsize;
1797{
1798	int s, j, i;
1799	unsigned char over;
1800
1801	for (j = 0; j < nbit; j += 8) {
1802		s = (nbit - j < 8) ? (nbit - j): 8;
1803		bitmap[0] <<= s;
1804		for (i = 1; i < wsize; i++) {
1805			over = (bitmap[i] >> (8 - s));
1806			bitmap[i] <<= s;
1807			bitmap[i-1] |= over;
1808		}
1809	}
1810
1811	return;
1812}
1813
1814/* Return a printable string for the IPv4 address. */
1815static char *
1816inet_ntoa4(struct in_addr ina)
1817{
1818	static char buf[4][4 * sizeof "123" + 4];
1819	unsigned char *ucp = (unsigned char *) &ina;
1820	static int i = 3;
1821
1822	i = (i + 1) % 4;
1823	sprintf(buf[i], "%d.%d.%d.%d", ucp[0] & 0xff, ucp[1] & 0xff,
1824	    ucp[2] & 0xff, ucp[3] & 0xff);
1825	return (buf[i]);
1826}
1827
1828/* Return a printable string for the address. */
1829char *
1830ipsec_address(union sockaddr_union* sa)
1831{
1832	switch (sa->sa.sa_family) {
1833#if INET
1834	case AF_INET:
1835		return inet_ntoa4(sa->sin.sin_addr);
1836#endif /* INET */
1837
1838#if INET6
1839	case AF_INET6:
1840		return ip6_sprintf(&sa->sin6.sin6_addr);
1841#endif /* INET6 */
1842
1843	default:
1844		return "(unknown address family)";
1845	}
1846}
1847
1848const char *
1849ipsec_logsastr(sav)
1850	struct secasvar *sav;
1851{
1852	static char buf[256];
1853	char *p;
1854	struct secasindex *saidx = &sav->sah->saidx;
1855
1856	KASSERT(saidx->src.sa.sa_family == saidx->dst.sa.sa_family,
1857		("ipsec_logsastr: address family mismatch"));
1858
1859	p = buf;
1860	snprintf(buf, sizeof(buf), "SA(SPI=%u ", (u_int32_t)ntohl(sav->spi));
1861	while (p && *p)
1862		p++;
1863	/* NB: only use ipsec_address on one address at a time */
1864	snprintf(p, sizeof (buf) - (p - buf), "src=%s ",
1865		ipsec_address(&saidx->src));
1866	while (p && *p)
1867		p++;
1868	snprintf(p, sizeof (buf) - (p - buf), "dst=%s)",
1869		ipsec_address(&saidx->dst));
1870
1871	return buf;
1872}
1873
1874void
1875ipsec_dumpmbuf(m)
1876	struct mbuf *m;
1877{
1878	int totlen;
1879	int i;
1880	u_char *p;
1881
1882	totlen = 0;
1883	printf("---\n");
1884	while (m) {
1885		p = mtod(m, u_char *);
1886		for (i = 0; i < m->m_len; i++) {
1887			printf("%02x ", p[i]);
1888			totlen++;
1889			if (totlen % 16 == 0)
1890				printf("\n");
1891		}
1892		m = m->m_next;
1893	}
1894	if (totlen % 16 != 0)
1895		printf("\n");
1896	printf("---\n");
1897}
1898
1899/* XXX this stuff doesn't belong here... */
1900
1901static	struct xformsw* xforms = NULL;
1902
1903/*
1904 * Register a transform; typically at system startup.
1905 */
1906void
1907xform_register(struct xformsw* xsp)
1908{
1909	xsp->xf_next = xforms;
1910	xforms = xsp;
1911}
1912
1913/*
1914 * Initialize transform support in an sav.
1915 */
1916int
1917xform_init(struct secasvar *sav, int xftype)
1918{
1919	struct xformsw *xsp;
1920
1921	for (xsp = xforms; xsp; xsp = xsp->xf_next)
1922		if (xsp->xf_type == xftype)
1923			return (*xsp->xf_init)(sav, xsp);
1924	return EINVAL;
1925}
1926