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