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