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