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