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