xref: /freebsd/sys/netipsec/ipsec.c (revision 4f52dfbb8d6c4d446500c5b097e3806ec219fbd4)
1 /*	$FreeBSD$	*/
2 /*	$KAME: ipsec.c,v 1.103 2001/05/24 07:14:18 sakane Exp $	*/
3 
4 /*-
5  * SPDX-License-Identifier: BSD-3-Clause
6  *
7  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the project nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * IPsec controller part.
37  */
38 
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/domain.h>
48 #include <sys/priv.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/errno.h>
53 #include <sys/hhook.h>
54 #include <sys/time.h>
55 #include <sys/kernel.h>
56 #include <sys/syslog.h>
57 #include <sys/sysctl.h>
58 #include <sys/proc.h>
59 
60 #include <net/if.h>
61 #include <net/if_enc.h>
62 #include <net/if_var.h>
63 #include <net/vnet.h>
64 
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/in_var.h>
70 #include <netinet/udp.h>
71 #include <netinet/udp_var.h>
72 #include <netinet/tcp.h>
73 #include <netinet/udp.h>
74 
75 #include <netinet/ip6.h>
76 #ifdef INET6
77 #include <netinet6/ip6_var.h>
78 #endif
79 #include <netinet/in_pcb.h>
80 #ifdef INET6
81 #include <netinet/icmp6.h>
82 #endif
83 
84 #include <sys/types.h>
85 #include <netipsec/ipsec.h>
86 #ifdef INET6
87 #include <netipsec/ipsec6.h>
88 #endif
89 #include <netipsec/ah_var.h>
90 #include <netipsec/esp_var.h>
91 #include <netipsec/ipcomp.h>		/*XXX*/
92 #include <netipsec/ipcomp_var.h>
93 #include <netipsec/ipsec_support.h>
94 
95 #include <netipsec/key.h>
96 #include <netipsec/keydb.h>
97 #include <netipsec/key_debug.h>
98 
99 #include <netipsec/xform.h>
100 
101 #include <machine/in_cksum.h>
102 
103 #include <opencrypto/cryptodev.h>
104 
105 /* NB: name changed so netstat doesn't use it. */
106 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec4stat);
107 VNET_PCPUSTAT_SYSINIT(ipsec4stat);
108 
109 #ifdef VIMAGE
110 VNET_PCPUSTAT_SYSUNINIT(ipsec4stat);
111 #endif /* VIMAGE */
112 
113 /* DF bit on encap. 0: clear 1: set 2: copy */
114 VNET_DEFINE(int, ip4_ipsec_dfbit) = 0;
115 VNET_DEFINE(int, ip4_esp_trans_deflev) = IPSEC_LEVEL_USE;
116 VNET_DEFINE(int, ip4_esp_net_deflev) = IPSEC_LEVEL_USE;
117 VNET_DEFINE(int, ip4_ah_trans_deflev) = IPSEC_LEVEL_USE;
118 VNET_DEFINE(int, ip4_ah_net_deflev) = IPSEC_LEVEL_USE;
119 /* ECN ignore(-1)/forbidden(0)/allowed(1) */
120 VNET_DEFINE(int, ip4_ipsec_ecn) = 0;
121 
122 static VNET_DEFINE(int, ip4_filtertunnel) = 0;
123 #define	V_ip4_filtertunnel VNET(ip4_filtertunnel)
124 static VNET_DEFINE(int, check_policy_history) = 0;
125 #define	V_check_policy_history	VNET(check_policy_history)
126 static VNET_DEFINE(struct secpolicy *, def_policy) = NULL;
127 #define	V_def_policy	VNET(def_policy)
128 static int
129 sysctl_def_policy(SYSCTL_HANDLER_ARGS)
130 {
131 	int error, value;
132 
133 	value = V_def_policy->policy;
134 	error = sysctl_handle_int(oidp, &value, 0, req);
135 	if (error == 0) {
136 		if (value != IPSEC_POLICY_DISCARD &&
137 		    value != IPSEC_POLICY_NONE)
138 			return (EINVAL);
139 		V_def_policy->policy = value;
140 	}
141 	return (error);
142 }
143 
144 /*
145  * Crypto support requirements:
146  *
147  *  1	require hardware support
148  * -1	require software support
149  *  0	take anything
150  */
151 VNET_DEFINE(int, crypto_support) = CRYPTOCAP_F_HARDWARE | CRYPTOCAP_F_SOFTWARE;
152 
153 /*
154  * Use asynchronous mode to parallelize crypto jobs:
155  *
156  *  0 - disabled
157  *  1 - enabled
158  */
159 VNET_DEFINE(int, async_crypto) = 0;
160 
161 /*
162  * TCP/UDP checksum handling policy for transport mode NAT-T (RFC3948)
163  *
164  * 0 - auto: incrementally recompute, when checksum delta is known;
165  *     if checksum delta isn't known, reset checksum to zero for UDP,
166  *     and mark csum_flags as valid for TCP.
167  * 1 - fully recompute TCP/UDP checksum.
168  */
169 VNET_DEFINE(int, natt_cksum_policy) = 0;
170 
171 FEATURE(ipsec, "Internet Protocol Security (IPsec)");
172 FEATURE(ipsec_natt, "UDP Encapsulation of IPsec ESP Packets ('NAT-T')");
173 
174 SYSCTL_DECL(_net_inet_ipsec);
175 
176 /* net.inet.ipsec */
177 SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
178 	CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW, 0, 0, sysctl_def_policy, "I",
179 	"IPsec default policy.");
180 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
181 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
182 	"Default ESP transport mode level");
183 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
184 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
185 	"Default ESP tunnel mode level.");
186 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
187 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
188 	"AH transfer mode default level.");
189 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
190 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
191 	"AH tunnel mode default level.");
192 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
193 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
194 	"If set, clear type-of-service field when doing AH computation.");
195 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
196 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
197 	"Do not fragment bit on encap.");
198 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
199 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
200 	"Explicit Congestion Notification handling.");
201 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
202 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
203 	"Crypto driver selection.");
204 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, async_crypto,
205 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(async_crypto), 0,
206 	"Use asynchronous mode to parallelize crypto jobs.");
207 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, check_policy_history,
208 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(check_policy_history), 0,
209 	"Use strict check of inbound packets to security policy compliance.");
210 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, natt_cksum_policy,
211 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(natt_cksum_policy), 0,
212 	"Method to fix TCP/UDP checksum for transport mode IPsec after NAT.");
213 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, filtertunnel,
214 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_filtertunnel), 0,
215 	"If set, filter packets from an IPsec tunnel.");
216 SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
217     ipsec4stat, "IPsec IPv4 statistics.");
218 
219 #ifdef REGRESSION
220 /*
221  * When set to 1, IPsec will send packets with the same sequence number.
222  * This allows to verify if the other side has proper replay attacks detection.
223  */
224 VNET_DEFINE(int, ipsec_replay) = 0;
225 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay,
226 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
227 	"Emulate replay attack");
228 /*
229  * When set 1, IPsec will send packets with corrupted HMAC.
230  * This allows to verify if the other side properly detects modified packets.
231  */
232 VNET_DEFINE(int, ipsec_integrity) = 0;
233 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
234 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
235 	"Emulate man-in-the-middle attack");
236 #endif
237 
238 #ifdef INET6
239 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
240 VNET_PCPUSTAT_SYSINIT(ipsec6stat);
241 
242 #ifdef VIMAGE
243 VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
244 #endif /* VIMAGE */
245 
246 VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
247 VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
248 VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
249 VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
250 VNET_DEFINE(int, ip6_ipsec_ecn) = 0;	/* ECN ignore(-1)/forbidden(0)/allowed(1) */
251 
252 static VNET_DEFINE(int, ip6_filtertunnel) = 0;
253 #define	V_ip6_filtertunnel	VNET(ip6_filtertunnel)
254 
255 SYSCTL_DECL(_net_inet6_ipsec6);
256 
257 /* net.inet6.ipsec6 */
258 SYSCTL_PROC(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy,
259 	CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW, 0, 0, sysctl_def_policy, "I",
260 	"IPsec default policy.");
261 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
262 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
263 	"Default ESP transport mode level.");
264 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
265 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0,
266 	"Default ESP tunnel mode level.");
267 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
268 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0,
269 	"AH transfer mode default level.");
270 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
271 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0,
272 	"AH tunnel mode default level.");
273 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn,
274 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0,
275 	"Explicit Congestion Notification handling.");
276 SYSCTL_INT(_net_inet6_ipsec6, OID_AUTO, filtertunnel,
277 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_filtertunnel),  0,
278 	"If set, filter packets from an IPsec tunnel.");
279 SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
280     struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
281 #endif /* INET6 */
282 
283 static int ipsec_in_reject(struct secpolicy *, struct inpcb *,
284     const struct mbuf *);
285 
286 #ifdef INET
287 static void ipsec4_get_ulp(const struct mbuf *, struct secpolicyindex *, int);
288 static void ipsec4_setspidx_ipaddr(const struct mbuf *,
289     struct secpolicyindex *);
290 #endif
291 #ifdef INET6
292 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
293 static void ipsec6_setspidx_ipaddr(const struct mbuf *,
294     struct secpolicyindex *);
295 #endif
296 
297 /*
298  * Return a held reference to the default SP.
299  */
300 static struct secpolicy *
301 key_allocsp_default(void)
302 {
303 
304 	key_addref(V_def_policy);
305 	return (V_def_policy);
306 }
307 
308 static void
309 ipsec_invalidate_cache(struct inpcb *inp, u_int dir)
310 {
311 	struct secpolicy *sp;
312 
313 	INP_WLOCK_ASSERT(inp);
314 	if (dir == IPSEC_DIR_OUTBOUND) {
315 		if (inp->inp_sp->flags & INP_INBOUND_POLICY)
316 			return;
317 		sp = inp->inp_sp->sp_in;
318 		inp->inp_sp->sp_in = NULL;
319 	} else {
320 		if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
321 			return;
322 		sp = inp->inp_sp->sp_out;
323 		inp->inp_sp->sp_out = NULL;
324 	}
325 	if (sp != NULL)
326 		key_freesp(&sp); /* release extra reference */
327 }
328 
329 static void
330 ipsec_cachepolicy(struct inpcb *inp, struct secpolicy *sp, u_int dir)
331 {
332 	uint32_t genid;
333 	int downgrade;
334 
335 	INP_LOCK_ASSERT(inp);
336 
337 	if (dir == IPSEC_DIR_OUTBOUND) {
338 		/* Do we have configured PCB policy? */
339 		if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
340 			return;
341 		/* Another thread has already set cached policy */
342 		if (inp->inp_sp->sp_out != NULL)
343 			return;
344 		/*
345 		 * Do not cache OUTBOUND policy if PCB isn't connected,
346 		 * i.e. foreign address is INADDR_ANY/UNSPECIFIED.
347 		 */
348 #ifdef INET
349 		if ((inp->inp_vflag & INP_IPV4) != 0 &&
350 		    inp->inp_faddr.s_addr == INADDR_ANY)
351 			return;
352 #endif
353 #ifdef INET6
354 		if ((inp->inp_vflag & INP_IPV6) != 0 &&
355 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
356 			return;
357 #endif
358 	} else {
359 		/* Do we have configured PCB policy? */
360 		if (inp->inp_sp->flags & INP_INBOUND_POLICY)
361 			return;
362 		/* Another thread has already set cached policy */
363 		if (inp->inp_sp->sp_in != NULL)
364 			return;
365 		/*
366 		 * Do not cache INBOUND policy for listen socket,
367 		 * that is bound to INADDR_ANY/UNSPECIFIED address.
368 		 */
369 #ifdef INET
370 		if ((inp->inp_vflag & INP_IPV4) != 0 &&
371 		    inp->inp_faddr.s_addr == INADDR_ANY)
372 			return;
373 #endif
374 #ifdef INET6
375 		if ((inp->inp_vflag & INP_IPV6) != 0 &&
376 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
377 			return;
378 #endif
379 	}
380 	downgrade = 0;
381 	if (!INP_WLOCKED(inp)) {
382 		if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
383 			return;
384 	}
385 	if (dir == IPSEC_DIR_OUTBOUND)
386 		inp->inp_sp->sp_out = sp;
387 	else
388 		inp->inp_sp->sp_in = sp;
389 	/*
390 	 * SP is already referenced by the lookup code.
391 	 * We take extra reference here to avoid race in the
392 	 * ipsec_getpcbpolicy() function - SP will not be freed in the
393 	 * time between we take SP pointer from the cache and key_addref()
394 	 * call.
395 	 */
396 	key_addref(sp);
397 	genid = key_getspgen();
398 	if (genid != inp->inp_sp->genid) {
399 		ipsec_invalidate_cache(inp, dir);
400 		inp->inp_sp->genid = genid;
401 	}
402 	KEYDBG(IPSEC_STAMP,
403 	    printf("%s: PCB(%p): cached %s SP(%p)\n",
404 	    __func__, inp, dir == IPSEC_DIR_OUTBOUND ? "OUTBOUND":
405 	    "INBOUND", sp));
406 	if (downgrade != 0)
407 		INP_DOWNGRADE(inp);
408 }
409 
410 static struct secpolicy *
411 ipsec_checkpolicy(struct secpolicy *sp, struct inpcb *inp, int *error)
412 {
413 
414 	/* Save found OUTBOUND policy into PCB SP cache. */
415 	if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_out == NULL)
416 		ipsec_cachepolicy(inp, sp, IPSEC_DIR_OUTBOUND);
417 
418 	switch (sp->policy) {
419 	default:
420 		printf("%s: invalid policy %u\n", __func__, sp->policy);
421 		/* FALLTHROUGH */
422 	case IPSEC_POLICY_DISCARD:
423 		*error = -EINVAL;	/* Packet is discarded by caller. */
424 		/* FALLTHROUGH */
425 	case IPSEC_POLICY_BYPASS:
426 	case IPSEC_POLICY_NONE:
427 		key_freesp(&sp);
428 		sp = NULL;		/* NB: force NULL result. */
429 		break;
430 	case IPSEC_POLICY_IPSEC:
431 		/* XXXAE: handle LARVAL SP */
432 		break;
433 	}
434 	KEYDBG(IPSEC_DUMP,
435 	    printf("%s: get SP(%p), error %d\n", __func__, sp, *error));
436 	return (sp);
437 }
438 
439 static struct secpolicy *
440 ipsec_getpcbpolicy(struct inpcb *inp, u_int dir)
441 {
442 	struct secpolicy *sp;
443 	int flags, downgrade;
444 
445 	if (inp == NULL || inp->inp_sp == NULL)
446 		return (NULL);
447 
448 	INP_LOCK_ASSERT(inp);
449 
450 	flags = inp->inp_sp->flags;
451 	if (dir == IPSEC_DIR_OUTBOUND) {
452 		sp = inp->inp_sp->sp_out;
453 		flags &= INP_OUTBOUND_POLICY;
454 	} else {
455 		sp = inp->inp_sp->sp_in;
456 		flags &= INP_INBOUND_POLICY;
457 	}
458 	/*
459 	 * Check flags. If we have PCB SP, just return it.
460 	 * Otherwise we need to check that cached SP entry isn't stale.
461 	 */
462 	if (flags == 0) {
463 		if (sp == NULL)
464 			return (NULL);
465 		if (inp->inp_sp->genid != key_getspgen()) {
466 			/* Invalidate the cache. */
467 			downgrade = 0;
468 			if (!INP_WLOCKED(inp)) {
469 				if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
470 					return (NULL);
471 			}
472 			ipsec_invalidate_cache(inp, IPSEC_DIR_OUTBOUND);
473 			ipsec_invalidate_cache(inp, IPSEC_DIR_INBOUND);
474 			if (downgrade != 0)
475 				INP_DOWNGRADE(inp);
476 			return (NULL);
477 		}
478 		KEYDBG(IPSEC_STAMP,
479 		    printf("%s: PCB(%p): cache hit SP(%p)\n",
480 		    __func__, inp, sp));
481 		/* Return referenced cached policy */
482 	}
483 	key_addref(sp);
484 	return (sp);
485 }
486 
487 #ifdef INET
488 static void
489 ipsec4_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
490     int needport)
491 {
492 	uint8_t nxt;
493 	int off;
494 
495 	/* Sanity check. */
496 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
497 	    ("packet too short"));
498 
499 	if (m->m_len >= sizeof (struct ip)) {
500 		const struct ip *ip = mtod(m, const struct ip *);
501 		if (ip->ip_off & htons(IP_MF | IP_OFFMASK))
502 			goto done;
503 		off = ip->ip_hl << 2;
504 		nxt = ip->ip_p;
505 	} else {
506 		struct ip ih;
507 
508 		m_copydata(m, 0, sizeof (struct ip), (caddr_t) &ih);
509 		if (ih.ip_off & htons(IP_MF | IP_OFFMASK))
510 			goto done;
511 		off = ih.ip_hl << 2;
512 		nxt = ih.ip_p;
513 	}
514 
515 	while (off < m->m_pkthdr.len) {
516 		struct ip6_ext ip6e;
517 		struct tcphdr th;
518 		struct udphdr uh;
519 
520 		switch (nxt) {
521 		case IPPROTO_TCP:
522 			spidx->ul_proto = nxt;
523 			if (!needport)
524 				goto done_proto;
525 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
526 				goto done;
527 			m_copydata(m, off, sizeof (th), (caddr_t) &th);
528 			spidx->src.sin.sin_port = th.th_sport;
529 			spidx->dst.sin.sin_port = th.th_dport;
530 			return;
531 		case IPPROTO_UDP:
532 			spidx->ul_proto = nxt;
533 			if (!needport)
534 				goto done_proto;
535 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
536 				goto done;
537 			m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
538 			spidx->src.sin.sin_port = uh.uh_sport;
539 			spidx->dst.sin.sin_port = uh.uh_dport;
540 			return;
541 		case IPPROTO_AH:
542 			if (off + sizeof(ip6e) > m->m_pkthdr.len)
543 				goto done;
544 			/* XXX Sigh, this works but is totally bogus. */
545 			m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
546 			off += (ip6e.ip6e_len + 2) << 2;
547 			nxt = ip6e.ip6e_nxt;
548 			break;
549 		case IPPROTO_ICMP:
550 		default:
551 			/* XXX Intermediate headers??? */
552 			spidx->ul_proto = nxt;
553 			goto done_proto;
554 		}
555 	}
556 done:
557 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
558 done_proto:
559 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
560 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
561 	KEYDBG(IPSEC_DUMP,
562 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
563 }
564 
565 static void
566 ipsec4_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
567 {
568 
569 	ipsec4_setsockaddrs(m, &spidx->src, &spidx->dst);
570 	spidx->prefs = sizeof(struct in_addr) << 3;
571 	spidx->prefd = sizeof(struct in_addr) << 3;
572 }
573 
574 static struct secpolicy *
575 ipsec4_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
576     int needport)
577 {
578 	struct secpolicyindex spidx;
579 	struct secpolicy *sp;
580 
581 	sp = ipsec_getpcbpolicy(inp, dir);
582 	if (sp == NULL && key_havesp(dir)) {
583 		/* Make an index to look for a policy. */
584 		ipsec4_setspidx_ipaddr(m, &spidx);
585 		ipsec4_get_ulp(m, &spidx, needport);
586 		spidx.dir = dir;
587 		sp = key_allocsp(&spidx, dir);
588 	}
589 	if (sp == NULL)		/* No SP found, use system default. */
590 		sp = key_allocsp_default();
591 	return (sp);
592 }
593 
594 /*
595  * Check security policy for *OUTBOUND* IPv4 packet.
596  */
597 struct secpolicy *
598 ipsec4_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
599     int needport)
600 {
601 	struct secpolicy *sp;
602 
603 	*error = 0;
604 	sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
605 	if (sp != NULL)
606 		sp = ipsec_checkpolicy(sp, inp, error);
607 	if (sp == NULL) {
608 		switch (*error) {
609 		case 0: /* No IPsec required: BYPASS or NONE */
610 			break;
611 		case -EINVAL:
612 			IPSECSTAT_INC(ips_out_polvio);
613 			break;
614 		default:
615 			IPSECSTAT_INC(ips_out_inval);
616 		}
617 	}
618 	KEYDBG(IPSEC_STAMP,
619 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
620 	if (sp != NULL)
621 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
622 	return (sp);
623 }
624 
625 /*
626  * Check IPv4 packet against *INBOUND* security policy.
627  * This function is called from tcp_input(), udp_input(),
628  * rip_input() and sctp_input().
629  */
630 int
631 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
632 {
633 	struct secpolicy *sp;
634 	int result;
635 
636 	sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
637 	result = ipsec_in_reject(sp, inp, m);
638 	key_freesp(&sp);
639 	if (result != 0)
640 		IPSECSTAT_INC(ips_in_polvio);
641 	return (result);
642 }
643 
644 /*
645  * IPSEC_CAP() method implementation for IPv4.
646  */
647 int
648 ipsec4_capability(struct mbuf *m, u_int cap)
649 {
650 
651 	switch (cap) {
652 	case IPSEC_CAP_BYPASS_FILTER:
653 		/*
654 		 * Bypass packet filtering for packets previously handled
655 		 * by IPsec.
656 		 */
657 		if (!V_ip4_filtertunnel &&
658 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
659 			return (1);
660 		return (0);
661 	case IPSEC_CAP_OPERABLE:
662 		/* Do we have active security policies? */
663 		if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
664 		    key_havesp(IPSEC_DIR_OUTBOUND) != 0)
665 			return (1);
666 		return (0);
667 	};
668 	return (EOPNOTSUPP);
669 }
670 
671 #endif /* INET */
672 
673 #ifdef INET6
674 static void
675 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
676     int needport)
677 {
678 	struct tcphdr th;
679 	struct udphdr uh;
680 	struct icmp6_hdr ih;
681 	int off, nxt;
682 
683 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
684 	    ("packet too short"));
685 
686 	/* Set default. */
687 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
688 	spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
689 	spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
690 
691 	nxt = -1;
692 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
693 	if (off < 0 || m->m_pkthdr.len < off)
694 		return;
695 
696 	switch (nxt) {
697 	case IPPROTO_TCP:
698 		spidx->ul_proto = nxt;
699 		if (!needport)
700 			break;
701 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
702 			break;
703 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
704 		spidx->src.sin6.sin6_port = th.th_sport;
705 		spidx->dst.sin6.sin6_port = th.th_dport;
706 		break;
707 	case IPPROTO_UDP:
708 		spidx->ul_proto = nxt;
709 		if (!needport)
710 			break;
711 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
712 			break;
713 		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
714 		spidx->src.sin6.sin6_port = uh.uh_sport;
715 		spidx->dst.sin6.sin6_port = uh.uh_dport;
716 		break;
717 	case IPPROTO_ICMPV6:
718 		spidx->ul_proto = nxt;
719 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
720 			break;
721 		m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
722 		spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
723 		spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
724 		break;
725 	default:
726 		/* XXX Intermediate headers??? */
727 		spidx->ul_proto = nxt;
728 		break;
729 	}
730 	KEYDBG(IPSEC_DUMP,
731 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
732 }
733 
734 static void
735 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
736 {
737 
738 	ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
739 	spidx->prefs = sizeof(struct in6_addr) << 3;
740 	spidx->prefd = sizeof(struct in6_addr) << 3;
741 }
742 
743 static struct secpolicy *
744 ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
745     int needport)
746 {
747 	struct secpolicyindex spidx;
748 	struct secpolicy *sp;
749 
750 	sp = ipsec_getpcbpolicy(inp, dir);
751 	if (sp == NULL && key_havesp(dir)) {
752 		/* Make an index to look for a policy. */
753 		ipsec6_setspidx_ipaddr(m, &spidx);
754 		ipsec6_get_ulp(m, &spidx, needport);
755 		spidx.dir = dir;
756 		sp = key_allocsp(&spidx, dir);
757 	}
758 	if (sp == NULL)		/* No SP found, use system default. */
759 		sp = key_allocsp_default();
760 	return (sp);
761 }
762 
763 /*
764  * Check security policy for *OUTBOUND* IPv6 packet.
765  */
766 struct secpolicy *
767 ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
768     int needport)
769 {
770 	struct secpolicy *sp;
771 
772 	*error = 0;
773 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
774 	if (sp != NULL)
775 		sp = ipsec_checkpolicy(sp, inp, error);
776 	if (sp == NULL) {
777 		switch (*error) {
778 		case 0: /* No IPsec required: BYPASS or NONE */
779 			break;
780 		case -EINVAL:
781 			IPSEC6STAT_INC(ips_out_polvio);
782 			break;
783 		default:
784 			IPSEC6STAT_INC(ips_out_inval);
785 		}
786 	}
787 	KEYDBG(IPSEC_STAMP,
788 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
789 	if (sp != NULL)
790 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
791 	return (sp);
792 }
793 
794 /*
795  * Check IPv6 packet against inbound security policy.
796  * This function is called from tcp6_input(), udp6_input(),
797  * rip6_input() and sctp_input().
798  */
799 int
800 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
801 {
802 	struct secpolicy *sp;
803 	int result;
804 
805 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
806 	result = ipsec_in_reject(sp, inp, m);
807 	key_freesp(&sp);
808 	if (result)
809 		IPSEC6STAT_INC(ips_in_polvio);
810 	return (result);
811 }
812 
813 /*
814  * IPSEC_CAP() method implementation for IPv6.
815  */
816 int
817 ipsec6_capability(struct mbuf *m, u_int cap)
818 {
819 
820 	switch (cap) {
821 	case IPSEC_CAP_BYPASS_FILTER:
822 		/*
823 		 * Bypass packet filtering for packets previously handled
824 		 * by IPsec.
825 		 */
826 		if (!V_ip6_filtertunnel &&
827 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
828 			return (1);
829 		return (0);
830 	case IPSEC_CAP_OPERABLE:
831 		/* Do we have active security policies? */
832 		if (key_havesp(IPSEC_DIR_INBOUND) != 0 ||
833 		    key_havesp(IPSEC_DIR_OUTBOUND) != 0)
834 			return (1);
835 		return (0);
836 	};
837 	return (EOPNOTSUPP);
838 }
839 #endif /* INET6 */
840 
841 int
842 ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
843 {
844 	int idx;
845 
846 	switch (ctx->af) {
847 #ifdef INET
848 	case AF_INET:
849 		idx = HHOOK_IPSEC_INET;
850 		break;
851 #endif
852 #ifdef INET6
853 	case AF_INET6:
854 		idx = HHOOK_IPSEC_INET6;
855 		break;
856 #endif
857 	default:
858 		return (EPFNOSUPPORT);
859 	}
860 	if (type == HHOOK_TYPE_IPSEC_IN)
861 		HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
862 	else
863 		HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
864 	if (*ctx->mp == NULL)
865 		return (EACCES);
866 	return (0);
867 }
868 
869 /*
870  * Return current level.
871  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
872  */
873 u_int
874 ipsec_get_reqlevel(struct secpolicy *sp, u_int idx)
875 {
876 	struct ipsecrequest *isr;
877 	u_int esp_trans_deflev, esp_net_deflev;
878 	u_int ah_trans_deflev, ah_net_deflev;
879 	u_int level = 0;
880 
881 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
882 /* XXX Note that we have ipseclog() expanded here - code sync issue. */
883 #define IPSEC_CHECK_DEFAULT(lev) \
884 	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE &&	\
885 	  (lev) != IPSEC_LEVEL_UNIQUE)					\
886 		? (V_ipsec_debug  ?					\
887 		log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
888 		(lev), IPSEC_LEVEL_REQUIRE) : 0),			\
889 		(lev) = IPSEC_LEVEL_REQUIRE, (lev) : (lev))
890 
891 	/*
892 	 * IPsec VTI uses unique security policy with fake spidx filled
893 	 * with zeroes. Just return IPSEC_LEVEL_REQUIRE instead of doing
894 	 * full level lookup for such policies.
895 	 */
896 	if (sp->state == IPSEC_SPSTATE_IFNET) {
897 		IPSEC_ASSERT(sp->req[idx]->level == IPSEC_LEVEL_UNIQUE,
898 		    ("Wrong IPsec request level %d", sp->req[idx]->level));
899 		return (IPSEC_LEVEL_REQUIRE);
900 	}
901 
902 	/* Set default level. */
903 	switch (sp->spidx.src.sa.sa_family) {
904 #ifdef INET
905 	case AF_INET:
906 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
907 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
908 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
909 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
910 		break;
911 #endif
912 #ifdef INET6
913 	case AF_INET6:
914 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
915 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
916 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
917 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
918 		break;
919 #endif /* INET6 */
920 	default:
921 		panic("%s: unknown af %u",
922 			__func__, sp->spidx.src.sa.sa_family);
923 	}
924 
925 #undef IPSEC_CHECK_DEFAULT
926 
927 	isr = sp->req[idx];
928 	/* Set level. */
929 	switch (isr->level) {
930 	case IPSEC_LEVEL_DEFAULT:
931 		switch (isr->saidx.proto) {
932 		case IPPROTO_ESP:
933 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
934 				level = esp_net_deflev;
935 			else
936 				level = esp_trans_deflev;
937 			break;
938 		case IPPROTO_AH:
939 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
940 				level = ah_net_deflev;
941 			else
942 				level = ah_trans_deflev;
943 			break;
944 		case IPPROTO_IPCOMP:
945 			/*
946 			 * We don't really care, as IPcomp document says that
947 			 * we shouldn't compress small packets.
948 			 */
949 			level = IPSEC_LEVEL_USE;
950 			break;
951 		default:
952 			panic("%s: Illegal protocol defined %u\n", __func__,
953 				isr->saidx.proto);
954 		}
955 		break;
956 
957 	case IPSEC_LEVEL_USE:
958 	case IPSEC_LEVEL_REQUIRE:
959 		level = isr->level;
960 		break;
961 	case IPSEC_LEVEL_UNIQUE:
962 		level = IPSEC_LEVEL_REQUIRE;
963 		break;
964 
965 	default:
966 		panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
967 	}
968 
969 	return (level);
970 }
971 
972 static int
973 ipsec_check_history(const struct mbuf *m, struct secpolicy *sp, u_int idx)
974 {
975 	struct xform_history *xh;
976 	struct m_tag *mtag;
977 
978 	mtag = NULL;
979 	while ((mtag = m_tag_find(__DECONST(struct mbuf *, m),
980 	    PACKET_TAG_IPSEC_IN_DONE, mtag)) != NULL) {
981 		xh = (struct xform_history *)(mtag + 1);
982 		KEYDBG(IPSEC_DATA,
983 		    char buf[IPSEC_ADDRSTRLEN];
984 		    printf("%s: mode %s proto %u dst %s\n", __func__,
985 			kdebug_secasindex_mode(xh->mode), xh->proto,
986 			ipsec_address(&xh->dst, buf, sizeof(buf))));
987 		if (xh->proto != sp->req[idx]->saidx.proto)
988 			continue;
989 		/* If SA had IPSEC_MODE_ANY, consider this as match. */
990 		if (xh->mode != sp->req[idx]->saidx.mode &&
991 		    xh->mode != IPSEC_MODE_ANY)
992 			continue;
993 		/*
994 		 * For transport mode IPsec request doesn't contain
995 		 * addresses. We need to use address from spidx.
996 		 */
997 		if (sp->req[idx]->saidx.mode == IPSEC_MODE_TRANSPORT) {
998 			if (key_sockaddrcmp_withmask(&xh->dst.sa,
999 			    &sp->spidx.dst.sa, sp->spidx.prefd) != 0)
1000 				continue;
1001 		} else {
1002 			if (key_sockaddrcmp(&xh->dst.sa,
1003 			    &sp->req[idx]->saidx.dst.sa, 0) != 0)
1004 				continue;
1005 		}
1006 		return (0); /* matched */
1007 	}
1008 	return (1);
1009 }
1010 
1011 /*
1012  * Check security policy requirements against the actual
1013  * packet contents.  Return one if the packet should be
1014  * reject as "invalid"; otherwiser return zero to have the
1015  * packet treated as "valid".
1016  *
1017  * OUT:
1018  *	0: valid
1019  *	1: invalid
1020  */
1021 static int
1022 ipsec_in_reject(struct secpolicy *sp, struct inpcb *inp, const struct mbuf *m)
1023 {
1024 	int i;
1025 
1026 	KEYDBG(IPSEC_STAMP,
1027 	    printf("%s: PCB(%p): using SP(%p)\n", __func__, inp, sp));
1028 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1029 
1030 	if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_in == NULL)
1031 		ipsec_cachepolicy(inp, sp, IPSEC_DIR_INBOUND);
1032 
1033 	/* Check policy. */
1034 	switch (sp->policy) {
1035 	case IPSEC_POLICY_DISCARD:
1036 		return (1);
1037 	case IPSEC_POLICY_BYPASS:
1038 	case IPSEC_POLICY_NONE:
1039 		return (0);
1040 	}
1041 
1042 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1043 		("invalid policy %u", sp->policy));
1044 
1045 	/*
1046 	 * ipsec[46]_common_input_cb after each transform adds
1047 	 * PACKET_TAG_IPSEC_IN_DONE mbuf tag. It contains SPI, proto, mode
1048 	 * and destination address from saidx. We can compare info from
1049 	 * these tags with requirements in SP.
1050 	 */
1051 	for (i = 0; i < sp->tcount; i++) {
1052 		/*
1053 		 * Do not check IPcomp, since IPcomp document
1054 		 * says that we shouldn't compress small packets.
1055 		 * IPComp policy should always be treated as being
1056 		 * in "use" level.
1057 		 */
1058 		if (sp->req[i]->saidx.proto == IPPROTO_IPCOMP ||
1059 		    ipsec_get_reqlevel(sp, i) != IPSEC_LEVEL_REQUIRE)
1060 			continue;
1061 		if (V_check_policy_history != 0 &&
1062 		    ipsec_check_history(m, sp, i) != 0)
1063 			return (1);
1064 		else switch (sp->req[i]->saidx.proto) {
1065 		case IPPROTO_ESP:
1066 			if ((m->m_flags & M_DECRYPTED) == 0) {
1067 				KEYDBG(IPSEC_DUMP,
1068 				    printf("%s: ESP m_flags:%x\n", __func__,
1069 					    m->m_flags));
1070 				return (1);
1071 			}
1072 			break;
1073 		case IPPROTO_AH:
1074 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1075 				KEYDBG(IPSEC_DUMP,
1076 				    printf("%s: AH m_flags:%x\n", __func__,
1077 					    m->m_flags));
1078 				return (1);
1079 			}
1080 			break;
1081 		}
1082 	}
1083 	return (0);		/* Valid. */
1084 }
1085 
1086 /*
1087  * Compute the byte size to be occupied by IPsec header.
1088  * In case it is tunnelled, it includes the size of outer IP header.
1089  */
1090 static size_t
1091 ipsec_hdrsiz_internal(struct secpolicy *sp)
1092 {
1093 	size_t size;
1094 	int i;
1095 
1096 	KEYDBG(IPSEC_STAMP, printf("%s: using SP(%p)\n", __func__, sp));
1097 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1098 
1099 	switch (sp->policy) {
1100 	case IPSEC_POLICY_DISCARD:
1101 	case IPSEC_POLICY_BYPASS:
1102 	case IPSEC_POLICY_NONE:
1103 		return (0);
1104 	}
1105 
1106 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1107 		("invalid policy %u", sp->policy));
1108 
1109 	/*
1110 	 * XXX: for each transform we need to lookup suitable SA
1111 	 * and use info from SA to calculate headers size.
1112 	 * XXX: for NAT-T we need to cosider UDP header size.
1113 	 */
1114 	size = 0;
1115 	for (i = 0; i < sp->tcount; i++) {
1116 		switch (sp->req[i]->saidx.proto) {
1117 		case IPPROTO_ESP:
1118 			size += esp_hdrsiz(NULL);
1119 			break;
1120 		case IPPROTO_AH:
1121 			size += ah_hdrsiz(NULL);
1122 			break;
1123 		case IPPROTO_IPCOMP:
1124 			size += sizeof(struct ipcomp);
1125 			break;
1126 		}
1127 
1128 		if (sp->req[i]->saidx.mode == IPSEC_MODE_TUNNEL) {
1129 			switch (sp->req[i]->saidx.dst.sa.sa_family) {
1130 #ifdef INET
1131 			case AF_INET:
1132 				size += sizeof(struct ip);
1133 				break;
1134 #endif
1135 #ifdef INET6
1136 			case AF_INET6:
1137 				size += sizeof(struct ip6_hdr);
1138 				break;
1139 #endif
1140 			default:
1141 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
1142 				    "IPsec tunnel SA\n", __func__,
1143 				    sp->req[i]->saidx.dst.sa.sa_family));
1144 				break;
1145 			}
1146 		}
1147 	}
1148 	return (size);
1149 }
1150 
1151 /*
1152  * Compute ESP/AH header size for protocols with PCB, including
1153  * outer IP header. Currently only tcp_output() uses it.
1154  */
1155 size_t
1156 ipsec_hdrsiz_inpcb(struct inpcb *inp)
1157 {
1158 	struct secpolicyindex spidx;
1159 	struct secpolicy *sp;
1160 	size_t sz;
1161 
1162 	sp = ipsec_getpcbpolicy(inp, IPSEC_DIR_OUTBOUND);
1163 	if (sp == NULL && key_havesp(IPSEC_DIR_OUTBOUND)) {
1164 		ipsec_setspidx_inpcb(inp, &spidx, IPSEC_DIR_OUTBOUND);
1165 		sp = key_allocsp(&spidx, IPSEC_DIR_OUTBOUND);
1166 	}
1167 	if (sp == NULL)
1168 		sp = key_allocsp_default();
1169 	sz = ipsec_hdrsiz_internal(sp);
1170 	key_freesp(&sp);
1171 	return (sz);
1172 }
1173 
1174 /*
1175  * Check the variable replay window.
1176  * ipsec_chkreplay() performs replay check before ICV verification.
1177  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1178  * ICV verification (it also performs replay check, which is usually done
1179  * beforehand).
1180  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1181  *
1182  * Based on RFC 6479. Blocks are 32 bits unsigned integers
1183  */
1184 
1185 #define IPSEC_BITMAP_INDEX_MASK(w)	(w - 1)
1186 #define IPSEC_REDUNDANT_BIT_SHIFTS	5
1187 #define IPSEC_REDUNDANT_BITS		(1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1188 #define IPSEC_BITMAP_LOC_MASK		(IPSEC_REDUNDANT_BITS - 1)
1189 
1190 int
1191 ipsec_chkreplay(uint32_t seq, struct secasvar *sav)
1192 {
1193 	const struct secreplay *replay;
1194 	uint32_t wsizeb;		/* Constant: window size. */
1195 	int index, bit_location;
1196 
1197 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1198 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1199 
1200 	replay = sav->replay;
1201 
1202 	/* No need to check replay if disabled. */
1203 	if (replay->wsize == 0)
1204 		return (1);
1205 
1206 	/* Constant. */
1207 	wsizeb = replay->wsize << 3;
1208 
1209 	/* Sequence number of 0 is invalid. */
1210 	if (seq == 0)
1211 		return (0);
1212 
1213 	/* First time is always okay. */
1214 	if (replay->count == 0)
1215 		return (1);
1216 
1217 	/* Larger sequences are okay. */
1218 	if (seq > replay->lastseq)
1219 		return (1);
1220 
1221 	/* Over range to check, i.e. too old or wrapped. */
1222 	if (replay->lastseq - seq >= wsizeb)
1223 		return (0);
1224 
1225 	/* The sequence is inside the sliding window
1226 	 * now check the bit in the bitmap
1227 	 * bit location only depends on the sequence number
1228 	 */
1229 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1230 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1231 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1232 
1233 	/* This packet already seen? */
1234 	if ((replay->bitmap)[index] & (1 << bit_location))
1235 		return (0);
1236 	return (1);
1237 }
1238 
1239 /*
1240  * Check replay counter whether to update or not.
1241  * OUT:	0:	OK
1242  *	1:	NG
1243  */
1244 int
1245 ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
1246 {
1247 	char buf[128];
1248 	struct secreplay *replay;
1249 	uint32_t wsizeb;		/* Constant: window size. */
1250 	int diff, index, bit_location;
1251 
1252 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1253 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1254 
1255 	replay = sav->replay;
1256 
1257 	if (replay->wsize == 0)
1258 		goto ok;	/* No need to check replay. */
1259 
1260 	/* Constant. */
1261 	wsizeb = replay->wsize << 3;
1262 
1263 	/* Sequence number of 0 is invalid. */
1264 	if (seq == 0)
1265 		return (1);
1266 
1267 	/* The packet is too old, no need to update */
1268 	if (wsizeb + seq < replay->lastseq)
1269 		goto ok;
1270 
1271 	/* Now update the bit */
1272 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS);
1273 
1274 	/* First check if the sequence number is in the range */
1275 	if (seq > replay->lastseq) {
1276 		int id;
1277 		int index_cur = replay->lastseq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1278 
1279 		diff = index - index_cur;
1280 		if (diff > replay->bitmap_size) {
1281 			/* something unusual in this case */
1282 			diff = replay->bitmap_size;
1283 		}
1284 
1285 		for (id = 0; id < diff; ++id) {
1286 			replay->bitmap[(id + index_cur + 1)
1287 			& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1288 		}
1289 
1290 		replay->lastseq = seq;
1291 	}
1292 
1293 	index &= IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1294 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1295 
1296 	/* this packet has already been received */
1297 	if (replay->bitmap[index] & (1 << bit_location))
1298 		return (1);
1299 
1300 	replay->bitmap[index] |= (1 << bit_location);
1301 
1302 ok:
1303 	if (replay->count == ~0) {
1304 
1305 		/* Set overflow flag. */
1306 		replay->overflow++;
1307 
1308 		/* Don't increment, no more packets accepted. */
1309 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1310 			if (sav->sah->saidx.proto == IPPROTO_AH)
1311 				AHSTAT_INC(ahs_wrap);
1312 			else if (sav->sah->saidx.proto == IPPROTO_ESP)
1313 				ESPSTAT_INC(esps_wrap);
1314 			return (1);
1315 		}
1316 
1317 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1318 		    __func__, replay->overflow,
1319 		    ipsec_sa2str(sav, buf, sizeof(buf))));
1320 	}
1321 	return (0);
1322 }
1323 
1324 int
1325 ipsec_updateid(struct secasvar *sav, uint64_t *new, uint64_t *old)
1326 {
1327 	uint64_t tmp;
1328 
1329 	/*
1330 	 * tdb_cryptoid is initialized by xform_init().
1331 	 * Then it can be changed only when some crypto error occurred or
1332 	 * when SA is deleted. We stored used cryptoid in the xform_data
1333 	 * structure. In case when crypto error occurred and crypto
1334 	 * subsystem has reinited the session, it returns new cryptoid
1335 	 * and EAGAIN error code.
1336 	 *
1337 	 * This function will be called when we got EAGAIN from crypto
1338 	 * subsystem.
1339 	 * *new is cryptoid that was returned by crypto subsystem in
1340 	 * the crp_sid.
1341 	 * *old is the original cryptoid that we stored in xform_data.
1342 	 *
1343 	 * For first failed request *old == sav->tdb_cryptoid, then
1344 	 * we update sav->tdb_cryptoid and redo crypto_dispatch().
1345 	 * For next failed request *old != sav->tdb_cryptoid, then
1346 	 * we store cryptoid from first request into the *new variable
1347 	 * and crp_sid from this second session will be returned via
1348 	 * *old pointer, so caller can release second session.
1349 	 *
1350 	 * XXXAE: check this more carefully.
1351 	 */
1352 	KEYDBG(IPSEC_STAMP,
1353 	    printf("%s: SA(%p) moves cryptoid %jd -> %jd\n",
1354 		__func__, sav, (uintmax_t)(*old), (uintmax_t)(*new)));
1355 	KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1356 	SECASVAR_LOCK(sav);
1357 	if (sav->tdb_cryptoid != *old) {
1358 		/* cryptoid was already updated */
1359 		tmp = *new;
1360 		*new = sav->tdb_cryptoid;
1361 		*old = tmp;
1362 		SECASVAR_UNLOCK(sav);
1363 		return (1);
1364 	}
1365 	sav->tdb_cryptoid = *new;
1366 	SECASVAR_UNLOCK(sav);
1367 	return (0);
1368 }
1369 
1370 int
1371 ipsec_initialized(void)
1372 {
1373 
1374 	return (V_def_policy != NULL);
1375 }
1376 
1377 static void
1378 def_policy_init(const void *unused __unused)
1379 {
1380 
1381 	V_def_policy = key_newsp();
1382 	if (V_def_policy != NULL) {
1383 		V_def_policy->policy = IPSEC_POLICY_NONE;
1384 		/* Force INPCB SP cache invalidation */
1385 		key_bumpspgen();
1386 	} else
1387 		printf("%s: failed to initialize default policy\n", __func__);
1388 }
1389 
1390 
1391 static void
1392 def_policy_uninit(const void *unused __unused)
1393 {
1394 
1395 	if (V_def_policy != NULL) {
1396 		key_freesp(&V_def_policy);
1397 		key_bumpspgen();
1398 	}
1399 }
1400 
1401 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1402     def_policy_init, NULL);
1403 VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1404     def_policy_uninit, NULL);
1405