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