xref: /freebsd/sys/netipsec/ipsec.c (revision 0ff2d00d2aa37cd883ffd8c7363dddef9cba267e)
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
sysctl_def_policy(SYSCTL_HANDLER_ARGS)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 /* net.inet.ipsec */
176 SYSCTL_PROC(_net_inet_ipsec, IPSECCTL_DEF_POLICY, def_policy,
177     CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
178     0, 0, sysctl_def_policy, "I",
179     "IPsec default policy.");
180 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
181 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_trans_deflev), 0,
182 	"Default ESP transport mode level");
183 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
184 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_esp_net_deflev), 0,
185 	"Default ESP tunnel mode level.");
186 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
187 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_trans_deflev), 0,
188 	"AH transfer mode default level.");
189 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
190 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ah_net_deflev), 0,
191 	"AH tunnel mode default level.");
192 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_AH_CLEARTOS, ah_cleartos,
193 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ah_cleartos), 0,
194 	"If set, clear type-of-service field when doing AH computation.");
195 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_DFBIT, dfbit,
196 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_dfbit), 0,
197 	"Do not fragment bit on encap.");
198 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_MIN_PMTU, min_pmtu,
199 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_min_pmtu), 0,
200 	"Lowest acceptable PMTU value.");
201 SYSCTL_INT(_net_inet_ipsec, IPSECCTL_ECN, ecn,
202 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_ipsec_ecn), 0,
203 	"Explicit Congestion Notification handling.");
204 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, crypto_support,
205 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(crypto_support), 0,
206 	"Crypto driver selection.");
207 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, async_crypto,
208 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(async_crypto), 0,
209 	"Use asynchronous mode to parallelize crypto jobs.");
210 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, check_policy_history,
211 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(check_policy_history), 0,
212 	"Use strict check of inbound packets to security policy compliance.");
213 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, natt_cksum_policy,
214 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(natt_cksum_policy), 0,
215 	"Method to fix TCP/UDP checksum for transport mode IPsec after NAT.");
216 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, filtertunnel,
217 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip4_filtertunnel), 0,
218 	"If set, filter packets from an IPsec tunnel.");
219 SYSCTL_VNET_PCPUSTAT(_net_inet_ipsec, OID_AUTO, ipsecstats, struct ipsecstat,
220     ipsec4stat, "IPsec IPv4 statistics.");
221 
222 #ifdef REGRESSION
223 /*
224  * When set to 1, IPsec will send packets with the same sequence number.
225  * This allows to verify if the other side has proper replay attacks detection.
226  */
227 VNET_DEFINE(int, ipsec_replay) = 0;
228 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_replay,
229 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_replay), 0,
230 	"Emulate replay attack");
231 /*
232  * When set 1, IPsec will send packets with corrupted HMAC.
233  * This allows to verify if the other side properly detects modified packets.
234  */
235 VNET_DEFINE(int, ipsec_integrity) = 0;
236 SYSCTL_INT(_net_inet_ipsec, OID_AUTO, test_integrity,
237 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ipsec_integrity), 0,
238 	"Emulate man-in-the-middle attack");
239 #endif
240 
241 #ifdef INET6
242 VNET_PCPUSTAT_DEFINE(struct ipsecstat, ipsec6stat);
243 VNET_PCPUSTAT_SYSINIT(ipsec6stat);
244 
245 #ifdef VIMAGE
246 VNET_PCPUSTAT_SYSUNINIT(ipsec6stat);
247 #endif /* VIMAGE */
248 
249 VNET_DEFINE(int, ip6_esp_trans_deflev) = IPSEC_LEVEL_USE;
250 VNET_DEFINE(int, ip6_esp_net_deflev) = IPSEC_LEVEL_USE;
251 VNET_DEFINE(int, ip6_ah_trans_deflev) = IPSEC_LEVEL_USE;
252 VNET_DEFINE(int, ip6_ah_net_deflev) = IPSEC_LEVEL_USE;
253 VNET_DEFINE(int, ip6_ipsec_ecn) = 0;	/* ECN ignore(-1)/forbidden(0)/allowed(1) */
254 
255 VNET_DEFINE_STATIC(int, ip6_filtertunnel) = 0;
256 #define	V_ip6_filtertunnel	VNET(ip6_filtertunnel)
257 
258 /* net.inet6.ipsec6 */
259 SYSCTL_PROC(_net_inet6_ipsec6, IPSECCTL_DEF_POLICY, def_policy,
260     CTLTYPE_INT | CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
261     0, 0, sysctl_def_policy, "I",
262     "IPsec default policy.");
263 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_TRANSLEV, esp_trans_deflev,
264 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_trans_deflev), 0,
265 	"Default ESP transport mode level.");
266 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_ESP_NETLEV, esp_net_deflev,
267 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_esp_net_deflev), 0,
268 	"Default ESP tunnel mode level.");
269 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_TRANSLEV, ah_trans_deflev,
270 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_trans_deflev), 0,
271 	"AH transfer mode default level.");
272 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_DEF_AH_NETLEV, ah_net_deflev,
273 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ah_net_deflev), 0,
274 	"AH tunnel mode default level.");
275 SYSCTL_INT(_net_inet6_ipsec6, IPSECCTL_ECN, ecn,
276 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_ipsec_ecn), 0,
277 	"Explicit Congestion Notification handling.");
278 SYSCTL_INT(_net_inet6_ipsec6, OID_AUTO, filtertunnel,
279 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_filtertunnel),  0,
280 	"If set, filter packets from an IPsec tunnel.");
281 SYSCTL_VNET_PCPUSTAT(_net_inet6_ipsec6, IPSECCTL_STATS, ipsecstats,
282     struct ipsecstat, ipsec6stat, "IPsec IPv6 statistics.");
283 #endif /* INET6 */
284 
285 static int ipsec_in_reject(struct secpolicy *, struct inpcb *,
286     const struct mbuf *);
287 
288 #ifdef INET
289 static void ipsec4_get_ulp(const struct mbuf *, const struct ip *,
290     struct secpolicyindex *, int);
291 static void ipsec4_setspidx_ipaddr(const struct mbuf *, struct ip *,
292     struct secpolicyindex *);
293 #endif
294 #ifdef INET6
295 static void ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *, int);
296 static void ipsec6_setspidx_ipaddr(const struct mbuf *,
297     struct secpolicyindex *);
298 #endif
299 
300 /*
301  * Return a held reference to the default SP.
302  */
303 static struct secpolicy *
key_allocsp_default(void)304 key_allocsp_default(void)
305 {
306 
307 	key_addref(V_def_policy);
308 	return (V_def_policy);
309 }
310 
311 static void
ipsec_invalidate_cache(struct inpcb * inp,u_int dir)312 ipsec_invalidate_cache(struct inpcb *inp, u_int dir)
313 {
314 	struct secpolicy *sp;
315 
316 	INP_WLOCK_ASSERT(inp);
317 	if (dir == IPSEC_DIR_OUTBOUND) {
318 		if (inp->inp_sp->flags & INP_INBOUND_POLICY)
319 			return;
320 		sp = inp->inp_sp->sp_in;
321 		inp->inp_sp->sp_in = NULL;
322 	} else {
323 		if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
324 			return;
325 		sp = inp->inp_sp->sp_out;
326 		inp->inp_sp->sp_out = NULL;
327 	}
328 	if (sp != NULL)
329 		key_freesp(&sp); /* release extra reference */
330 }
331 
332 static void
ipsec_cachepolicy(struct inpcb * inp,struct secpolicy * sp,u_int dir)333 ipsec_cachepolicy(struct inpcb *inp, struct secpolicy *sp, u_int dir)
334 {
335 	uint32_t genid;
336 	int downgrade;
337 
338 	INP_LOCK_ASSERT(inp);
339 
340 	if (dir == IPSEC_DIR_OUTBOUND) {
341 		/* Do we have configured PCB policy? */
342 		if (inp->inp_sp->flags & INP_OUTBOUND_POLICY)
343 			return;
344 		/* Another thread has already set cached policy */
345 		if (inp->inp_sp->sp_out != NULL)
346 			return;
347 		/*
348 		 * Do not cache OUTBOUND policy if PCB isn't connected,
349 		 * i.e. foreign address is INADDR_ANY/UNSPECIFIED.
350 		 */
351 #ifdef INET
352 		if ((inp->inp_vflag & INP_IPV4) != 0 &&
353 		    inp->inp_faddr.s_addr == INADDR_ANY)
354 			return;
355 #endif
356 #ifdef INET6
357 		if ((inp->inp_vflag & INP_IPV6) != 0 &&
358 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
359 			return;
360 #endif
361 	} else {
362 		/* Do we have configured PCB policy? */
363 		if (inp->inp_sp->flags & INP_INBOUND_POLICY)
364 			return;
365 		/* Another thread has already set cached policy */
366 		if (inp->inp_sp->sp_in != NULL)
367 			return;
368 		/*
369 		 * Do not cache INBOUND policy for listen socket,
370 		 * that is bound to INADDR_ANY/UNSPECIFIED address.
371 		 */
372 #ifdef INET
373 		if ((inp->inp_vflag & INP_IPV4) != 0 &&
374 		    inp->inp_faddr.s_addr == INADDR_ANY)
375 			return;
376 #endif
377 #ifdef INET6
378 		if ((inp->inp_vflag & INP_IPV6) != 0 &&
379 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
380 			return;
381 #endif
382 	}
383 	downgrade = 0;
384 	if (!INP_WLOCKED(inp)) {
385 		if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
386 			return;
387 	}
388 	if (dir == IPSEC_DIR_OUTBOUND)
389 		inp->inp_sp->sp_out = sp;
390 	else
391 		inp->inp_sp->sp_in = sp;
392 	/*
393 	 * SP is already referenced by the lookup code.
394 	 * We take extra reference here to avoid race in the
395 	 * ipsec_getpcbpolicy() function - SP will not be freed in the
396 	 * time between we take SP pointer from the cache and key_addref()
397 	 * call.
398 	 */
399 	key_addref(sp);
400 	genid = key_getspgen();
401 	if (genid != inp->inp_sp->genid) {
402 		ipsec_invalidate_cache(inp, dir);
403 		inp->inp_sp->genid = genid;
404 	}
405 	KEYDBG(IPSEC_STAMP,
406 	    printf("%s: PCB(%p): cached %s SP(%p)\n",
407 	    __func__, inp, dir == IPSEC_DIR_OUTBOUND ? "OUTBOUND":
408 	    "INBOUND", sp));
409 	if (downgrade != 0)
410 		INP_DOWNGRADE(inp);
411 }
412 
413 static struct secpolicy *
ipsec_checkpolicy(struct secpolicy * sp,struct inpcb * inp,int * error)414 ipsec_checkpolicy(struct secpolicy *sp, struct inpcb *inp, int *error)
415 {
416 
417 	/* Save found OUTBOUND policy into PCB SP cache. */
418 	if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_out == NULL)
419 		ipsec_cachepolicy(inp, sp, IPSEC_DIR_OUTBOUND);
420 
421 	switch (sp->policy) {
422 	default:
423 		printf("%s: invalid policy %u\n", __func__, sp->policy);
424 		/* FALLTHROUGH */
425 	case IPSEC_POLICY_DISCARD:
426 		*error = -EINVAL;	/* Packet is discarded by caller. */
427 		/* FALLTHROUGH */
428 	case IPSEC_POLICY_BYPASS:
429 	case IPSEC_POLICY_NONE:
430 		key_freesp(&sp);
431 		sp = NULL;		/* NB: force NULL result. */
432 		break;
433 	case IPSEC_POLICY_IPSEC:
434 		/* XXXAE: handle LARVAL SP */
435 		break;
436 	}
437 	KEYDBG(IPSEC_DUMP,
438 	    printf("%s: get SP(%p), error %d\n", __func__, sp, *error));
439 	return (sp);
440 }
441 
442 static struct secpolicy *
ipsec_getpcbpolicy(struct inpcb * inp,u_int dir)443 ipsec_getpcbpolicy(struct inpcb *inp, u_int dir)
444 {
445 	struct secpolicy *sp;
446 	int flags, downgrade;
447 
448 	if (inp == NULL || inp->inp_sp == NULL)
449 		return (NULL);
450 
451 	INP_LOCK_ASSERT(inp);
452 
453 	flags = inp->inp_sp->flags;
454 	if (dir == IPSEC_DIR_OUTBOUND) {
455 		sp = inp->inp_sp->sp_out;
456 		flags &= INP_OUTBOUND_POLICY;
457 	} else {
458 		sp = inp->inp_sp->sp_in;
459 		flags &= INP_INBOUND_POLICY;
460 	}
461 	/*
462 	 * Check flags. If we have PCB SP, just return it.
463 	 * Otherwise we need to check that cached SP entry isn't stale.
464 	 */
465 	if (flags == 0) {
466 		if (sp == NULL)
467 			return (NULL);
468 		if (inp->inp_sp->genid != key_getspgen()) {
469 			/* Invalidate the cache. */
470 			downgrade = 0;
471 			if (!INP_WLOCKED(inp)) {
472 				if ((downgrade = INP_TRY_UPGRADE(inp)) == 0)
473 					return (NULL);
474 			}
475 			ipsec_invalidate_cache(inp, IPSEC_DIR_OUTBOUND);
476 			ipsec_invalidate_cache(inp, IPSEC_DIR_INBOUND);
477 			if (downgrade != 0)
478 				INP_DOWNGRADE(inp);
479 			return (NULL);
480 		}
481 		KEYDBG(IPSEC_STAMP,
482 		    printf("%s: PCB(%p): cache hit SP(%p)\n",
483 		    __func__, inp, sp));
484 		/* Return referenced cached policy */
485 	}
486 	key_addref(sp);
487 	return (sp);
488 }
489 
490 #ifdef INET
491 static void
ipsec4_get_ulp(const struct mbuf * m,const struct ip * ip1,struct secpolicyindex * spidx,int needport)492 ipsec4_get_ulp(const struct mbuf *m, const struct ip *ip1,
493     struct secpolicyindex *spidx, int needport)
494 {
495 	uint8_t nxt;
496 	int off;
497 
498 	/* Sanity check. */
499 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip),
500 	    ("packet too short"));
501 
502 	if (ip1->ip_off & htons(IP_MF | IP_OFFMASK))
503 		goto done;
504 	off = ip1->ip_hl << 2;
505 	nxt = ip1->ip_p;
506 
507 	while (off < m->m_pkthdr.len) {
508 		struct ip6_ext ip6e;
509 		struct tcphdr th;
510 		struct udphdr uh;
511 
512 		switch (nxt) {
513 		case IPPROTO_TCP:
514 			spidx->ul_proto = nxt;
515 			if (!needport)
516 				goto done_proto;
517 			if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
518 				goto done;
519 			m_copydata(m, off, sizeof (th), (caddr_t) &th);
520 			spidx->src.sin.sin_port = th.th_sport;
521 			spidx->dst.sin.sin_port = th.th_dport;
522 			return;
523 		case IPPROTO_UDP:
524 			spidx->ul_proto = nxt;
525 			if (!needport)
526 				goto done_proto;
527 			if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
528 				goto done;
529 			m_copydata(m, off, sizeof (uh), (caddr_t) &uh);
530 			spidx->src.sin.sin_port = uh.uh_sport;
531 			spidx->dst.sin.sin_port = uh.uh_dport;
532 			return;
533 		case IPPROTO_AH:
534 			if (off + sizeof(ip6e) > m->m_pkthdr.len)
535 				goto done;
536 			/* XXX Sigh, this works but is totally bogus. */
537 			m_copydata(m, off, sizeof(ip6e), (caddr_t) &ip6e);
538 			off += (ip6e.ip6e_len + 2) << 2;
539 			nxt = ip6e.ip6e_nxt;
540 			break;
541 		case IPPROTO_ICMP:
542 		default:
543 			/* XXX Intermediate headers??? */
544 			spidx->ul_proto = nxt;
545 			goto done_proto;
546 		}
547 	}
548 done:
549 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
550 done_proto:
551 	spidx->src.sin.sin_port = IPSEC_PORT_ANY;
552 	spidx->dst.sin.sin_port = IPSEC_PORT_ANY;
553 	KEYDBG(IPSEC_DUMP,
554 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
555 }
556 
557 static void
ipsec4_setspidx_ipaddr(const struct mbuf * m,struct ip * ip1,struct secpolicyindex * spidx)558 ipsec4_setspidx_ipaddr(const struct mbuf *m, struct ip *ip1,
559     struct secpolicyindex *spidx)
560 {
561 
562 	ipsec4_setsockaddrs(m, ip1, &spidx->src, &spidx->dst);
563 	spidx->prefs = sizeof(struct in_addr) << 3;
564 	spidx->prefd = sizeof(struct in_addr) << 3;
565 }
566 
567 static struct secpolicy *
ipsec4_getpolicy(const struct mbuf * m,struct inpcb * inp,struct ip * ip1,u_int dir,int needport)568 ipsec4_getpolicy(const struct mbuf *m, struct inpcb *inp, struct ip *ip1,
569     u_int dir, int needport)
570 {
571 	struct secpolicyindex spidx;
572 	struct secpolicy *sp;
573 
574 	sp = ipsec_getpcbpolicy(inp, dir);
575 	if (sp == NULL && key_havesp(dir)) {
576 		/* Make an index to look for a policy. */
577 		ipsec4_setspidx_ipaddr(m, ip1, &spidx);
578 		ipsec4_get_ulp(m, ip1, &spidx, needport);
579 		spidx.dir = dir;
580 		sp = key_allocsp(&spidx, dir);
581 	}
582 	if (sp == NULL)		/* No SP found, use system default. */
583 		sp = key_allocsp_default();
584 	return (sp);
585 }
586 
587 /*
588  * Check security policy for *OUTBOUND* IPv4 packet.
589  */
590 struct secpolicy *
ipsec4_checkpolicy(const struct mbuf * m,struct inpcb * inp,struct ip * ip1,int * error,int needport)591 ipsec4_checkpolicy(const struct mbuf *m, struct inpcb *inp, struct ip *ip1,
592     int *error, int needport)
593 {
594 	struct secpolicy *sp;
595 
596 	*error = 0;
597 	sp = ipsec4_getpolicy(m, inp, ip1, IPSEC_DIR_OUTBOUND, needport);
598 	if (sp != NULL)
599 		sp = ipsec_checkpolicy(sp, inp, error);
600 	if (sp == NULL) {
601 		switch (*error) {
602 		case 0: /* No IPsec required: BYPASS or NONE */
603 			break;
604 		case -EINVAL:
605 			IPSECSTAT_INC(ips_out_polvio);
606 			break;
607 		default:
608 			IPSECSTAT_INC(ips_out_inval);
609 		}
610 	}
611 	KEYDBG(IPSEC_STAMP,
612 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
613 	if (sp != NULL)
614 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
615 	return (sp);
616 }
617 
618 /*
619  * Check IPv4 packet against *INBOUND* security policy.
620  * This function is called from tcp_input(), udp_input(),
621  * rip_input() and sctp_input().
622  */
623 int
ipsec4_in_reject1(const struct mbuf * m,struct ip * ip1,struct inpcb * inp)624 ipsec4_in_reject1(const struct mbuf *m, struct ip *ip1, struct inpcb *inp)
625 {
626 	struct secpolicy *sp;
627 #ifdef IPSEC_OFFLOAD
628 	struct ipsec_accel_in_tag *tag;
629 #endif
630 	struct ip ip_hdr;
631 	int result;
632 
633 #ifdef IPSEC_OFFLOAD
634 	tag = ipsec_accel_input_tag_lookup(m);
635 	if (tag != NULL)
636 		return (0);
637 #endif
638 
639 	if (ip1 == NULL) {
640 		ip1 = &ip_hdr;
641 		m_copydata(m, 0, sizeof(*ip1), (char *)ip1);
642 	}
643 
644 	sp = ipsec4_getpolicy(m, inp, ip1, IPSEC_DIR_INBOUND, 0);
645 	result = ipsec_in_reject(sp, inp, m);
646 	key_freesp(&sp);
647 	if (result != 0)
648 		IPSECSTAT_INC(ips_in_polvio);
649 	return (result);
650 }
651 
652 int
ipsec4_in_reject(const struct mbuf * m,struct inpcb * inp)653 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
654 {
655 	return (ipsec4_in_reject1(m, NULL, inp));
656 }
657 
658 /*
659  * IPSEC_CAP() method implementation for IPv4.
660  */
661 int
ipsec4_capability(struct mbuf * m,u_int cap)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
ipsec6_get_ulp(const struct mbuf * m,struct secpolicyindex * spidx,int needport)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
ipsec6_setspidx_ipaddr(const struct mbuf * m,struct secpolicyindex * spidx)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 *
ipsec6_getpolicy(const struct mbuf * m,struct inpcb * inp,u_int dir,int needport)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 *
ipsec6_checkpolicy(const struct mbuf * m,struct inpcb * inp,int * error,int needport)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
ipsec6_in_reject(const struct mbuf * m,struct inpcb * inp)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
ipsec6_capability(struct mbuf * m,u_int cap)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
ipsec_run_hhooks(struct ipsec_ctx_data * ctx,int type)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
ipsec_get_reqlevel(struct secpolicy * sp,u_int idx)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
ipsec_check_history(const struct mbuf * m,struct secpolicy * sp,u_int idx)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
ipsec_in_reject(struct secpolicy * sp,struct inpcb * inp,const struct mbuf * m)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
ipsec_hdrsiz_internal(struct secpolicy * sp)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
ipsec_hdrsiz_inpcb(struct inpcb * inp)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
check_window(const struct secreplay * replay,uint64_t seq)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
advance_window(const struct secreplay * replay,uint64_t seq)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
set_window(const struct secreplay * replay,uint64_t seq)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
ipsec_chkreplay(uint32_t seq,uint32_t * seqhigh,struct secasvar * sav)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
ipsec_updatereplay(uint32_t seq,struct secasvar * sav)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
ipsec_updateid(struct secasvar * sav,crypto_session_t * new,crypto_session_t * old)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
ipsec_initialized(void)1550 ipsec_initialized(void)
1551 {
1552 
1553 	return (V_def_policy != NULL);
1554 }
1555 
1556 static void
def_policy_init(const void * unused __unused)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
def_policy_uninit(const void * unused __unused)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