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