xref: /freebsd/sys/netipsec/ipsec.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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_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 	int result;
641 
642 	sp = ipsec4_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
643 	result = ipsec_in_reject(sp, inp, m);
644 	key_freesp(&sp);
645 	if (result != 0)
646 		IPSECSTAT_INC(ips_in_polvio);
647 	return (result);
648 }
649 
650 /*
651  * IPSEC_CAP() method implementation for IPv4.
652  */
653 int
654 ipsec4_capability(struct mbuf *m, u_int cap)
655 {
656 
657 	switch (cap) {
658 	case IPSEC_CAP_BYPASS_FILTER:
659 		/*
660 		 * Bypass packet filtering for packets previously handled
661 		 * by IPsec.
662 		 */
663 		if (!V_ip4_filtertunnel &&
664 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
665 			return (1);
666 		return (0);
667 	case IPSEC_CAP_OPERABLE:
668 		/* Do we have active security policies? */
669 		return (key_havesp_any());
670 	};
671 	return (EOPNOTSUPP);
672 }
673 
674 #endif /* INET */
675 
676 #ifdef INET6
677 static void
678 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
679     int needport)
680 {
681 	struct tcphdr th;
682 	struct udphdr uh;
683 	struct icmp6_hdr ih;
684 	int off, nxt;
685 
686 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
687 	    ("packet too short"));
688 
689 	/* Set default. */
690 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
691 	spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
692 	spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
693 
694 	nxt = -1;
695 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
696 	if (off < 0 || m->m_pkthdr.len < off)
697 		return;
698 
699 	switch (nxt) {
700 	case IPPROTO_TCP:
701 		spidx->ul_proto = nxt;
702 		if (!needport)
703 			break;
704 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
705 			break;
706 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
707 		spidx->src.sin6.sin6_port = th.th_sport;
708 		spidx->dst.sin6.sin6_port = th.th_dport;
709 		break;
710 	case IPPROTO_UDP:
711 		spidx->ul_proto = nxt;
712 		if (!needport)
713 			break;
714 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
715 			break;
716 		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
717 		spidx->src.sin6.sin6_port = uh.uh_sport;
718 		spidx->dst.sin6.sin6_port = uh.uh_dport;
719 		break;
720 	case IPPROTO_ICMPV6:
721 		spidx->ul_proto = nxt;
722 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
723 			break;
724 		m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
725 		spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
726 		spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
727 		break;
728 	default:
729 		/* XXX Intermediate headers??? */
730 		spidx->ul_proto = nxt;
731 		break;
732 	}
733 	KEYDBG(IPSEC_DUMP,
734 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
735 }
736 
737 static void
738 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
739 {
740 
741 	ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
742 	spidx->prefs = sizeof(struct in6_addr) << 3;
743 	spidx->prefd = sizeof(struct in6_addr) << 3;
744 }
745 
746 static struct secpolicy *
747 ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
748     int needport)
749 {
750 	struct secpolicyindex spidx;
751 	struct secpolicy *sp;
752 
753 	sp = ipsec_getpcbpolicy(inp, dir);
754 	if (sp == NULL && key_havesp(dir)) {
755 		/* Make an index to look for a policy. */
756 		ipsec6_setspidx_ipaddr(m, &spidx);
757 		ipsec6_get_ulp(m, &spidx, needport);
758 		spidx.dir = dir;
759 		sp = key_allocsp(&spidx, dir);
760 	}
761 	if (sp == NULL)		/* No SP found, use system default. */
762 		sp = key_allocsp_default();
763 	return (sp);
764 }
765 
766 /*
767  * Check security policy for *OUTBOUND* IPv6 packet.
768  */
769 struct secpolicy *
770 ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
771     int needport)
772 {
773 	struct secpolicy *sp;
774 
775 	*error = 0;
776 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
777 	if (sp != NULL)
778 		sp = ipsec_checkpolicy(sp, inp, error);
779 	if (sp == NULL) {
780 		switch (*error) {
781 		case 0: /* No IPsec required: BYPASS or NONE */
782 			break;
783 		case -EINVAL:
784 			IPSEC6STAT_INC(ips_out_polvio);
785 			break;
786 		default:
787 			IPSEC6STAT_INC(ips_out_inval);
788 		}
789 	}
790 	KEYDBG(IPSEC_STAMP,
791 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
792 	if (sp != NULL)
793 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
794 	return (sp);
795 }
796 
797 /*
798  * Check IPv6 packet against inbound security policy.
799  * This function is called from tcp6_input(), udp6_input(),
800  * rip6_input() and sctp_input().
801  */
802 int
803 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
804 {
805 	struct secpolicy *sp;
806 	int result;
807 
808 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
809 	result = ipsec_in_reject(sp, inp, m);
810 	key_freesp(&sp);
811 	if (result)
812 		IPSEC6STAT_INC(ips_in_polvio);
813 	return (result);
814 }
815 
816 /*
817  * IPSEC_CAP() method implementation for IPv6.
818  */
819 int
820 ipsec6_capability(struct mbuf *m, u_int cap)
821 {
822 
823 	switch (cap) {
824 	case IPSEC_CAP_BYPASS_FILTER:
825 		/*
826 		 * Bypass packet filtering for packets previously handled
827 		 * by IPsec.
828 		 */
829 		if (!V_ip6_filtertunnel &&
830 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
831 			return (1);
832 		return (0);
833 	case IPSEC_CAP_OPERABLE:
834 		/* Do we have active security policies? */
835 		return (key_havesp_any());
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  * rejected as "invalid"; otherwise 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 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 #define IPSEC_BITMAP_INDEX_MASK(w)	(w - 1)
1176 #define IPSEC_REDUNDANT_BIT_SHIFTS	5
1177 #define IPSEC_REDUNDANT_BITS		(1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1178 #define IPSEC_BITMAP_LOC_MASK		(IPSEC_REDUNDANT_BITS - 1)
1179 
1180 /*
1181  * Functions below are responsible for checking and updating bitmap.
1182  * These are used to separate ipsec_chkreplay() and ipsec_updatereplay()
1183  * from window implementation
1184  *
1185  * Based on RFC 6479. Blocks are 32 bits unsigned integers
1186  */
1187 
1188 static inline int
1189 check_window(const struct secreplay *replay, uint64_t seq)
1190 {
1191 	int index, bit_location;
1192 
1193 	SECREPLAY_ASSERT(replay);
1194 
1195 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1196 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1197 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1198 
1199 	/* This packet already seen? */
1200 	return ((replay->bitmap)[index] & (1 << bit_location));
1201 }
1202 
1203 static inline void
1204 advance_window(const struct secreplay *replay, uint64_t seq)
1205 {
1206 	int i;
1207 	uint64_t index, index_cur, diff;
1208 
1209 	SECREPLAY_ASSERT(replay);
1210 
1211 	index_cur = replay->last >> IPSEC_REDUNDANT_BIT_SHIFTS;
1212 	index = seq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1213 	diff = index - index_cur;
1214 
1215 	if (diff > replay->bitmap_size) {
1216 		/* something unusual in this case */
1217 		diff = replay->bitmap_size;
1218 	}
1219 
1220 	for (i = 0; i < diff; i++) {
1221 		replay->bitmap[(i + index_cur + 1)
1222 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1223 	}
1224 }
1225 
1226 static inline void
1227 set_window(const struct secreplay *replay, uint64_t seq)
1228 {
1229 	int index, bit_location;
1230 
1231 	SECREPLAY_ASSERT(replay);
1232 
1233 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1234 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1235 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1236 
1237 	replay->bitmap[index] |= (1 << bit_location);
1238 }
1239 
1240 /*
1241  * Check the variable replay window.
1242  * ipsec_chkreplay() performs replay check before ICV verification.
1243  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1244  * ICV verification (it also performs replay check, which is usually done
1245  * beforehand).
1246  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1247  *
1248  * Based on RFC 4303
1249  */
1250 
1251 int
1252 ipsec_chkreplay(uint32_t seq, uint32_t *seqhigh, struct secasvar *sav)
1253 {
1254 	char buf[128];
1255 	struct secreplay *replay;
1256 	uint32_t window;
1257 	uint32_t tl, th, bl;
1258 	uint32_t seqh;
1259 
1260 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1261 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1262 
1263 	replay = sav->replay;
1264 
1265 	/* No need to check replay if disabled. */
1266 	if (replay->wsize == 0) {
1267 		return (1);
1268 	}
1269 
1270 	SECREPLAY_LOCK(replay);
1271 
1272 	/* Zero sequence number is not allowed. */
1273 	if (seq == 0 && replay->last == 0) {
1274 		SECREPLAY_UNLOCK(replay);
1275 		return (0);
1276 	}
1277 
1278 	window = replay->wsize << 3;		/* Size of window */
1279 	tl = (uint32_t)replay->last;		/* Top of window, lower part */
1280 	th = (uint32_t)(replay->last >> 32);	/* Top of window, high part */
1281 	bl = tl - window + 1;			/* Bottom of window, lower part */
1282 
1283 	/*
1284 	 * We keep the high part intact when:
1285 	 * 1) the seq is within [bl, 0xffffffff] and the whole window is
1286 	 *    within one subspace;
1287 	 * 2) the seq is within [0, bl) and window spans two subspaces.
1288 	 */
1289 	if ((tl >= window - 1 && seq >= bl) ||
1290 	    (tl < window - 1 && seq < bl)) {
1291 		*seqhigh = th;
1292 		if (seq <= tl) {
1293 			/* Sequence number inside window - check against replay */
1294 			if (check_window(replay, seq)) {
1295 				SECREPLAY_UNLOCK(replay);
1296 				return (0);
1297 			}
1298 		}
1299 
1300 		SECREPLAY_UNLOCK(replay);
1301 		/* Sequence number above top of window or not found in bitmap */
1302 		return (1);
1303 	}
1304 
1305 	/*
1306 	 * If ESN is not enabled and packet with highest sequence number
1307 	 * was received we should report overflow
1308 	 */
1309 	if (tl == 0xffffffff && !(sav->flags & SADB_X_SAFLAGS_ESN)) {
1310 		/* Set overflow flag. */
1311 		replay->overflow++;
1312 
1313 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1314 			if (sav->sah->saidx.proto == IPPROTO_ESP)
1315 				ESPSTAT_INC(esps_wrap);
1316 			else if (sav->sah->saidx.proto == IPPROTO_AH)
1317 				AHSTAT_INC(ahs_wrap);
1318 			SECREPLAY_UNLOCK(replay);
1319 			return (0);
1320 		}
1321 
1322 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1323 		    __func__, replay->overflow,
1324 		    ipsec_sa2str(sav, buf, sizeof(buf))));
1325 	}
1326 
1327 	/*
1328 	 * Seq is within [bl, 0xffffffff] and bl is within
1329 	 * [0xffffffff-window, 0xffffffff].  This means we got a seq
1330 	 * which is within our replay window, but in the previous
1331 	 * subspace.
1332 	 */
1333 	if (tl < window - 1 && seq >= bl) {
1334 		if (th == 0)
1335 			return (0);
1336 		*seqhigh = th - 1;
1337 		seqh = th - 1;
1338 		if (check_window(replay, seq)) {
1339 			SECREPLAY_UNLOCK(replay);
1340 			return (0);
1341 		}
1342 		SECREPLAY_UNLOCK(replay);
1343 		return (1);
1344 	}
1345 
1346 	/*
1347 	 * Seq is within [0, bl) but the whole window is within one subspace.
1348 	 * This means that seq has wrapped and is in next subspace
1349 	 */
1350 	*seqhigh = th + 1;
1351 	seqh = th + 1;
1352 
1353 	/* Don't let high part wrap. */
1354 	if (seqh == 0) {
1355 		/* Set overflow flag. */
1356 		replay->overflow++;
1357 
1358 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1359 			if (sav->sah->saidx.proto == IPPROTO_ESP)
1360 				ESPSTAT_INC(esps_wrap);
1361 			else if (sav->sah->saidx.proto == IPPROTO_AH)
1362 				AHSTAT_INC(ahs_wrap);
1363 			SECREPLAY_UNLOCK(replay);
1364 			return (0);
1365 		}
1366 
1367 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1368 		    __func__, replay->overflow,
1369 		    ipsec_sa2str(sav, buf, sizeof(buf))));
1370 	}
1371 
1372 	SECREPLAY_UNLOCK(replay);
1373 	return (1);
1374 }
1375 
1376 /*
1377  * Check replay counter whether to update or not.
1378  * OUT:	0:	OK
1379  *	1:	NG
1380  */
1381 int
1382 ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
1383 {
1384 	struct secreplay *replay;
1385 	uint32_t window;
1386 	uint32_t tl, th, bl;
1387 	uint32_t seqh;
1388 
1389 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1390 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1391 
1392 	replay = sav->replay;
1393 
1394 	/* No need to check replay if disabled. */
1395 	if (replay->wsize == 0)
1396 		return (0);
1397 
1398 	SECREPLAY_LOCK(replay);
1399 
1400 	/* Zero sequence number is not allowed. */
1401 	if (seq == 0 && replay->last == 0) {
1402 		SECREPLAY_UNLOCK(replay);
1403 		return (1);
1404 	}
1405 
1406 	window = replay->wsize << 3;		/* Size of window */
1407 	tl = (uint32_t)replay->last;		/* Top of window, lower part */
1408 	th = (uint32_t)(replay->last >> 32);	/* Top of window, high part */
1409 	bl = tl - window + 1;			/* Bottom of window, lower part */
1410 
1411 	/*
1412 	 * We keep the high part intact when:
1413 	 * 1) the seq is within [bl, 0xffffffff] and the whole window is
1414 	 *    within one subspace;
1415 	 * 2) the seq is within [0, bl) and window spans two subspaces.
1416 	 */
1417 	if ((tl >= window - 1 && seq >= bl) ||
1418 	    (tl < window - 1 && seq < bl)) {
1419 		seqh = th;
1420 		if (seq <= tl) {
1421 			/* Sequence number inside window - check against replay */
1422 			if (check_window(replay, seq)) {
1423 				SECREPLAY_UNLOCK(replay);
1424 				return (1);
1425 			}
1426 			set_window(replay, seq);
1427 		} else {
1428 			advance_window(replay, ((uint64_t)seqh << 32) | seq);
1429 			set_window(replay, seq);
1430 			replay->last = ((uint64_t)seqh << 32) | seq;
1431 		}
1432 
1433 		/* Sequence number above top of window or not found in bitmap */
1434 		replay->count++;
1435 		SECREPLAY_UNLOCK(replay);
1436 		return (0);
1437 	}
1438 
1439 	if (!(sav->flags & SADB_X_SAFLAGS_ESN)) {
1440 		SECREPLAY_UNLOCK(replay);
1441 		return (1);
1442 	}
1443 
1444 	/*
1445 	 * Seq is within [bl, 0xffffffff] and bl is within
1446 	 * [0xffffffff-window, 0xffffffff].  This means we got a seq
1447 	 * which is within our replay window, but in the previous
1448 	 * subspace.
1449 	 */
1450 	if (tl < window - 1 && seq >= bl) {
1451 		if (th == 0) {
1452 			SECREPLAY_UNLOCK(replay);
1453 			return (1);
1454 		}
1455 		if (check_window(replay, seq)) {
1456 			SECREPLAY_UNLOCK(replay);
1457 			return (1);
1458 		}
1459 
1460 		set_window(replay, seq);
1461 		replay->count++;
1462 		SECREPLAY_UNLOCK(replay);
1463 		return (0);
1464 	}
1465 
1466 	/*
1467 	 * Seq is within [0, bl) but the whole window is within one subspace.
1468 	 * This means that seq has wrapped and is in next subspace
1469 	 */
1470 	seqh = th + 1;
1471 
1472 	/* Don't let high part wrap. */
1473 	if (seqh == 0) {
1474 		SECREPLAY_UNLOCK(replay);
1475 		return (1);
1476 	}
1477 
1478 	advance_window(replay, ((uint64_t)seqh << 32) | seq);
1479 	set_window(replay, seq);
1480 	replay->last = ((uint64_t)seqh << 32) | seq;
1481 	replay->count++;
1482 
1483 	SECREPLAY_UNLOCK(replay);
1484 	return (0);
1485 }
1486 int
1487 ipsec_updateid(struct secasvar *sav, crypto_session_t *new,
1488     crypto_session_t *old)
1489 {
1490 	crypto_session_t tmp;
1491 
1492 	/*
1493 	 * tdb_cryptoid is initialized by xform_init().
1494 	 * Then it can be changed only when some crypto error occurred or
1495 	 * when SA is deleted. We stored used cryptoid in the xform_data
1496 	 * structure. In case when crypto error occurred and crypto
1497 	 * subsystem has reinited the session, it returns new cryptoid
1498 	 * and EAGAIN error code.
1499 	 *
1500 	 * This function will be called when we got EAGAIN from crypto
1501 	 * subsystem.
1502 	 * *new is cryptoid that was returned by crypto subsystem in
1503 	 * the crp_sid.
1504 	 * *old is the original cryptoid that we stored in xform_data.
1505 	 *
1506 	 * For first failed request *old == sav->tdb_cryptoid, then
1507 	 * we update sav->tdb_cryptoid and redo crypto_dispatch().
1508 	 * For next failed request *old != sav->tdb_cryptoid, then
1509 	 * we store cryptoid from first request into the *new variable
1510 	 * and crp_sid from this second session will be returned via
1511 	 * *old pointer, so caller can release second session.
1512 	 *
1513 	 * XXXAE: check this more carefully.
1514 	 */
1515 	KEYDBG(IPSEC_STAMP,
1516 	    printf("%s: SA(%p) moves cryptoid %p -> %p\n",
1517 		__func__, sav, *old, *new));
1518 	KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1519 	SECASVAR_WLOCK(sav);
1520 	if (sav->tdb_cryptoid != *old) {
1521 		/* cryptoid was already updated */
1522 		tmp = *new;
1523 		*new = sav->tdb_cryptoid;
1524 		*old = tmp;
1525 		SECASVAR_WUNLOCK(sav);
1526 		return (1);
1527 	}
1528 	sav->tdb_cryptoid = *new;
1529 	SECASVAR_WUNLOCK(sav);
1530 	return (0);
1531 }
1532 
1533 int
1534 ipsec_initialized(void)
1535 {
1536 
1537 	return (V_def_policy != NULL);
1538 }
1539 
1540 static void
1541 def_policy_init(const void *unused __unused)
1542 {
1543 
1544 	V_def_policy = key_newsp();
1545 	if (V_def_policy != NULL) {
1546 		V_def_policy->policy = IPSEC_POLICY_NONE;
1547 		/* Force INPCB SP cache invalidation */
1548 		key_bumpspgen();
1549 	} else
1550 		printf("%s: failed to initialize default policy\n", __func__);
1551 }
1552 
1553 static void
1554 def_policy_uninit(const void *unused __unused)
1555 {
1556 
1557 	if (V_def_policy != NULL) {
1558 		key_freesp(&V_def_policy);
1559 		key_bumpspgen();
1560 	}
1561 }
1562 
1563 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1564     def_policy_init, NULL);
1565 VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1566     def_policy_uninit, NULL);
1567