xref: /freebsd/sys/netipsec/ipsec.c (revision 7f9dff23d3092aa33ad45b2b63e52469b3c13a6e)
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 *, const struct mbuf *);
244 static int ipsec_setspidx_inpcb(const struct mbuf *, struct inpcb *);
245 static int ipsec_setspidx(const struct mbuf *, struct secpolicyindex *, int);
246 static void ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
247 static int ipsec4_setspidx_ipaddr(const struct mbuf *, struct secpolicyindex *);
248 #ifdef INET6
249 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
250 static int ipsec6_setspidx_ipaddr(const struct mbuf *, struct secpolicyindex *);
251 #endif
252 static void ipsec_delpcbpolicy(struct inpcbpolicy *);
253 static struct secpolicy *ipsec_deepcopy_policy(struct secpolicy *src);
254 
255 MALLOC_DEFINE(M_IPSEC_INPCB, "inpcbpolicy", "inpcb-resident ipsec policy");
256 
257 /*
258  * Return a held reference to the default SP.
259  */
260 static struct secpolicy *
261 key_allocsp_default(const char* where, int tag)
262 {
263 	struct secpolicy *sp;
264 
265 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
266 		printf("DP key_allocsp_default from %s:%u\n", where, tag));
267 
268 	sp = &V_def_policy;
269 	if (sp->policy != IPSEC_POLICY_DISCARD &&
270 	    sp->policy != IPSEC_POLICY_NONE) {
271 		ipseclog((LOG_INFO, "fixed system default policy: %d->%d\n",
272 		    sp->policy, IPSEC_POLICY_NONE));
273 		sp->policy = IPSEC_POLICY_NONE;
274 	}
275 	key_addref(sp);
276 
277 	KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
278 		printf("DP key_allocsp_default returns SP:%p (%u)\n",
279 			sp, sp->refcnt));
280 	return (sp);
281 }
282 #define	KEY_ALLOCSP_DEFAULT() \
283 	key_allocsp_default(__FILE__, __LINE__)
284 
285 /*
286  * For OUTBOUND packet having a socket. Searching SPD for packet,
287  * and return a pointer to SP.
288  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
289  *		0	: bypass
290  *		EACCES	: discard packet.
291  *		ENOENT	: ipsec_acquire() in progress, maybe.
292  *		others	: error occurred.
293  *	others:	a pointer to SP
294  *
295  * NOTE: IPv6 mapped adddress concern is implemented here.
296  */
297 struct secpolicy *
298 ipsec_getpolicy(struct tdb_ident *tdbi, u_int dir)
299 {
300 	struct secpolicy *sp;
301 
302 	IPSEC_ASSERT(tdbi != NULL, ("null tdbi"));
303 	IPSEC_ASSERT(dir == IPSEC_DIR_INBOUND || dir == IPSEC_DIR_OUTBOUND,
304 		("invalid direction %u", dir));
305 
306 	sp = KEY_ALLOCSP2(tdbi->spi, &tdbi->dst, tdbi->proto, dir);
307 	if (sp == NULL)			/*XXX????*/
308 		sp = KEY_ALLOCSP_DEFAULT();
309 	IPSEC_ASSERT(sp != NULL, ("null SP"));
310 	return (sp);
311 }
312 
313 /*
314  * For OUTBOUND packet having a socket. Searching SPD for packet,
315  * and return a pointer to SP.
316  * OUT:	NULL:	no apropreate SP found, the following value is set to error.
317  *		0	: bypass
318  *		EACCES	: discard packet.
319  *		ENOENT	: ipsec_acquire() in progress, maybe.
320  *		others	: error occurred.
321  *	others:	a pointer to SP
322  *
323  * NOTE: IPv6 mapped adddress concern is implemented here.
324  */
325 static struct secpolicy *
326 ipsec_getpolicybysock(const struct mbuf *m, u_int dir, struct inpcb *inp,
327     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 occurred.
428  */
429 struct secpolicy *
430 ipsec_getpolicybyaddr(const 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(const struct mbuf *m, u_int dir, int *error,
461     struct inpcb *inp)
462 {
463 	struct secpolicy *sp;
464 
465 	*error = 0;
466 	if (inp == NULL)
467 		sp = ipsec_getpolicybyaddr(m, dir, error);
468 	else
469 		sp = ipsec_getpolicybysock(m, dir, inp, error);
470 	if (sp == NULL) {
471 		IPSEC_ASSERT(*error != 0, ("getpolicy failed w/o error"));
472 		IPSECSTAT_INC(ips_out_inval);
473 		return (NULL);
474 	}
475 	IPSEC_ASSERT(*error == 0, ("sp w/ error set to %u", *error));
476 	switch (sp->policy) {
477 	case IPSEC_POLICY_ENTRUST:
478 	default:
479 		printf("%s: invalid policy %u\n", __func__, sp->policy);
480 		/* FALLTHROUGH */
481 	case IPSEC_POLICY_DISCARD:
482 		IPSECSTAT_INC(ips_out_polvio);
483 		*error = -EINVAL;	/* Packet is discarded by caller. */
484 		break;
485 	case IPSEC_POLICY_BYPASS:
486 	case IPSEC_POLICY_NONE:
487 		KEY_FREESP(&sp);
488 		sp = NULL;		/* NB: force NULL result. */
489 		break;
490 	case IPSEC_POLICY_IPSEC:
491 		if (sp->req == NULL)	/* Acquire a SA. */
492 			*error = key_spdacquire(sp);
493 		break;
494 	}
495 	if (*error != 0) {
496 		KEY_FREESP(&sp);
497 		sp = NULL;
498 	}
499 	return (sp);
500 }
501 
502 static int
503 ipsec_setspidx_inpcb(const struct mbuf *m, struct inpcb *inp)
504 {
505 	int error;
506 
507 	IPSEC_ASSERT(inp != NULL, ("null inp"));
508 	IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp"));
509 	IPSEC_ASSERT(inp->inp_sp->sp_out != NULL && inp->inp_sp->sp_in != NULL,
510 		("null sp_in || sp_out"));
511 
512 	error = ipsec_setspidx(m, &inp->inp_sp->sp_in->spidx, 1);
513 	if (error == 0) {
514 		inp->inp_sp->sp_in->spidx.dir = IPSEC_DIR_INBOUND;
515 		inp->inp_sp->sp_out->spidx = inp->inp_sp->sp_in->spidx;
516 		inp->inp_sp->sp_out->spidx.dir = IPSEC_DIR_OUTBOUND;
517 	} else {
518 		bzero(&inp->inp_sp->sp_in->spidx,
519 			sizeof (inp->inp_sp->sp_in->spidx));
520 		bzero(&inp->inp_sp->sp_out->spidx,
521 			sizeof (inp->inp_sp->sp_in->spidx));
522 	}
523 	return (error);
524 }
525 
526 /*
527  * Configure security policy index (src/dst/proto/sport/dport)
528  * by looking at the content of mbuf.
529  * The caller is responsible for error recovery (like clearing up spidx).
530  */
531 static int
532 ipsec_setspidx(const struct mbuf *m, struct secpolicyindex *spidx,
533     int needport)
534 {
535 	struct ip ipbuf;
536 	const struct ip *ip = NULL;
537 	const struct mbuf *n;
538 	u_int v;
539 	int len;
540 	int error;
541 
542 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
543 
544 	/*
545 	 * Validate m->m_pkthdr.len.  We see incorrect length if we
546 	 * mistakenly call this function with inconsistent mbuf chain
547 	 * (like 4.4BSD tcp/udp processing).  XXX Should we panic here?
548 	 */
549 	len = 0;
550 	for (n = m; n; n = n->m_next)
551 		len += n->m_len;
552 	if (m->m_pkthdr.len != len) {
553 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
554 			printf("%s: pkthdr len(%d) mismatch (%d), ignored.\n",
555 				__func__, len, m->m_pkthdr.len));
556 		return (EINVAL);
557 	}
558 
559 	if (m->m_pkthdr.len < sizeof(struct ip)) {
560 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
561 			printf("%s: pkthdr len(%d) too small (v4), ignored.\n",
562 			    __func__, m->m_pkthdr.len));
563 		return (EINVAL);
564 	}
565 
566 	if (m->m_len >= sizeof(*ip))
567 		ip = mtod(m, const struct ip *);
568 	else {
569 		m_copydata(m, 0, sizeof(ipbuf), (caddr_t)&ipbuf);
570 		ip = &ipbuf;
571 	}
572 	v = ip->ip_v;
573 	switch (v) {
574 	case 4:
575 		error = ipsec4_setspidx_ipaddr(m, spidx);
576 		if (error)
577 			return (error);
578 		ipsec4_get_ulp(m, spidx, needport);
579 		return (0);
580 #ifdef INET6
581 	case 6:
582 		if (m->m_pkthdr.len < sizeof(struct ip6_hdr)) {
583 			KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
584 				printf("%s: pkthdr len(%d) too small (v6), "
585 				"ignored\n", __func__, m->m_pkthdr.len));
586 			return (EINVAL);
587 		}
588 		error = ipsec6_setspidx_ipaddr(m, spidx);
589 		if (error)
590 			return (error);
591 		ipsec6_get_ulp(m, spidx, needport);
592 		return (0);
593 #endif
594 	default:
595 		KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
596 			printf("%s: " "unknown IP version %u, ignored.\n",
597 				__func__, v));
598 		return (EINVAL);
599 	}
600 }
601 
602 static void
603 ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
604     int needport)
605 {
606 	u_int8_t nxt;
607 	int off;
608 
609 	/* Sanity check. */
610 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
611 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),("packet too short"));
612 
613 	if (m->m_len >= sizeof (struct ip)) {
614 		const struct ip *ip = mtod(m, const struct ip *);
615 		if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
616 			goto done;
617 		off = ip->ip_hl << 2;
618 		nxt = ip->ip_p;
619 	} else {
620 		struct ip ih;
621 
622 		m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
623 		if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
624 			goto done;
625 		off = ih.ip_hl << 2;
626 		nxt = ih.ip_p;
627 	}
628 
629 	while (off < m->m_pkthdr.len) {
630 		struct ip6_ext ip6e;
631 		struct tcphdr th;
632 		struct udphdr uh;
633 
634 		switch (nxt) {
635 		case IPPROTO_TCP:
636 			spidx->ul_proto = nxt;
637 			if (!needport)
638 				goto done_proto;
639 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
640 				goto done;
641 			m_copydata(m, off, sizeof (th), (caddr_t) &th);
642 			spidx->src.sin.sin_port = th.th_sport;
643 			spidx->dst.sin.sin_port = th.th_dport;
644 			return;
645 		case IPPROTO_UDP:
646 			spidx->ul_proto = nxt;
647 			if (!needport)
648 				goto done_proto;
649 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
650 				goto done;
651 			m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
652 			spidx->src.sin.sin_port = uh.uh_sport;
653 			spidx->dst.sin.sin_port = uh.uh_dport;
654 			return;
655 		case IPPROTO_AH:
656 			if (off + sizeof(ip6e) > m->m_pkthdr.len)
657 				goto done;
658 			/* XXX Sigh, this works but is totally bogus. */
659 			m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
660 			off += (ip6e.ip6e_len + 2) << 2;
661 			nxt = ip6e.ip6e_nxt;
662 			break;
663 		case IPPROTO_ICMP:
664 		default:
665 			/* XXX Intermediate headers??? */
666 			spidx->ul_proto = nxt;
667 			goto done_proto;
668 		}
669 	}
670 done:
671 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
672 done_proto:
673 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
674 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
675 }
676 
677 /* Assumes that m is sane. */
678 static int
679 ipsec4_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
680 {
681 	static const struct sockaddr_in template = {
682 		sizeof (struct sockaddr_in),
683 		AF_INET,
684 		0, { 0 }, { 0, 0, 0, 0, 0, 0, 0, 0 }
685 	};
686 
687 	spidx->src.sin = template;
688 	spidx->dst.sin = template;
689 
690 	if (m->m_len < sizeof (struct ip)) {
691 		m_copydata(m, offsetof(struct ip, ip_src),
692 			   sizeof (struct  in_addr),
693 			   (caddr_t) &spidx->src.sin.sin_addr);
694 		m_copydata(m, offsetof(struct ip, ip_dst),
695 			   sizeof (struct  in_addr),
696 			   (caddr_t) &spidx->dst.sin.sin_addr);
697 	} else {
698 		const struct ip *ip = mtod(m, const struct ip *);
699 		spidx->src.sin.sin_addr = ip->ip_src;
700 		spidx->dst.sin.sin_addr = ip->ip_dst;
701 	}
702 
703 	spidx->prefs = sizeof(struct in_addr) << 3;
704 	spidx->prefd = sizeof(struct in_addr) << 3;
705 
706 	return (0);
707 }
708 
709 #ifdef INET6
710 static void
711 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
712     int needport)
713 {
714 	int off, nxt;
715 	struct tcphdr th;
716 	struct udphdr uh;
717 	struct icmp6_hdr ih;
718 
719 	/* Sanity check. */
720 	if (m == NULL)
721 		panic("%s: NULL pointer was passed.\n", __func__);
722 
723 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
724 		printf("%s:\n", __func__); kdebug_mbuf(m));
725 
726 	/* Set default. */
727 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
728 	((struct sockaddr_in6 *)&spidx->src)->sin6_port = IPSEC_PORT_ANY;
729 	((struct sockaddr_in6 *)&spidx->dst)->sin6_port = IPSEC_PORT_ANY;
730 
731 	nxt = -1;
732 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
733 	if (off < 0 || m->m_pkthdr.len < off)
734 		return;
735 
736 	switch (nxt) {
737 	case IPPROTO_TCP:
738 		spidx->ul_proto = nxt;
739 		if (!needport)
740 			break;
741 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
742 			break;
743 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
744 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = th.th_sport;
745 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = th.th_dport;
746 		break;
747 	case IPPROTO_UDP:
748 		spidx->ul_proto = nxt;
749 		if (!needport)
750 			break;
751 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
752 			break;
753 		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
754 		((struct sockaddr_in6 *)&spidx->src)->sin6_port = uh.uh_sport;
755 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port = uh.uh_dport;
756 		break;
757 	case IPPROTO_ICMPV6:
758 		spidx->ul_proto = nxt;
759 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
760 			break;
761 		m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
762 		((struct sockaddr_in6 *)&spidx->src)->sin6_port =
763 		    htons((uint16_t)ih.icmp6_type);
764 		((struct sockaddr_in6 *)&spidx->dst)->sin6_port =
765 		    htons((uint16_t)ih.icmp6_code);
766 		break;
767 	default:
768 		/* XXX Intermediate headers??? */
769 		spidx->ul_proto = nxt;
770 		break;
771 	}
772 }
773 
774 /* Assumes that m is sane. */
775 static int
776 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
777 {
778 	struct ip6_hdr ip6buf;
779 	const struct ip6_hdr *ip6 = NULL;
780 	struct sockaddr_in6 *sin6;
781 
782 	if (m->m_len >= sizeof(*ip6))
783 		ip6 = mtod(m, const struct ip6_hdr *);
784 	else {
785 		m_copydata(m, 0, sizeof(ip6buf), (caddr_t)&ip6buf);
786 		ip6 = &ip6buf;
787 	}
788 
789 	sin6 = (struct sockaddr_in6 *)&spidx->src;
790 	bzero(sin6, sizeof(*sin6));
791 	sin6->sin6_family = AF_INET6;
792 	sin6->sin6_len = sizeof(struct sockaddr_in6);
793 	bcopy(&ip6->ip6_src, &sin6->sin6_addr, sizeof(ip6->ip6_src));
794 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
795 		sin6->sin6_addr.s6_addr16[1] = 0;
796 		sin6->sin6_scope_id = ntohs(ip6->ip6_src.s6_addr16[1]);
797 	}
798 	spidx->prefs = sizeof(struct in6_addr) << 3;
799 
800 	sin6 = (struct sockaddr_in6 *)&spidx->dst;
801 	bzero(sin6, sizeof(*sin6));
802 	sin6->sin6_family = AF_INET6;
803 	sin6->sin6_len = sizeof(struct sockaddr_in6);
804 	bcopy(&ip6->ip6_dst, &sin6->sin6_addr, sizeof(ip6->ip6_dst));
805 	if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
806 		sin6->sin6_addr.s6_addr16[1] = 0;
807 		sin6->sin6_scope_id = ntohs(ip6->ip6_dst.s6_addr16[1]);
808 	}
809 	spidx->prefd = sizeof(struct in6_addr) << 3;
810 
811 	return (0);
812 }
813 #endif
814 
815 int
816 ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
817 {
818 	int idx;
819 
820 	switch (ctx->af) {
821 #ifdef INET
822 	case AF_INET:
823 		idx = HHOOK_IPSEC_INET;
824 		break;
825 #endif
826 #ifdef INET6
827 	case AF_INET6:
828 		idx = HHOOK_IPSEC_INET6;
829 		break;
830 #endif
831 	default:
832 		return (EPFNOSUPPORT);
833 	}
834 	if (type == HHOOK_TYPE_IPSEC_IN)
835 		HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
836 	else
837 		HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
838 	if (*ctx->mp == NULL)
839 		return (EACCES);
840 	return (0);
841 }
842 
843 static void
844 ipsec_delpcbpolicy(struct inpcbpolicy *p)
845 {
846 
847 	free(p, M_IPSEC_INPCB);
848 }
849 
850 /* Initialize policy in PCB. */
851 int
852 ipsec_init_policy(struct socket *so, struct inpcbpolicy **pcb_sp)
853 {
854 	struct inpcbpolicy *new;
855 
856 	/* Sanity check. */
857 	if (so == NULL || pcb_sp == NULL)
858 		panic("%s: NULL pointer was passed.\n", __func__);
859 
860 	new = (struct inpcbpolicy *) malloc(sizeof(struct inpcbpolicy),
861 					    M_IPSEC_INPCB, M_NOWAIT|M_ZERO);
862 	if (new == NULL) {
863 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
864 		return (ENOBUFS);
865 	}
866 
867 	new->priv = IPSEC_IS_PRIVILEGED_SO(so);
868 
869 	if ((new->sp_in = KEY_NEWSP()) == NULL) {
870 		ipsec_delpcbpolicy(new);
871 		return (ENOBUFS);
872 	}
873 	new->sp_in->policy = IPSEC_POLICY_ENTRUST;
874 	if ((new->sp_out = KEY_NEWSP()) == NULL) {
875 		KEY_FREESP(&new->sp_in);
876 		ipsec_delpcbpolicy(new);
877 		return (ENOBUFS);
878 	}
879 	new->sp_out->policy = IPSEC_POLICY_ENTRUST;
880 	*pcb_sp = new;
881 
882 	return (0);
883 }
884 
885 /* Copy old IPsec policy into new. */
886 int
887 ipsec_copy_policy(struct inpcbpolicy *old, struct inpcbpolicy *new)
888 {
889 	struct secpolicy *sp;
890 
891 	sp = ipsec_deepcopy_policy(old->sp_in);
892 	if (sp) {
893 		KEY_FREESP(&new->sp_in);
894 		new->sp_in = sp;
895 	} else
896 		return (ENOBUFS);
897 
898 	sp = ipsec_deepcopy_policy(old->sp_out);
899 	if (sp) {
900 		KEY_FREESP(&new->sp_out);
901 		new->sp_out = sp;
902 	} else
903 		return (ENOBUFS);
904 
905 	new->priv = old->priv;
906 
907 	return (0);
908 }
909 
910 struct ipsecrequest *
911 ipsec_newisr(void)
912 {
913 	struct ipsecrequest *p;
914 
915 	p = malloc(sizeof(struct ipsecrequest), M_IPSEC_SR, M_NOWAIT|M_ZERO);
916 	if (p != NULL)
917 		IPSECREQUEST_LOCK_INIT(p);
918 	return (p);
919 }
920 
921 void
922 ipsec_delisr(struct ipsecrequest *p)
923 {
924 
925 	IPSECREQUEST_LOCK_DESTROY(p);
926 	free(p, M_IPSEC_SR);
927 }
928 
929 /* Deep-copy a policy in PCB. */
930 static struct secpolicy *
931 ipsec_deepcopy_policy(struct secpolicy *src)
932 {
933 	struct ipsecrequest *newchain = NULL;
934 	struct ipsecrequest *p;
935 	struct ipsecrequest **q;
936 	struct ipsecrequest *r;
937 	struct secpolicy *dst;
938 
939 	if (src == NULL)
940 		return (NULL);
941 	dst = KEY_NEWSP();
942 	if (dst == NULL)
943 		return (NULL);
944 
945 	/*
946 	 * Deep-copy IPsec request chain.  This is required since struct
947 	 * ipsecrequest is not reference counted.
948 	 */
949 	q = &newchain;
950 	for (p = src->req; p; p = p->next) {
951 		*q = ipsec_newisr();
952 		if (*q == NULL)
953 			goto fail;
954 		(*q)->saidx.proto = p->saidx.proto;
955 		(*q)->saidx.mode = p->saidx.mode;
956 		(*q)->level = p->level;
957 		(*q)->saidx.reqid = p->saidx.reqid;
958 
959 		bcopy(&p->saidx.src, &(*q)->saidx.src, sizeof((*q)->saidx.src));
960 		bcopy(&p->saidx.dst, &(*q)->saidx.dst, sizeof((*q)->saidx.dst));
961 
962 		(*q)->sp = dst;
963 
964 		q = &((*q)->next);
965 	}
966 
967 	dst->req = newchain;
968 	dst->policy = src->policy;
969 	/* Do not touch the refcnt fields. */
970 
971 	return (dst);
972 
973 fail:
974 	for (p = newchain; p; p = r) {
975 		r = p->next;
976 		ipsec_delisr(p);
977 		p = NULL;
978 	}
979 	KEY_FREESP(&dst);
980 	return (NULL);
981 }
982 
983 /* Set policy and IPsec request if present. */
984 static int
985 ipsec_set_policy_internal(struct secpolicy **pcb_sp, int optname,
986     caddr_t request, size_t len, struct ucred *cred)
987 {
988 	struct sadb_x_policy *xpl;
989 	struct secpolicy *newsp = NULL;
990 	int error;
991 
992 	/* Sanity check. */
993 	if (pcb_sp == NULL || *pcb_sp == NULL || request == NULL)
994 		return (EINVAL);
995 	if (len < sizeof(*xpl))
996 		return (EINVAL);
997 	xpl = (struct sadb_x_policy *)request;
998 
999 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1000 		printf("%s: passed policy\n", __func__);
1001 		kdebug_sadb_x_policy((struct sadb_ext *)xpl));
1002 
1003 	/* Check policy type. */
1004 	/* ipsec_set_policy_internal() accepts IPSEC, ENTRUST and BYPASS. */
1005 	if (xpl->sadb_x_policy_type == IPSEC_POLICY_DISCARD
1006 	 || xpl->sadb_x_policy_type == IPSEC_POLICY_NONE)
1007 		return (EINVAL);
1008 
1009 	/* Check privileged socket. */
1010 	if (cred != NULL && xpl->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
1011 		error = priv_check_cred(cred, PRIV_NETINET_IPSEC, 0);
1012 		if (error)
1013 			return (EACCES);
1014 	}
1015 
1016 	/* Allocating new SP entry. */
1017 	if ((newsp = key_msg2sp(xpl, len, &error)) == NULL)
1018 		return (error);
1019 
1020 	/* Clear old SP and set new SP. */
1021 	KEY_FREESP(pcb_sp);
1022 	*pcb_sp = newsp;
1023 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1024 		printf("%s: new policy\n", __func__);
1025 		kdebug_secpolicy(newsp));
1026 
1027 	return (0);
1028 }
1029 
1030 int
1031 ipsec_set_policy(struct inpcb *inp, int optname, caddr_t request,
1032     size_t len, struct ucred *cred)
1033 {
1034 	struct sadb_x_policy *xpl;
1035 	struct secpolicy **pcb_sp;
1036 
1037 	/* Sanity check. */
1038 	if (inp == NULL || request == NULL)
1039 		return (EINVAL);
1040 	if (len < sizeof(*xpl))
1041 		return (EINVAL);
1042 	xpl = (struct sadb_x_policy *)request;
1043 
1044 	/* Select direction. */
1045 	switch (xpl->sadb_x_policy_dir) {
1046 	case IPSEC_DIR_INBOUND:
1047 		pcb_sp = &inp->inp_sp->sp_in;
1048 		break;
1049 	case IPSEC_DIR_OUTBOUND:
1050 		pcb_sp = &inp->inp_sp->sp_out;
1051 		break;
1052 	default:
1053 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1054 			xpl->sadb_x_policy_dir));
1055 		return (EINVAL);
1056 	}
1057 
1058 	return (ipsec_set_policy_internal(pcb_sp, optname, request, len, cred));
1059 }
1060 
1061 int
1062 ipsec_get_policy(struct inpcb *inp, caddr_t request, size_t len,
1063     struct mbuf **mp)
1064 {
1065 	struct sadb_x_policy *xpl;
1066 	struct secpolicy *pcb_sp;
1067 
1068 	/* Sanity check. */
1069 	if (inp == NULL || request == NULL || mp == NULL)
1070 		return (EINVAL);
1071 	IPSEC_ASSERT(inp->inp_sp != NULL, ("null inp_sp"));
1072 	if (len < sizeof(*xpl))
1073 		return (EINVAL);
1074 	xpl = (struct sadb_x_policy *)request;
1075 
1076 	/* Select direction. */
1077 	switch (xpl->sadb_x_policy_dir) {
1078 	case IPSEC_DIR_INBOUND:
1079 		pcb_sp = inp->inp_sp->sp_in;
1080 		break;
1081 	case IPSEC_DIR_OUTBOUND:
1082 		pcb_sp = inp->inp_sp->sp_out;
1083 		break;
1084 	default:
1085 		ipseclog((LOG_ERR, "%s: invalid direction=%u\n", __func__,
1086 			xpl->sadb_x_policy_dir));
1087 		return (EINVAL);
1088 	}
1089 
1090 	/* Sanity check. Should be an IPSEC_ASSERT. */
1091 	if (pcb_sp == NULL)
1092 		return (EINVAL);
1093 
1094 	*mp = key_sp2msg(pcb_sp);
1095 	if (!*mp) {
1096 		ipseclog((LOG_DEBUG, "%s: No more memory.\n", __func__));
1097 		return (ENOBUFS);
1098 	}
1099 
1100 	(*mp)->m_type = MT_DATA;
1101 	KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1102 		printf("%s:\n", __func__); kdebug_mbuf(*mp));
1103 
1104 	return (0);
1105 }
1106 
1107 /* Delete policy in PCB. */
1108 int
1109 ipsec_delete_pcbpolicy(struct inpcb *inp)
1110 {
1111 	IPSEC_ASSERT(inp != NULL, ("null inp"));
1112 
1113 	if (inp->inp_sp == NULL)
1114 		return (0);
1115 
1116 	if (inp->inp_sp->sp_in != NULL)
1117 		KEY_FREESP(&inp->inp_sp->sp_in);
1118 
1119 	if (inp->inp_sp->sp_out != NULL)
1120 		KEY_FREESP(&inp->inp_sp->sp_out);
1121 
1122 	ipsec_delpcbpolicy(inp->inp_sp);
1123 	inp->inp_sp = NULL;
1124 
1125 	return (0);
1126 }
1127 
1128 /*
1129  * Return current level.
1130  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
1131  */
1132 u_int
1133 ipsec_get_reqlevel(struct ipsecrequest *isr)
1134 {
1135 	u_int level = 0;
1136 	u_int esp_trans_deflev, esp_net_deflev;
1137 	u_int ah_trans_deflev, ah_net_deflev;
1138 
1139 	IPSEC_ASSERT(isr != NULL && isr->sp != NULL, ("null argument"));
1140 	IPSEC_ASSERT(isr->sp->spidx.src.sa.sa_family == isr->sp->spidx.dst.sa.sa_family,
1141 		("af family mismatch, src %u, dst %u",
1142 		 isr->sp->spidx.src.sa.sa_family,
1143 		 isr->sp->spidx.dst.sa.sa_family));
1144 
1145 /* XXX Note that we have ipseclog() expanded here - code sync issue. */
1146 #define IPSEC_CHECK_DEFAULT(lev) \
1147 	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE	      \
1148 			&& (lev) != IPSEC_LEVEL_UNIQUE)			      \
1149 		? (V_ipsec_debug						      \
1150 			? log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
1151 				(lev), IPSEC_LEVEL_REQUIRE)		      \
1152 			: 0),						      \
1153 			(lev) = IPSEC_LEVEL_REQUIRE,			      \
1154 			(lev)						      \
1155 		: (lev))
1156 
1157 	/* Set default level. */
1158 	switch (((struct sockaddr *)&isr->sp->spidx.src)->sa_family) {
1159 #ifdef INET
1160 	case AF_INET:
1161 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
1162 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
1163 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
1164 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
1165 		break;
1166 #endif
1167 #ifdef INET6
1168 	case AF_INET6:
1169 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
1170 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
1171 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
1172 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
1173 		break;
1174 #endif /* INET6 */
1175 	default:
1176 		panic("%s: unknown af %u",
1177 			__func__, isr->sp->spidx.src.sa.sa_family);
1178 	}
1179 
1180 #undef IPSEC_CHECK_DEFAULT
1181 
1182 	/* Set level. */
1183 	switch (isr->level) {
1184 	case IPSEC_LEVEL_DEFAULT:
1185 		switch (isr->saidx.proto) {
1186 		case IPPROTO_ESP:
1187 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1188 				level = esp_net_deflev;
1189 			else
1190 				level = esp_trans_deflev;
1191 			break;
1192 		case IPPROTO_AH:
1193 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
1194 				level = ah_net_deflev;
1195 			else
1196 				level = ah_trans_deflev;
1197 			break;
1198 		case IPPROTO_IPCOMP:
1199 			/*
1200 			 * We don't really care, as IPcomp document says that
1201 			 * we shouldn't compress small packets.
1202 			 */
1203 			level = IPSEC_LEVEL_USE;
1204 			break;
1205 		default:
1206 			panic("%s: Illegal protocol defined %u\n", __func__,
1207 				isr->saidx.proto);
1208 		}
1209 		break;
1210 
1211 	case IPSEC_LEVEL_USE:
1212 	case IPSEC_LEVEL_REQUIRE:
1213 		level = isr->level;
1214 		break;
1215 	case IPSEC_LEVEL_UNIQUE:
1216 		level = IPSEC_LEVEL_REQUIRE;
1217 		break;
1218 
1219 	default:
1220 		panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
1221 	}
1222 
1223 	return (level);
1224 }
1225 
1226 /*
1227  * Check security policy requirements against the actual
1228  * packet contents.  Return one if the packet should be
1229  * reject as "invalid"; otherwiser return zero to have the
1230  * packet treated as "valid".
1231  *
1232  * OUT:
1233  *	0: valid
1234  *	1: invalid
1235  */
1236 static int
1237 ipsec_in_reject(struct secpolicy *sp, const struct mbuf *m)
1238 {
1239 	struct ipsecrequest *isr;
1240 	int need_auth;
1241 
1242 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1243 		printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
1244 
1245 	/* Check policy. */
1246 	switch (sp->policy) {
1247 	case IPSEC_POLICY_DISCARD:
1248 		return (1);
1249 	case IPSEC_POLICY_BYPASS:
1250 	case IPSEC_POLICY_NONE:
1251 		return (0);
1252 	}
1253 
1254 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1255 		("invalid policy %u", sp->policy));
1256 
1257 	/* XXX Should compare policy against IPsec header history. */
1258 
1259 	need_auth = 0;
1260 	for (isr = sp->req; isr != NULL; isr = isr->next) {
1261 		if (ipsec_get_reqlevel(isr) != IPSEC_LEVEL_REQUIRE)
1262 			continue;
1263 		switch (isr->saidx.proto) {
1264 		case IPPROTO_ESP:
1265 			if ((m->m_flags & M_DECRYPTED) == 0) {
1266 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1267 				    printf("%s: ESP m_flags:%x\n", __func__,
1268 					    m->m_flags));
1269 				return (1);
1270 			}
1271 
1272 			if (!need_auth &&
1273 			    isr->sav != NULL &&
1274 			    isr->sav->tdb_authalgxform != NULL &&
1275 			    (m->m_flags & M_AUTHIPDGM) == 0) {
1276 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1277 				    printf("%s: ESP/AH m_flags:%x\n", __func__,
1278 					    m->m_flags));
1279 				return (1);
1280 			}
1281 			break;
1282 		case IPPROTO_AH:
1283 			need_auth = 1;
1284 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1285 				KEYDEBUG(KEYDEBUG_IPSEC_DUMP,
1286 				    printf("%s: AH m_flags:%x\n", __func__,
1287 					    m->m_flags));
1288 				return (1);
1289 			}
1290 			break;
1291 		case IPPROTO_IPCOMP:
1292 			/*
1293 			 * We don't really care, as IPcomp document
1294 			 * says that we shouldn't compress small
1295 			 * packets.  IPComp policy should always be
1296 			 * treated as being in "use" level.
1297 			 */
1298 			break;
1299 		}
1300 	}
1301 	return (0);		/* Valid. */
1302 }
1303 
1304 /*
1305  * Non zero return value means security policy DISCARD or policy violation.
1306  */
1307 static int
1308 ipsec46_in_reject(const struct mbuf *m, struct inpcb *inp)
1309 {
1310 	struct secpolicy *sp;
1311 	int error;
1312 	int result;
1313 
1314 	if (!key_havesp(IPSEC_DIR_INBOUND))
1315 		return 0;
1316 
1317 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1318 
1319 	/* Get SP for this packet. */
1320 	if (inp == NULL)
1321 		sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND, &error);
1322 	else
1323 		sp = ipsec_getpolicybysock(m, IPSEC_DIR_INBOUND, inp, &error);
1324 
1325 	if (sp != NULL) {
1326 		result = ipsec_in_reject(sp, m);
1327 		KEY_FREESP(&sp);
1328 	} else {
1329 		result = 1;	/* treat errors as policy violation */
1330 	}
1331 	return (result);
1332 }
1333 
1334 /*
1335  * Check AH/ESP integrity.
1336  * This function is called from tcp_input(), udp_input(),
1337  * and {ah,esp}4_input for tunnel mode.
1338  */
1339 int
1340 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
1341 {
1342 	int result;
1343 
1344 	result = ipsec46_in_reject(m, inp);
1345 	if (result)
1346 		IPSECSTAT_INC(ips_in_polvio);
1347 
1348 	return (result);
1349 }
1350 
1351 #ifdef INET6
1352 /*
1353  * Check AH/ESP integrity.
1354  * This function is called from tcp6_input(), udp6_input(),
1355  * and {ah,esp}6_input for tunnel mode.
1356  */
1357 int
1358 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
1359 {
1360 	int result;
1361 
1362 	result = ipsec46_in_reject(m, inp);
1363 	if (result)
1364 		IPSEC6STAT_INC(ips_in_polvio);
1365 
1366 	return (result);
1367 }
1368 #endif
1369 
1370 /*
1371  * Compute the byte size to be occupied by IPsec header.
1372  * In case it is tunnelled, it includes the size of outer IP header.
1373  * NOTE: SP passed is freed in this function.
1374  */
1375 static size_t
1376 ipsec_hdrsiz_internal(struct secpolicy *sp)
1377 {
1378 	struct ipsecrequest *isr;
1379 	size_t size;
1380 
1381 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1382 		printf("%s: using SP\n", __func__); kdebug_secpolicy(sp));
1383 
1384 	switch (sp->policy) {
1385 	case IPSEC_POLICY_DISCARD:
1386 	case IPSEC_POLICY_BYPASS:
1387 	case IPSEC_POLICY_NONE:
1388 		return (0);
1389 	}
1390 
1391 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1392 		("invalid policy %u", sp->policy));
1393 
1394 	size = 0;
1395 	for (isr = sp->req; isr != NULL; isr = isr->next) {
1396 		size_t clen = 0;
1397 
1398 		switch (isr->saidx.proto) {
1399 		case IPPROTO_ESP:
1400 			clen = esp_hdrsiz(isr->sav);
1401 			break;
1402 		case IPPROTO_AH:
1403 			clen = ah_hdrsiz(isr->sav);
1404 			break;
1405 		case IPPROTO_IPCOMP:
1406 			clen = sizeof(struct ipcomp);
1407 			break;
1408 		}
1409 
1410 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
1411 			switch (isr->saidx.dst.sa.sa_family) {
1412 			case AF_INET:
1413 				clen += sizeof(struct ip);
1414 				break;
1415 #ifdef INET6
1416 			case AF_INET6:
1417 				clen += sizeof(struct ip6_hdr);
1418 				break;
1419 #endif
1420 			default:
1421 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
1422 				    "IPsec tunnel SA\n", __func__,
1423 				    ((struct sockaddr *)&isr->saidx.dst)->sa_family));
1424 				break;
1425 			}
1426 		}
1427 		size += clen;
1428 	}
1429 
1430 	return (size);
1431 }
1432 
1433 /*
1434  * This function is called from ipsec_hdrsiz_tcp(), ip_ipsec_mtu(),
1435  * disabled ip6_ipsec_mtu() and ip6_forward().
1436  */
1437 size_t
1438 ipsec_hdrsiz(const struct mbuf *m, u_int dir, struct inpcb *inp)
1439 {
1440 	struct secpolicy *sp;
1441 	int error;
1442 	size_t size;
1443 
1444 	if (!key_havesp(dir))
1445 		return 0;
1446 
1447 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
1448 
1449 	/* Get SP for this packet. */
1450 	if (inp == NULL)
1451 		sp = ipsec_getpolicybyaddr(m, dir, &error);
1452 	else
1453 		sp = ipsec_getpolicybysock(m, dir, inp, &error);
1454 
1455 	if (sp != NULL) {
1456 		size = ipsec_hdrsiz_internal(sp);
1457 		KEYDEBUG(KEYDEBUG_IPSEC_DATA,
1458 			printf("%s: size:%lu.\n", __func__,
1459 				(unsigned long)size));
1460 
1461 		KEY_FREESP(&sp);
1462 	} else {
1463 		size = 0;	/* XXX Should be panic?
1464 				 * -> No, we are called w/o knowing if
1465 				 *    IPsec processing is needed. */
1466 	}
1467 	return (size);
1468 }
1469 
1470 /*
1471  * Check the variable replay window.
1472  * ipsec_chkreplay() performs replay check before ICV verification.
1473  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1474  * ICV verification (it also performs replay check, which is usually done
1475  * beforehand).
1476  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1477  *
1478  * Based on RFC 6479. Blocks are 32 bits unsigned integers
1479  */
1480 
1481 #define IPSEC_BITMAP_INDEX_MASK(w)	(w - 1)
1482 #define IPSEC_REDUNDANT_BIT_SHIFTS	5
1483 #define IPSEC_REDUNDANT_BITS		(1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1484 #define IPSEC_BITMAP_LOC_MASK		(IPSEC_REDUNDANT_BITS - 1)
1485 
1486 int
1487 ipsec_chkreplay(u_int32_t seq, struct secasvar *sav)
1488 {
1489 	const struct secreplay *replay;
1490 	u_int32_t wsizeb;		/* Constant: window size. */
1491 	int ret, index, bit_location;
1492 
1493 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1494 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1495 
1496 	SECASVAR_LOCK(sav);
1497 
1498 	ret = 0;
1499 	replay = sav->replay;
1500 
1501 	/* No need to check replay if disabled. */
1502 	if (replay->wsize == 0)
1503 		goto allowed;
1504 
1505 	/* Constant. */
1506 	wsizeb = replay->wsize << 3;
1507 
1508 	/* Sequence number of 0 is invalid. */
1509 	if (seq == 0)
1510 		goto end;
1511 
1512 	/* First time is always okay. */
1513 	if (replay->count == 0)
1514 		goto allowed;
1515 
1516 	/* Larger sequences are okay. */
1517 	if (seq > replay->lastseq)
1518 		goto allowed;
1519 
1520 	/* Over range to check, i.e. too old or wrapped. */
1521 	if (replay->lastseq - seq >= wsizeb)
1522 		goto end;
1523 
1524 	/* The sequence is inside the sliding window
1525 	 * now check the bit in the bitmap
1526 	 * bit location only depends on the sequence number
1527 	 */
1528 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1529 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1530 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1531 
1532 	/* This packet already seen? */
1533 	if ((replay->bitmap)[index] & (1 << bit_location))
1534 		goto end;
1535 
1536 allowed:
1537 	ret = 1;
1538 end:
1539 	SECASVAR_UNLOCK(sav);
1540 
1541 	return (ret);
1542 }
1543 
1544 /*
1545  * Check replay counter whether to update or not.
1546  * OUT:	0:	OK
1547  *	1:	NG
1548  */
1549 int
1550 ipsec_updatereplay(u_int32_t seq, struct secasvar *sav)
1551 {
1552 	char buf[128];
1553 	struct secreplay *replay;
1554 	u_int32_t wsizeb;		/* Constant: window size. */
1555 	int ret, diff, index, bit_location;
1556 
1557 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1558 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1559 
1560 	SECASVAR_LOCK(sav);
1561 
1562 	ret = 1;
1563 	replay = sav->replay;
1564 
1565 	if (replay->wsize == 0)
1566 		goto ok;	/* No need to check replay. */
1567 
1568 	/* Constant. */
1569 	wsizeb = replay->wsize << 3;
1570 
1571 	/* Sequence number of 0 is invalid. */
1572 	if (seq == 0)
1573 		goto end;
1574 
1575 	/* The packet is too old, no need to update */
1576 	if (wsizeb + seq < replay->lastseq)
1577 		goto ok;
1578 
1579 	/* Now update the bit */
1580 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS);
1581 
1582 	/* First check if the sequence number is in the range */
1583 	if (seq > replay->lastseq) {
1584 		int id;
1585 		int index_cur = replay->lastseq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1586 
1587 		diff = index - index_cur;
1588 		if (diff > replay->bitmap_size) {
1589 			/* something unusual in this case */
1590 			diff = replay->bitmap_size;
1591 		}
1592 
1593 		for (id = 0; id < diff; ++id) {
1594 			replay->bitmap[(id + index_cur + 1)
1595 			& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1596 		}
1597 
1598 		replay->lastseq = seq;
1599 	}
1600 
1601 	index &= IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1602 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1603 
1604 	/* this packet has already been received */
1605 	if (replay->bitmap[index] & (1 << bit_location))
1606 		goto end;
1607 
1608 	replay->bitmap[index] |= (1 << bit_location);
1609 
1610 ok:
1611 	if (replay->count == ~0) {
1612 
1613 		/* Set overflow flag. */
1614 		replay->overflow++;
1615 
1616 		/* Don't increment, no more packets accepted. */
1617 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0)
1618 			goto end;
1619 
1620 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1621 		    __func__, replay->overflow,
1622 		    ipsec_logsastr(sav, buf, sizeof(buf))));
1623 	}
1624 
1625 	ret = 0;
1626 
1627 end:
1628 	SECASVAR_UNLOCK(sav);
1629 	return (ret);
1630 }
1631 
1632 /* Return a printable string for the address. */
1633 char*
1634 ipsec_address(union sockaddr_union* sa, char *buf, socklen_t size)
1635 {
1636 
1637 	switch (sa->sa.sa_family) {
1638 #ifdef INET
1639 	case AF_INET:
1640 		return (inet_ntop(AF_INET, &sa->sin.sin_addr, buf, size));
1641 #endif /* INET */
1642 #ifdef INET6
1643 	case AF_INET6:
1644 		return (inet_ntop(AF_INET6, &sa->sin6.sin6_addr, buf, size));
1645 #endif /* INET6 */
1646 	default:
1647 		return ("(unknown address family)");
1648 	}
1649 }
1650 
1651 char *
1652 ipsec_logsastr(struct secasvar *sav, char *buf, size_t size)
1653 {
1654 	char sbuf[INET6_ADDRSTRLEN], dbuf[INET6_ADDRSTRLEN];
1655 
1656 	IPSEC_ASSERT(sav->sah->saidx.src.sa.sa_family ==
1657 	    sav->sah->saidx.dst.sa.sa_family, ("address family mismatch"));
1658 
1659 	snprintf(buf, size, "SA(SPI=%08lx src=%s dst=%s)",
1660 	    (u_long)ntohl(sav->spi),
1661 	    ipsec_address(&sav->sah->saidx.src, sbuf, sizeof(sbuf)),
1662 	    ipsec_address(&sav->sah->saidx.dst, dbuf, sizeof(dbuf)));
1663 	return (buf);
1664 }
1665 
1666 void
1667 ipsec_dumpmbuf(const struct mbuf *m)
1668 {
1669 	const u_char *p;
1670 	int totlen;
1671 	int i;
1672 
1673 	totlen = 0;
1674 	printf("---\n");
1675 	while (m) {
1676 		p = mtod(m, const u_char *);
1677 		for (i = 0; i < m->m_len; i++) {
1678 			printf("%02x ", p[i]);
1679 			totlen++;
1680 			if (totlen % 16 == 0)
1681 				printf("\n");
1682 		}
1683 		m = m->m_next;
1684 	}
1685 	if (totlen % 16 != 0)
1686 		printf("\n");
1687 	printf("---\n");
1688 }
1689 
1690 static void
1691 def_policy_init(const void *unused __unused)
1692 {
1693 
1694 	bzero(&V_def_policy, sizeof(struct secpolicy));
1695 	V_def_policy.policy = IPSEC_POLICY_NONE;
1696 	V_def_policy.refcnt = 1;
1697 }
1698 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1699     def_policy_init, NULL);
1700 
1701 
1702 /* XXX This stuff doesn't belong here... */
1703 
1704 static	struct xformsw* xforms = NULL;
1705 
1706 /*
1707  * Register a transform; typically at system startup.
1708  */
1709 void
1710 xform_register(struct xformsw* xsp)
1711 {
1712 
1713 	xsp->xf_next = xforms;
1714 	xforms = xsp;
1715 }
1716 
1717 /*
1718  * Initialize transform support in an sav.
1719  */
1720 int
1721 xform_init(struct secasvar *sav, int xftype)
1722 {
1723 	struct xformsw *xsp;
1724 
1725 	if (sav->tdb_xform != NULL)	/* Previously initialized. */
1726 		return (0);
1727 	for (xsp = xforms; xsp; xsp = xsp->xf_next)
1728 		if (xsp->xf_type == xftype)
1729 			return ((*xsp->xf_init)(sav, xsp));
1730 	return (EINVAL);
1731 }
1732