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