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