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