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