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