xref: /freebsd/sys/netipsec/ipsec.c (revision 70703aa922b41faedfd72211633884bb580ceeac)
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 		return (0);
641 #endif
642 
643 	if (ip1 == NULL) {
644 		ip1 = &ip_hdr;
645 		m_copydata(m, 0, sizeof(*ip1), (char *)ip1);
646 	}
647 
648 	sp = ipsec4_getpolicy(m, inp, ip1, IPSEC_DIR_INBOUND, 0);
649 	result = ipsec_in_reject(sp, inp, m);
650 	key_freesp(&sp);
651 	if (result != 0)
652 		IPSECSTAT_INC(ips_in_polvio);
653 	return (result);
654 }
655 
656 int
ipsec4_in_reject(const struct mbuf * m,struct inpcb * inp)657 ipsec4_in_reject(const struct mbuf *m, struct inpcb *inp)
658 {
659 	return (ipsec4_in_reject1(m, NULL, inp));
660 }
661 
662 /*
663  * IPSEC_CAP() method implementation for IPv4.
664  */
665 int
ipsec4_capability(struct mbuf * m,u_int cap)666 ipsec4_capability(struct mbuf *m, u_int cap)
667 {
668 
669 	switch (cap) {
670 	case IPSEC_CAP_BYPASS_FILTER:
671 		/*
672 		 * Bypass packet filtering for packets previously handled
673 		 * by IPsec.
674 		 */
675 		if (!V_ip4_filtertunnel &&
676 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
677 			return (1);
678 		return (0);
679 	case IPSEC_CAP_OPERABLE:
680 		/* Do we have active security policies? */
681 		return (key_havesp_any());
682 	};
683 	return (EOPNOTSUPP);
684 }
685 
686 #endif /* INET */
687 
688 #ifdef INET6
689 static void
ipsec6_get_ulp(const struct mbuf * m,struct secpolicyindex * spidx,int needport)690 ipsec6_get_ulp(const struct mbuf *m, struct secpolicyindex *spidx,
691     int needport)
692 {
693 	struct tcphdr th;
694 	struct udphdr uh;
695 	struct icmp6_hdr ih;
696 	int off, nxt;
697 
698 	IPSEC_ASSERT(m->m_pkthdr.len >= sizeof(struct ip6_hdr),
699 	    ("packet too short"));
700 
701 	/* Set default. */
702 	spidx->ul_proto = IPSEC_ULPROTO_ANY;
703 	spidx->src.sin6.sin6_port = IPSEC_PORT_ANY;
704 	spidx->dst.sin6.sin6_port = IPSEC_PORT_ANY;
705 
706 	nxt = -1;
707 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
708 	if (off < 0 || m->m_pkthdr.len < off)
709 		return;
710 
711 	switch (nxt) {
712 	case IPPROTO_TCP:
713 		spidx->ul_proto = nxt;
714 		if (!needport)
715 			break;
716 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len)
717 			break;
718 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
719 		spidx->src.sin6.sin6_port = th.th_sport;
720 		spidx->dst.sin6.sin6_port = th.th_dport;
721 		break;
722 	case IPPROTO_UDP:
723 		spidx->ul_proto = nxt;
724 		if (!needport)
725 			break;
726 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len)
727 			break;
728 		m_copydata(m, off, sizeof(uh), (caddr_t)&uh);
729 		spidx->src.sin6.sin6_port = uh.uh_sport;
730 		spidx->dst.sin6.sin6_port = uh.uh_dport;
731 		break;
732 	case IPPROTO_ICMPV6:
733 		spidx->ul_proto = nxt;
734 		if (off + sizeof(struct icmp6_hdr) > m->m_pkthdr.len)
735 			break;
736 		m_copydata(m, off, sizeof(ih), (caddr_t)&ih);
737 		spidx->src.sin6.sin6_port = htons((uint16_t)ih.icmp6_type);
738 		spidx->dst.sin6.sin6_port = htons((uint16_t)ih.icmp6_code);
739 		break;
740 	default:
741 		/* XXX Intermediate headers??? */
742 		spidx->ul_proto = nxt;
743 		break;
744 	}
745 	KEYDBG(IPSEC_DUMP,
746 	    printf("%s: ", __func__); kdebug_secpolicyindex(spidx, NULL));
747 }
748 
749 static void
ipsec6_setspidx_ipaddr(const struct mbuf * m,struct secpolicyindex * spidx)750 ipsec6_setspidx_ipaddr(const struct mbuf *m, struct secpolicyindex *spidx)
751 {
752 
753 	ipsec6_setsockaddrs(m, &spidx->src, &spidx->dst);
754 	spidx->prefs = sizeof(struct in6_addr) << 3;
755 	spidx->prefd = sizeof(struct in6_addr) << 3;
756 }
757 
758 static struct secpolicy *
ipsec6_getpolicy(const struct mbuf * m,struct inpcb * inp,u_int dir,int needport)759 ipsec6_getpolicy(const struct mbuf *m, struct inpcb *inp, u_int dir,
760     int needport)
761 {
762 	struct secpolicyindex spidx;
763 	struct secpolicy *sp;
764 
765 	sp = ipsec_getpcbpolicy(inp, dir);
766 	if (sp == NULL && key_havesp(dir)) {
767 		/* Make an index to look for a policy. */
768 		ipsec6_setspidx_ipaddr(m, &spidx);
769 		ipsec6_get_ulp(m, &spidx, needport);
770 		spidx.dir = dir;
771 		sp = key_allocsp(&spidx, dir);
772 	}
773 	if (sp == NULL)		/* No SP found, use system default. */
774 		sp = key_allocsp_default();
775 	return (sp);
776 }
777 
778 /*
779  * Check security policy for *OUTBOUND* IPv6 packet.
780  */
781 struct secpolicy *
ipsec6_checkpolicy(const struct mbuf * m,struct inpcb * inp,int * error,int needport)782 ipsec6_checkpolicy(const struct mbuf *m, struct inpcb *inp, int *error,
783     int needport)
784 {
785 	struct secpolicy *sp;
786 
787 	*error = 0;
788 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_OUTBOUND, needport);
789 	if (sp != NULL)
790 		sp = ipsec_checkpolicy(sp, inp, error);
791 	if (sp == NULL) {
792 		switch (*error) {
793 		case 0: /* No IPsec required: BYPASS or NONE */
794 			break;
795 		case -EINVAL:
796 			IPSEC6STAT_INC(ips_out_polvio);
797 			break;
798 		default:
799 			IPSEC6STAT_INC(ips_out_inval);
800 		}
801 	}
802 	KEYDBG(IPSEC_STAMP,
803 	    printf("%s: using SP(%p), error %d\n", __func__, sp, *error));
804 	if (sp != NULL)
805 		KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
806 	return (sp);
807 }
808 
809 /*
810  * Check IPv6 packet against inbound security policy.
811  * This function is called from tcp6_input(), udp6_input(),
812  * rip6_input() and sctp_input().
813  */
814 int
ipsec6_in_reject(const struct mbuf * m,struct inpcb * inp)815 ipsec6_in_reject(const struct mbuf *m, struct inpcb *inp)
816 {
817 	struct secpolicy *sp;
818 #ifdef IPSEC_OFFLOAD
819 	struct ipsec_accel_in_tag *tag;
820 #endif
821 	int result;
822 
823 #ifdef IPSEC_OFFLOAD
824 	tag = ipsec_accel_input_tag_lookup(m);
825 	if (tag != NULL)
826 		return (0);
827 #endif
828 	sp = ipsec6_getpolicy(m, inp, IPSEC_DIR_INBOUND, 0);
829 	result = ipsec_in_reject(sp, inp, m);
830 	key_freesp(&sp);
831 	if (result)
832 		IPSEC6STAT_INC(ips_in_polvio);
833 	return (result);
834 }
835 
836 /*
837  * IPSEC_CAP() method implementation for IPv6.
838  */
839 int
ipsec6_capability(struct mbuf * m,u_int cap)840 ipsec6_capability(struct mbuf *m, u_int cap)
841 {
842 
843 	switch (cap) {
844 	case IPSEC_CAP_BYPASS_FILTER:
845 		/*
846 		 * Bypass packet filtering for packets previously handled
847 		 * by IPsec.
848 		 */
849 		if (!V_ip6_filtertunnel &&
850 		    m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
851 			return (1);
852 		return (0);
853 	case IPSEC_CAP_OPERABLE:
854 		/* Do we have active security policies? */
855 		return (key_havesp_any());
856 	};
857 	return (EOPNOTSUPP);
858 }
859 #endif /* INET6 */
860 
861 int
ipsec_run_hhooks(struct ipsec_ctx_data * ctx,int type)862 ipsec_run_hhooks(struct ipsec_ctx_data *ctx, int type)
863 {
864 	int idx;
865 
866 	switch (ctx->af) {
867 #ifdef INET
868 	case AF_INET:
869 		idx = HHOOK_IPSEC_INET;
870 		break;
871 #endif
872 #ifdef INET6
873 	case AF_INET6:
874 		idx = HHOOK_IPSEC_INET6;
875 		break;
876 #endif
877 	default:
878 		return (EPFNOSUPPORT);
879 	}
880 	if (type == HHOOK_TYPE_IPSEC_IN)
881 		HHOOKS_RUN_IF(V_ipsec_hhh_in[idx], ctx, NULL);
882 	else
883 		HHOOKS_RUN_IF(V_ipsec_hhh_out[idx], ctx, NULL);
884 	if (*ctx->mp == NULL)
885 		return (EACCES);
886 	return (0);
887 }
888 
889 /*
890  * Return current level.
891  * Either IPSEC_LEVEL_USE or IPSEC_LEVEL_REQUIRE are always returned.
892  */
893 u_int
ipsec_get_reqlevel(struct secpolicy * sp,u_int idx)894 ipsec_get_reqlevel(struct secpolicy *sp, u_int idx)
895 {
896 	struct ipsecrequest *isr;
897 	u_int esp_trans_deflev, esp_net_deflev;
898 	u_int ah_trans_deflev, ah_net_deflev;
899 	u_int level = 0;
900 
901 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
902 /* XXX Note that we have ipseclog() expanded here - code sync issue. */
903 #define IPSEC_CHECK_DEFAULT(lev) \
904 	(((lev) != IPSEC_LEVEL_USE && (lev) != IPSEC_LEVEL_REQUIRE &&	\
905 	  (lev) != IPSEC_LEVEL_UNIQUE)					\
906 		? (V_ipsec_debug  ?					\
907 		log(LOG_INFO, "fixed system default level " #lev ":%d->%d\n",\
908 		(lev), IPSEC_LEVEL_REQUIRE) : 0),			\
909 		(lev) = IPSEC_LEVEL_REQUIRE, (lev) : (lev))
910 
911 	/*
912 	 * IPsec VTI uses unique security policy with fake spidx filled
913 	 * with zeroes. Just return IPSEC_LEVEL_REQUIRE instead of doing
914 	 * full level lookup for such policies.
915 	 */
916 	if (sp->state == IPSEC_SPSTATE_IFNET) {
917 		IPSEC_ASSERT(sp->req[idx]->level == IPSEC_LEVEL_UNIQUE,
918 		    ("Wrong IPsec request level %d", sp->req[idx]->level));
919 		return (IPSEC_LEVEL_REQUIRE);
920 	}
921 
922 	/* Set default level. */
923 	switch (sp->spidx.src.sa.sa_family) {
924 #ifdef INET
925 	case AF_INET:
926 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_trans_deflev);
927 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_esp_net_deflev);
928 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_trans_deflev);
929 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip4_ah_net_deflev);
930 		break;
931 #endif
932 #ifdef INET6
933 	case AF_INET6:
934 		esp_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_trans_deflev);
935 		esp_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_esp_net_deflev);
936 		ah_trans_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_trans_deflev);
937 		ah_net_deflev = IPSEC_CHECK_DEFAULT(V_ip6_ah_net_deflev);
938 		break;
939 #endif /* INET6 */
940 	default:
941 		panic("%s: unknown af %u",
942 			__func__, sp->spidx.src.sa.sa_family);
943 	}
944 
945 #undef IPSEC_CHECK_DEFAULT
946 
947 	isr = sp->req[idx];
948 	/* Set level. */
949 	switch (isr->level) {
950 	case IPSEC_LEVEL_DEFAULT:
951 		switch (isr->saidx.proto) {
952 		case IPPROTO_ESP:
953 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
954 				level = esp_net_deflev;
955 			else
956 				level = esp_trans_deflev;
957 			break;
958 		case IPPROTO_AH:
959 			if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
960 				level = ah_net_deflev;
961 			else
962 				level = ah_trans_deflev;
963 			break;
964 		case IPPROTO_IPCOMP:
965 			/*
966 			 * We don't really care, as IPcomp document says that
967 			 * we shouldn't compress small packets.
968 			 */
969 			level = IPSEC_LEVEL_USE;
970 			break;
971 		default:
972 			panic("%s: Illegal protocol defined %u\n", __func__,
973 				isr->saidx.proto);
974 		}
975 		break;
976 
977 	case IPSEC_LEVEL_USE:
978 	case IPSEC_LEVEL_REQUIRE:
979 		level = isr->level;
980 		break;
981 	case IPSEC_LEVEL_UNIQUE:
982 		level = IPSEC_LEVEL_REQUIRE;
983 		break;
984 
985 	default:
986 		panic("%s: Illegal IPsec level %u\n", __func__, isr->level);
987 	}
988 
989 	return (level);
990 }
991 
992 static int
ipsec_check_history(const struct mbuf * m,struct secpolicy * sp,u_int idx)993 ipsec_check_history(const struct mbuf *m, struct secpolicy *sp, u_int idx)
994 {
995 	struct xform_history *xh;
996 	struct m_tag *mtag;
997 
998 	mtag = NULL;
999 	while ((mtag = m_tag_find(__DECONST(struct mbuf *, m),
1000 	    PACKET_TAG_IPSEC_IN_DONE, mtag)) != NULL) {
1001 		xh = (struct xform_history *)(mtag + 1);
1002 		KEYDBG(IPSEC_DATA,
1003 		    char buf[IPSEC_ADDRSTRLEN];
1004 		    printf("%s: mode %s proto %u dst %s\n", __func__,
1005 			kdebug_secasindex_mode(xh->mode), xh->proto,
1006 			ipsec_address(&xh->dst, buf, sizeof(buf))));
1007 		if (xh->proto != sp->req[idx]->saidx.proto)
1008 			continue;
1009 		/* If SA had IPSEC_MODE_ANY, consider this as match. */
1010 		if (xh->mode != sp->req[idx]->saidx.mode &&
1011 		    xh->mode != IPSEC_MODE_ANY)
1012 			continue;
1013 		/*
1014 		 * For transport mode IPsec request doesn't contain
1015 		 * addresses. We need to use address from spidx.
1016 		 */
1017 		if (sp->req[idx]->saidx.mode == IPSEC_MODE_TRANSPORT) {
1018 			if (key_sockaddrcmp_withmask(&xh->dst.sa,
1019 			    &sp->spidx.dst.sa, sp->spidx.prefd) != 0)
1020 				continue;
1021 		} else {
1022 			if (key_sockaddrcmp(&xh->dst.sa,
1023 			    &sp->req[idx]->saidx.dst.sa, 0) != 0)
1024 				continue;
1025 		}
1026 		return (0); /* matched */
1027 	}
1028 	return (1);
1029 }
1030 
1031 /*
1032  * Check security policy requirements against the actual
1033  * packet contents.  Return one if the packet should be
1034  * rejected as "invalid"; otherwise return zero to have the
1035  * packet treated as "valid".
1036  *
1037  * OUT:
1038  *	0: valid
1039  *	1: invalid
1040  */
1041 static int
ipsec_in_reject(struct secpolicy * sp,struct inpcb * inp,const struct mbuf * m)1042 ipsec_in_reject(struct secpolicy *sp, struct inpcb *inp, const struct mbuf *m)
1043 {
1044 	int i;
1045 
1046 	KEYDBG(IPSEC_STAMP,
1047 	    printf("%s: PCB(%p): using SP(%p)\n", __func__, inp, sp));
1048 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1049 
1050 	if (inp != NULL && inp->inp_sp != NULL && inp->inp_sp->sp_in == NULL)
1051 		ipsec_cachepolicy(inp, sp, IPSEC_DIR_INBOUND);
1052 
1053 	/* Check policy. */
1054 	switch (sp->policy) {
1055 	case IPSEC_POLICY_DISCARD:
1056 		return (1);
1057 	case IPSEC_POLICY_BYPASS:
1058 	case IPSEC_POLICY_NONE:
1059 		return (0);
1060 	}
1061 
1062 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1063 		("invalid policy %u", sp->policy));
1064 
1065 	/*
1066 	 * ipsec[46]_common_input_cb after each transform adds
1067 	 * PACKET_TAG_IPSEC_IN_DONE mbuf tag. It contains SPI, proto, mode
1068 	 * and destination address from saidx. We can compare info from
1069 	 * these tags with requirements in SP.
1070 	 */
1071 	for (i = 0; i < sp->tcount; i++) {
1072 		/*
1073 		 * Do not check IPcomp, since IPcomp document
1074 		 * says that we shouldn't compress small packets.
1075 		 * IPComp policy should always be treated as being
1076 		 * in "use" level.
1077 		 */
1078 		if (sp->req[i]->saidx.proto == IPPROTO_IPCOMP ||
1079 		    ipsec_get_reqlevel(sp, i) != IPSEC_LEVEL_REQUIRE)
1080 			continue;
1081 		if (V_check_policy_history != 0 &&
1082 		    ipsec_check_history(m, sp, i) != 0)
1083 			return (1);
1084 		else switch (sp->req[i]->saidx.proto) {
1085 		case IPPROTO_ESP:
1086 			if ((m->m_flags & M_DECRYPTED) == 0) {
1087 				KEYDBG(IPSEC_DUMP,
1088 				    printf("%s: ESP m_flags:%x\n", __func__,
1089 					    m->m_flags));
1090 				return (1);
1091 			}
1092 			break;
1093 		case IPPROTO_AH:
1094 			if ((m->m_flags & M_AUTHIPHDR) == 0) {
1095 				KEYDBG(IPSEC_DUMP,
1096 				    printf("%s: AH m_flags:%x\n", __func__,
1097 					    m->m_flags));
1098 				return (1);
1099 			}
1100 			break;
1101 		}
1102 	}
1103 	return (0);		/* Valid. */
1104 }
1105 
1106 /*
1107  * Compute the byte size to be occupied by IPsec header.
1108  * In case it is tunnelled, it includes the size of outer IP header.
1109  */
1110 size_t
ipsec_hdrsiz_internal(struct secpolicy * sp)1111 ipsec_hdrsiz_internal(struct secpolicy *sp)
1112 {
1113 	size_t size;
1114 	int i;
1115 
1116 	KEYDBG(IPSEC_STAMP, printf("%s: using SP(%p)\n", __func__, sp));
1117 	KEYDBG(IPSEC_DATA, kdebug_secpolicy(sp));
1118 
1119 	switch (sp->policy) {
1120 	case IPSEC_POLICY_DISCARD:
1121 	case IPSEC_POLICY_BYPASS:
1122 	case IPSEC_POLICY_NONE:
1123 		return (0);
1124 	}
1125 
1126 	IPSEC_ASSERT(sp->policy == IPSEC_POLICY_IPSEC,
1127 		("invalid policy %u", sp->policy));
1128 
1129 	/*
1130 	 * XXX: for each transform we need to lookup suitable SA
1131 	 * and use info from SA to calculate headers size.
1132 	 * XXX: for NAT-T we need to cosider UDP header size.
1133 	 */
1134 	size = 0;
1135 	for (i = 0; i < sp->tcount; i++) {
1136 		switch (sp->req[i]->saidx.proto) {
1137 		case IPPROTO_ESP:
1138 			size += esp_hdrsiz(NULL);
1139 			break;
1140 		case IPPROTO_AH:
1141 			size += ah_hdrsiz(NULL);
1142 			break;
1143 		case IPPROTO_IPCOMP:
1144 			size += sizeof(struct ipcomp);
1145 			break;
1146 		}
1147 
1148 		if (sp->req[i]->saidx.mode == IPSEC_MODE_TUNNEL) {
1149 			switch (sp->req[i]->saidx.dst.sa.sa_family) {
1150 #ifdef INET
1151 			case AF_INET:
1152 				size += sizeof(struct ip);
1153 				break;
1154 #endif
1155 #ifdef INET6
1156 			case AF_INET6:
1157 				size += sizeof(struct ip6_hdr);
1158 				break;
1159 #endif
1160 			default:
1161 				ipseclog((LOG_ERR, "%s: unknown AF %d in "
1162 				    "IPsec tunnel SA\n", __func__,
1163 				    sp->req[i]->saidx.dst.sa.sa_family));
1164 				break;
1165 			}
1166 		}
1167 	}
1168 	return (size);
1169 }
1170 
1171 /*
1172  * Compute ESP/AH header size for protocols with PCB, including
1173  * outer IP header. Currently only tcp_output() uses it.
1174  */
1175 size_t
ipsec_hdrsiz_inpcb(struct inpcb * inp)1176 ipsec_hdrsiz_inpcb(struct inpcb *inp)
1177 {
1178 	struct secpolicyindex spidx;
1179 	struct secpolicy *sp;
1180 	size_t sz;
1181 
1182 	sp = ipsec_getpcbpolicy(inp, IPSEC_DIR_OUTBOUND);
1183 	if (sp == NULL && key_havesp(IPSEC_DIR_OUTBOUND)) {
1184 		ipsec_setspidx_inpcb(inp, &spidx, IPSEC_DIR_OUTBOUND);
1185 		sp = key_allocsp(&spidx, IPSEC_DIR_OUTBOUND);
1186 	}
1187 	if (sp == NULL)
1188 		sp = key_allocsp_default();
1189 	sz = ipsec_hdrsiz_internal(sp);
1190 	key_freesp(&sp);
1191 	return (sz);
1192 }
1193 
1194 
1195 #define IPSEC_BITMAP_INDEX_MASK(w)	(w - 1)
1196 #define IPSEC_REDUNDANT_BIT_SHIFTS	5
1197 #define IPSEC_REDUNDANT_BITS		(1 << IPSEC_REDUNDANT_BIT_SHIFTS)
1198 #define IPSEC_BITMAP_LOC_MASK		(IPSEC_REDUNDANT_BITS - 1)
1199 
1200 /*
1201  * Functions below are responsible for checking and updating bitmap.
1202  * These are used to separate ipsec_chkreplay() and ipsec_updatereplay()
1203  * from window implementation
1204  *
1205  * Based on RFC 6479. Blocks are 32 bits unsigned integers
1206  */
1207 
1208 static inline int
check_window(const struct secreplay * replay,uint64_t seq)1209 check_window(const struct secreplay *replay, uint64_t seq)
1210 {
1211 	int index, bit_location;
1212 
1213 	SECREPLAY_ASSERT(replay);
1214 
1215 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1216 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1217 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1218 
1219 	/* This packet already seen? */
1220 	return ((replay->bitmap)[index] & (1 << bit_location));
1221 }
1222 
1223 static inline void
advance_window(const struct secreplay * replay,uint64_t seq)1224 advance_window(const struct secreplay *replay, uint64_t seq)
1225 {
1226 	int i;
1227 	uint64_t index, index_cur, diff;
1228 
1229 	SECREPLAY_ASSERT(replay);
1230 
1231 	index_cur = replay->last >> IPSEC_REDUNDANT_BIT_SHIFTS;
1232 	index = seq >> IPSEC_REDUNDANT_BIT_SHIFTS;
1233 	diff = index - index_cur;
1234 
1235 	if (diff > replay->bitmap_size) {
1236 		/* something unusual in this case */
1237 		diff = replay->bitmap_size;
1238 	}
1239 
1240 	for (i = 0; i < diff; i++) {
1241 		replay->bitmap[(i + index_cur + 1)
1242 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size)] = 0;
1243 	}
1244 }
1245 
1246 static inline void
set_window(const struct secreplay * replay,uint64_t seq)1247 set_window(const struct secreplay *replay, uint64_t seq)
1248 {
1249 	int index, bit_location;
1250 
1251 	SECREPLAY_ASSERT(replay);
1252 
1253 	bit_location = seq & IPSEC_BITMAP_LOC_MASK;
1254 	index = (seq >> IPSEC_REDUNDANT_BIT_SHIFTS)
1255 		& IPSEC_BITMAP_INDEX_MASK(replay->bitmap_size);
1256 
1257 	replay->bitmap[index] |= (1 << bit_location);
1258 }
1259 
1260 /*
1261  * Check the variable replay window.
1262  * ipsec_chkreplay() performs replay check before ICV verification.
1263  * ipsec_updatereplay() updates replay bitmap.  This must be called after
1264  * ICV verification (it also performs replay check, which is usually done
1265  * beforehand).
1266  * 0 (zero) is returned if packet disallowed, 1 if packet permitted.
1267  *
1268  * Based on RFC 4303
1269  */
1270 
1271 int
ipsec_chkreplay(uint32_t seq,uint32_t * seqhigh,struct secasvar * sav)1272 ipsec_chkreplay(uint32_t seq, uint32_t *seqhigh, struct secasvar *sav)
1273 {
1274 	char buf[128];
1275 	struct secreplay *replay;
1276 	uint32_t window;
1277 	uint32_t tl, th, bl;
1278 	uint32_t seqh;
1279 
1280 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1281 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1282 
1283 	replay = sav->replay;
1284 
1285 	/* No need to check replay if disabled. */
1286 	if (replay->wsize == 0) {
1287 		return (1);
1288 	}
1289 
1290 	SECREPLAY_LOCK(replay);
1291 
1292 	/* Zero sequence number is not allowed. */
1293 	if (seq == 0 && replay->last == 0) {
1294 		SECREPLAY_UNLOCK(replay);
1295 		return (0);
1296 	}
1297 
1298 	window = replay->wsize << 3;		/* Size of window */
1299 	tl = (uint32_t)replay->last;		/* Top of window, lower part */
1300 	th = (uint32_t)(replay->last >> 32);	/* Top of window, high part */
1301 	bl = tl - window + 1;			/* Bottom of window, lower part */
1302 
1303 	/*
1304 	 * We keep the high part intact when:
1305 	 * 1) the seq is within [bl, 0xffffffff] and the whole window is
1306 	 *    within one subspace;
1307 	 * 2) the seq is within [0, bl) and window spans two subspaces.
1308 	 */
1309 	if ((tl >= window - 1 && seq >= bl) ||
1310 	    (tl < window - 1 && seq < bl)) {
1311 		*seqhigh = th;
1312 		if (seq <= tl) {
1313 			/* Sequence number inside window - check against replay */
1314 			if (check_window(replay, seq)) {
1315 				SECREPLAY_UNLOCK(replay);
1316 				return (0);
1317 			}
1318 		}
1319 
1320 		SECREPLAY_UNLOCK(replay);
1321 		/* Sequence number above top of window or not found in bitmap */
1322 		return (1);
1323 	}
1324 
1325 	/*
1326 	 * If ESN is not enabled and packet with highest sequence number
1327 	 * was received we should report overflow
1328 	 */
1329 	if (tl == 0xffffffff && !(sav->flags & SADB_X_SAFLAGS_ESN)) {
1330 		/* Set overflow flag. */
1331 		replay->overflow++;
1332 
1333 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1334 			if (sav->sah->saidx.proto == IPPROTO_ESP)
1335 				ESPSTAT_INC(esps_wrap);
1336 			else if (sav->sah->saidx.proto == IPPROTO_AH)
1337 				AHSTAT_INC(ahs_wrap);
1338 			SECREPLAY_UNLOCK(replay);
1339 			return (0);
1340 		}
1341 
1342 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1343 		    __func__, replay->overflow,
1344 		    ipsec_sa2str(sav, buf, sizeof(buf))));
1345 	}
1346 
1347 	/*
1348 	 * Seq is within [bl, 0xffffffff] and bl is within
1349 	 * [0xffffffff-window, 0xffffffff].  This means we got a seq
1350 	 * which is within our replay window, but in the previous
1351 	 * subspace.
1352 	 */
1353 	if (tl < window - 1 && seq >= bl) {
1354 		if (th == 0)
1355 			return (0);
1356 		*seqhigh = th - 1;
1357 		seqh = th - 1;
1358 		if (check_window(replay, seq)) {
1359 			SECREPLAY_UNLOCK(replay);
1360 			return (0);
1361 		}
1362 		SECREPLAY_UNLOCK(replay);
1363 		return (1);
1364 	}
1365 
1366 	/*
1367 	 * Seq is within [0, bl) but the whole window is within one subspace.
1368 	 * This means that seq has wrapped and is in next subspace
1369 	 */
1370 	*seqhigh = th + 1;
1371 	seqh = th + 1;
1372 
1373 	/* Don't let high part wrap. */
1374 	if (seqh == 0) {
1375 		/* Set overflow flag. */
1376 		replay->overflow++;
1377 
1378 		if ((sav->flags & SADB_X_EXT_CYCSEQ) == 0) {
1379 			if (sav->sah->saidx.proto == IPPROTO_ESP)
1380 				ESPSTAT_INC(esps_wrap);
1381 			else if (sav->sah->saidx.proto == IPPROTO_AH)
1382 				AHSTAT_INC(ahs_wrap);
1383 			SECREPLAY_UNLOCK(replay);
1384 			return (0);
1385 		}
1386 
1387 		ipseclog((LOG_WARNING, "%s: replay counter made %d cycle. %s\n",
1388 		    __func__, replay->overflow,
1389 		    ipsec_sa2str(sav, buf, sizeof(buf))));
1390 	}
1391 
1392 	SECREPLAY_UNLOCK(replay);
1393 	return (1);
1394 }
1395 
1396 /*
1397  * Check replay counter whether to update or not.
1398  * OUT:	0:	OK
1399  *	1:	NG
1400  */
1401 int
ipsec_updatereplay(uint32_t seq,struct secasvar * sav)1402 ipsec_updatereplay(uint32_t seq, struct secasvar *sav)
1403 {
1404 	struct secreplay *replay;
1405 	uint32_t window;
1406 	uint32_t tl, th, bl;
1407 	uint32_t seqh;
1408 
1409 	IPSEC_ASSERT(sav != NULL, ("Null SA"));
1410 	IPSEC_ASSERT(sav->replay != NULL, ("Null replay state"));
1411 
1412 	replay = sav->replay;
1413 
1414 	/* No need to check replay if disabled. */
1415 	if (replay->wsize == 0)
1416 		return (0);
1417 
1418 	SECREPLAY_LOCK(replay);
1419 
1420 	/* Zero sequence number is not allowed. */
1421 	if (seq == 0 && replay->last == 0) {
1422 		SECREPLAY_UNLOCK(replay);
1423 		return (1);
1424 	}
1425 
1426 	window = replay->wsize << 3;		/* Size of window */
1427 	tl = (uint32_t)replay->last;		/* Top of window, lower part */
1428 	th = (uint32_t)(replay->last >> 32);	/* Top of window, high part */
1429 	bl = tl - window + 1;			/* Bottom of window, lower part */
1430 
1431 	/*
1432 	 * We keep the high part intact when:
1433 	 * 1) the seq is within [bl, 0xffffffff] and the whole window is
1434 	 *    within one subspace;
1435 	 * 2) the seq is within [0, bl) and window spans two subspaces.
1436 	 */
1437 	if ((tl >= window - 1 && seq >= bl) ||
1438 	    (tl < window - 1 && seq < bl)) {
1439 		seqh = th;
1440 		if (seq <= tl) {
1441 			/* Sequence number inside window - check against replay */
1442 			if (check_window(replay, seq)) {
1443 				SECREPLAY_UNLOCK(replay);
1444 				return (1);
1445 			}
1446 			set_window(replay, seq);
1447 		} else {
1448 			advance_window(replay, ((uint64_t)seqh << 32) | seq);
1449 			set_window(replay, seq);
1450 			replay->last = ((uint64_t)seqh << 32) | seq;
1451 		}
1452 
1453 		/* Sequence number above top of window or not found in bitmap */
1454 		replay->count++;
1455 		SECREPLAY_UNLOCK(replay);
1456 		return (0);
1457 	}
1458 
1459 	if (!(sav->flags & SADB_X_SAFLAGS_ESN)) {
1460 		SECREPLAY_UNLOCK(replay);
1461 		return (1);
1462 	}
1463 
1464 	/*
1465 	 * Seq is within [bl, 0xffffffff] and bl is within
1466 	 * [0xffffffff-window, 0xffffffff].  This means we got a seq
1467 	 * which is within our replay window, but in the previous
1468 	 * subspace.
1469 	 */
1470 	if (tl < window - 1 && seq >= bl) {
1471 		if (th == 0) {
1472 			SECREPLAY_UNLOCK(replay);
1473 			return (1);
1474 		}
1475 		if (check_window(replay, seq)) {
1476 			SECREPLAY_UNLOCK(replay);
1477 			return (1);
1478 		}
1479 
1480 		set_window(replay, seq);
1481 		replay->count++;
1482 		SECREPLAY_UNLOCK(replay);
1483 		return (0);
1484 	}
1485 
1486 	/*
1487 	 * Seq is within [0, bl) but the whole window is within one subspace.
1488 	 * This means that seq has wrapped and is in next subspace
1489 	 */
1490 	seqh = th + 1;
1491 
1492 	/* Don't let high part wrap. */
1493 	if (seqh == 0) {
1494 		SECREPLAY_UNLOCK(replay);
1495 		return (1);
1496 	}
1497 
1498 	advance_window(replay, ((uint64_t)seqh << 32) | seq);
1499 	set_window(replay, seq);
1500 	replay->last = ((uint64_t)seqh << 32) | seq;
1501 	replay->count++;
1502 
1503 	SECREPLAY_UNLOCK(replay);
1504 	return (0);
1505 }
1506 int
ipsec_updateid(struct secasvar * sav,crypto_session_t * new,crypto_session_t * old)1507 ipsec_updateid(struct secasvar *sav, crypto_session_t *new,
1508     crypto_session_t *old)
1509 {
1510 	crypto_session_t tmp;
1511 
1512 	/*
1513 	 * tdb_cryptoid is initialized by xform_init().
1514 	 * Then it can be changed only when some crypto error occurred or
1515 	 * when SA is deleted. We stored used cryptoid in the xform_data
1516 	 * structure. In case when crypto error occurred and crypto
1517 	 * subsystem has reinited the session, it returns new cryptoid
1518 	 * and EAGAIN error code.
1519 	 *
1520 	 * This function will be called when we got EAGAIN from crypto
1521 	 * subsystem.
1522 	 * *new is cryptoid that was returned by crypto subsystem in
1523 	 * the crp_sid.
1524 	 * *old is the original cryptoid that we stored in xform_data.
1525 	 *
1526 	 * For first failed request *old == sav->tdb_cryptoid, then
1527 	 * we update sav->tdb_cryptoid and redo crypto_dispatch().
1528 	 * For next failed request *old != sav->tdb_cryptoid, then
1529 	 * we store cryptoid from first request into the *new variable
1530 	 * and crp_sid from this second session will be returned via
1531 	 * *old pointer, so caller can release second session.
1532 	 *
1533 	 * XXXAE: check this more carefully.
1534 	 */
1535 	KEYDBG(IPSEC_STAMP,
1536 	    printf("%s: SA(%p) moves cryptoid %p -> %p\n",
1537 		__func__, sav, *old, *new));
1538 	KEYDBG(IPSEC_DATA, kdebug_secasv(sav));
1539 	SECASVAR_WLOCK(sav);
1540 	if (sav->tdb_cryptoid != *old) {
1541 		/* cryptoid was already updated */
1542 		tmp = *new;
1543 		*new = sav->tdb_cryptoid;
1544 		*old = tmp;
1545 		SECASVAR_WUNLOCK(sav);
1546 		return (1);
1547 	}
1548 	sav->tdb_cryptoid = *new;
1549 	SECASVAR_WUNLOCK(sav);
1550 	return (0);
1551 }
1552 
1553 int
ipsec_initialized(void)1554 ipsec_initialized(void)
1555 {
1556 
1557 	return (V_def_policy != NULL);
1558 }
1559 
1560 static void
def_policy_init(const void * unused __unused)1561 def_policy_init(const void *unused __unused)
1562 {
1563 
1564 	V_def_policy = key_newsp();
1565 	if (V_def_policy != NULL) {
1566 		V_def_policy->policy = IPSEC_POLICY_NONE;
1567 		/* Force INPCB SP cache invalidation */
1568 		key_bumpspgen();
1569 	} else
1570 		printf("%s: failed to initialize default policy\n", __func__);
1571 }
1572 
1573 static void
def_policy_uninit(const void * unused __unused)1574 def_policy_uninit(const void *unused __unused)
1575 {
1576 
1577 	if (V_def_policy != NULL) {
1578 		key_freesp(&V_def_policy);
1579 		key_bumpspgen();
1580 	}
1581 }
1582 
1583 VNET_SYSINIT(def_policy_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1584     def_policy_init, NULL);
1585 VNET_SYSUNINIT(def_policy_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
1586     def_policy_uninit, NULL);
1587