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