xref: /freebsd-13.1/sys/netipsec/ipsec_output.c (revision f763c81c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
5  * Copyright (c) 2016 Andrey V. Elsukov <[email protected]>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 /*
33  * IPsec output processing.
34  */
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_ipsec.h"
38 #include "opt_sctp.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/mbuf.h>
43 #include <sys/domain.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/errno.h>
47 #include <sys/hhook.h>
48 #include <sys/syslog.h>
49 
50 #include <net/if.h>
51 #include <net/if_enc.h>
52 #include <net/if_var.h>
53 #include <net/vnet.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_var.h>
59 #include <netinet/in_var.h>
60 #include <netinet/ip_ecn.h>
61 #ifdef INET6
62 #include <netinet6/ip6_ecn.h>
63 #endif
64 
65 #include <netinet/ip6.h>
66 #ifdef INET6
67 #include <netinet6/ip6_var.h>
68 #include <netinet6/scope6_var.h>
69 #endif
70 #include <netinet/in_pcb.h>
71 #ifdef INET6
72 #include <netinet/icmp6.h>
73 #endif
74 #if defined(SCTP) || defined(SCTP_SUPPORT)
75 #include <netinet/sctp_crc32.h>
76 #endif
77 
78 #include <netinet/udp.h>
79 #include <netipsec/ah.h>
80 #include <netipsec/esp.h>
81 #include <netipsec/ipsec.h>
82 #ifdef INET6
83 #include <netipsec/ipsec6.h>
84 #endif
85 #include <netipsec/ah_var.h>
86 #include <netipsec/esp_var.h>
87 #include <netipsec/ipcomp_var.h>
88 
89 #include <netipsec/xform.h>
90 
91 #include <netipsec/key.h>
92 #include <netipsec/keydb.h>
93 #include <netipsec/key_debug.h>
94 
95 #include <machine/in_cksum.h>
96 
97 #define	IPSEC_OSTAT_INC(proto, name)	do {		\
98 	if ((proto) == IPPROTO_ESP)	\
99 		ESPSTAT_INC(esps_##name);	\
100 	else if ((proto) == IPPROTO_AH)\
101 		AHSTAT_INC(ahs_##name);		\
102 	else					\
103 		IPCOMPSTAT_INC(ipcomps_##name);	\
104 } while (0)
105 
106 static int ipsec_encap(struct mbuf **mp, struct secasindex *saidx);
107 
108 #ifdef INET
109 static struct secasvar *
ipsec4_allocsa(struct mbuf * m,struct secpolicy * sp,u_int * pidx,int * error)110 ipsec4_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
111 {
112 	struct secasindex *saidx, tmpsaidx;
113 	struct ipsecrequest *isr;
114 	struct sockaddr_in *sin;
115 	struct secasvar *sav;
116 	struct ip *ip;
117 
118 	/*
119 	 * Check system global policy controls.
120 	 */
121 next:
122 	isr = sp->req[*pidx];
123 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
124 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
125 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
126 		DPRINTF(("%s: IPsec outbound packet dropped due"
127 			" to policy (check your sysctls)\n", __func__));
128 		IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
129 		*error = EHOSTUNREACH;
130 		return (NULL);
131 	}
132 	/*
133 	 * Craft SA index to search for proper SA.  Note that
134 	 * we only initialize unspecified SA peers for transport
135 	 * mode; for tunnel mode they must already be filled in.
136 	 */
137 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
138 		saidx = &tmpsaidx;
139 		*saidx = isr->saidx;
140 		ip = mtod(m, struct ip *);
141 		if (saidx->src.sa.sa_len == 0) {
142 			sin = &saidx->src.sin;
143 			sin->sin_len = sizeof(*sin);
144 			sin->sin_family = AF_INET;
145 			sin->sin_port = IPSEC_PORT_ANY;
146 			sin->sin_addr = ip->ip_src;
147 		}
148 		if (saidx->dst.sa.sa_len == 0) {
149 			sin = &saidx->dst.sin;
150 			sin->sin_len = sizeof(*sin);
151 			sin->sin_family = AF_INET;
152 			sin->sin_port = IPSEC_PORT_ANY;
153 			sin->sin_addr = ip->ip_dst;
154 		}
155 	} else
156 		saidx = &sp->req[*pidx]->saidx;
157 	/*
158 	 * Lookup SA and validate it.
159 	 */
160 	sav = key_allocsa_policy(sp, saidx, error);
161 	if (sav == NULL) {
162 		IPSECSTAT_INC(ips_out_nosa);
163 		if (*error != 0)
164 			return (NULL);
165 		if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
166 			/*
167 			 * We have no SA and policy that doesn't require
168 			 * this IPsec transform, thus we can continue w/o
169 			 * IPsec processing, i.e. return EJUSTRETURN.
170 			 * But first check if there is some bundled transform.
171 			 */
172 			if (sp->tcount > ++(*pidx))
173 				goto next;
174 			*error = EJUSTRETURN;
175 		}
176 		return (NULL);
177 	}
178 	IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
179 	return (sav);
180 }
181 
182 /*
183  * IPsec output logic for IPv4.
184  */
185 static int
ipsec4_perform_request(struct mbuf * m,struct secpolicy * sp,struct inpcb * inp,u_int idx)186 ipsec4_perform_request(struct mbuf *m, struct secpolicy *sp,
187     struct inpcb *inp, u_int idx)
188 {
189 	struct ipsec_ctx_data ctx;
190 	union sockaddr_union *dst;
191 	struct secasvar *sav;
192 	struct ip *ip;
193 	int error, i, off;
194 
195 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
196 
197 	/*
198 	 * We hold the reference to SP. Content of SP couldn't be changed.
199 	 * Craft secasindex and do lookup for suitable SA.
200 	 * Then do encapsulation if needed and call xform's output.
201 	 * We need to store SP in the xform callback parameters.
202 	 * In xform callback we will extract SP and it can be used to
203 	 * determine next transform. At the end of transform we can
204 	 * release reference to SP.
205 	 */
206 	sav = ipsec4_allocsa(m, sp, &idx, &error);
207 	if (sav == NULL) {
208 		if (error == EJUSTRETURN) { /* No IPsec required */
209 			key_freesp(&sp);
210 			return (error);
211 		}
212 		goto bad;
213 	}
214 	/*
215 	 * XXXAE: most likely ip_sum at this point is wrong.
216 	 */
217 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET, IPSEC_ENC_BEFORE);
218 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
219 		goto bad;
220 
221 	ip = mtod(m, struct ip *);
222 	dst = &sav->sah->saidx.dst;
223 	/* Do the appropriate encapsulation, if necessary */
224 	if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
225 	    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
226 	    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
227 	     dst->sin.sin_addr.s_addr != INADDR_ANY &&
228 	     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
229 		/* Fix IPv4 header checksum and length */
230 		ip->ip_len = htons(m->m_pkthdr.len);
231 		ip->ip_sum = 0;
232 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
233 		error = ipsec_encap(&m, &sav->sah->saidx);
234 		if (error != 0) {
235 			DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
236 			    "with error %d\n", __func__, ntohl(sav->spi),
237 			    error));
238 			/* XXXAE: IPSEC_OSTAT_INC(tunnel); */
239 			goto bad;
240 		}
241 		inp = NULL;
242 	}
243 
244 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
245 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
246 		goto bad;
247 
248 	/*
249 	 * Dispatch to the appropriate IPsec transform logic.  The
250 	 * packet will be returned for transmission after crypto
251 	 * processing, etc. are completed.
252 	 *
253 	 * NB: m & sav are ``passed to caller'' who's responsible for
254 	 *     reclaiming their resources.
255 	 */
256 	switch(dst->sa.sa_family) {
257 	case AF_INET:
258 		ip = mtod(m, struct ip *);
259 		i = ip->ip_hl << 2;
260 		off = offsetof(struct ip, ip_p);
261 		break;
262 #ifdef INET6
263 	case AF_INET6:
264 		i = sizeof(struct ip6_hdr);
265 		off = offsetof(struct ip6_hdr, ip6_nxt);
266 		break;
267 #endif /* INET6 */
268 	default:
269 		DPRINTF(("%s: unsupported protocol family %u\n",
270 		    __func__, dst->sa.sa_family));
271 		error = EPFNOSUPPORT;
272 		IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
273 		goto bad;
274 	}
275 	error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
276 	return (error);
277 bad:
278 	IPSECSTAT_INC(ips_out_inval);
279 	if (m != NULL)
280 		m_freem(m);
281 	if (sav != NULL)
282 		key_freesav(&sav);
283 	key_freesp(&sp);
284 	return (error);
285 }
286 
287 int
ipsec4_process_packet(struct mbuf * m,struct secpolicy * sp,struct inpcb * inp)288 ipsec4_process_packet(struct mbuf *m, struct secpolicy *sp,
289     struct inpcb *inp)
290 {
291 
292 	return (ipsec4_perform_request(m, sp, inp, 0));
293 }
294 
295 static int
ipsec4_common_output(struct mbuf * m,struct inpcb * inp,int forwarding)296 ipsec4_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
297 {
298 	struct secpolicy *sp;
299 	int error;
300 
301 	/* Lookup for the corresponding outbound security policy */
302 	sp = ipsec4_checkpolicy(m, inp, &error, !forwarding);
303 	if (sp == NULL) {
304 		if (error == -EINVAL) {
305 			/* Discarded by policy. */
306 			m_freem(m);
307 			return (EACCES);
308 		}
309 		return (0); /* No IPsec required. */
310 	}
311 
312 	/*
313 	 * Usually we have to have tunnel mode IPsec security policy
314 	 * when we are forwarding a packet. Otherwise we could not handle
315 	 * encrypted replies, because they are not destined for us. But
316 	 * some users are doing source address translation for forwarded
317 	 * packets, and thus, even if they are forwarded, the replies will
318 	 * return back to us.
319 	 */
320 	if (!forwarding) {
321 		/*
322 		 * Do delayed checksums now because we send before
323 		 * this is done in the normal processing path.
324 		 */
325 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
326 			in_delayed_cksum(m);
327 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
328 		}
329 #if defined(SCTP) || defined(SCTP_SUPPORT)
330 		if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
331 			struct ip *ip;
332 
333 			ip = mtod(m, struct ip *);
334 			sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
335 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
336 		}
337 #endif
338 	}
339 	/* NB: callee frees mbuf and releases reference to SP */
340 	error = ipsec4_process_packet(m, sp, inp);
341 	if (error == EJUSTRETURN) {
342 		/*
343 		 * We had a SP with a level of 'use' and no SA. We
344 		 * will just continue to process the packet without
345 		 * IPsec processing and return without error.
346 		 */
347 		return (0);
348 	}
349 	if (error == 0)
350 		return (EINPROGRESS); /* consumed by IPsec */
351 	return (error);
352 }
353 
354 /*
355  * IPSEC_OUTPUT() method implementation for IPv4.
356  * 0 - no IPsec handling needed
357  * other values - mbuf consumed by IPsec.
358  */
359 int
ipsec4_output(struct mbuf * m,struct inpcb * inp)360 ipsec4_output(struct mbuf *m, struct inpcb *inp)
361 {
362 
363 	/*
364 	 * If the packet is resubmitted to ip_output (e.g. after
365 	 * AH, ESP, etc. processing), there will be a tag to bypass
366 	 * the lookup and related policy checking.
367 	 */
368 	if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
369 		return (0);
370 
371 	return (ipsec4_common_output(m, inp, 0));
372 }
373 
374 /*
375  * IPSEC_FORWARD() method implementation for IPv4.
376  * 0 - no IPsec handling needed
377  * other values - mbuf consumed by IPsec.
378  */
379 int
ipsec4_forward(struct mbuf * m)380 ipsec4_forward(struct mbuf *m)
381 {
382 
383 	/*
384 	 * Check if this packet has an active inbound SP and needs to be
385 	 * dropped instead of forwarded.
386 	 */
387 	if (ipsec4_in_reject(m, NULL) != 0) {
388 		m_freem(m);
389 		return (EACCES);
390 	}
391 	return (ipsec4_common_output(m, NULL, 1));
392 }
393 #endif
394 
395 #ifdef INET6
396 static int
in6_sa_equal_addrwithscope(const struct sockaddr_in6 * sa,const struct in6_addr * ia)397 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
398     const struct in6_addr *ia)
399 {
400 	struct in6_addr ia2;
401 
402 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr)) {
403 		memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
404 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
405 		return (IN6_ARE_ADDR_EQUAL(ia, &ia2));
406 	}
407 	return (IN6_ARE_ADDR_EQUAL(&sa->sin6_addr, ia));
408 }
409 
410 static struct secasvar *
ipsec6_allocsa(struct mbuf * m,struct secpolicy * sp,u_int * pidx,int * error)411 ipsec6_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
412 {
413 	struct secasindex *saidx, tmpsaidx;
414 	struct ipsecrequest *isr;
415 	struct sockaddr_in6 *sin6;
416 	struct secasvar *sav;
417 	struct ip6_hdr *ip6;
418 
419 	/*
420 	 * Check system global policy controls.
421 	 */
422 next:
423 	isr = sp->req[*pidx];
424 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
425 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
426 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
427 		DPRINTF(("%s: IPsec outbound packet dropped due"
428 			" to policy (check your sysctls)\n", __func__));
429 		IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
430 		*error = EHOSTUNREACH;
431 		return (NULL);
432 	}
433 	/*
434 	 * Craft SA index to search for proper SA.  Note that
435 	 * we only fillin unspecified SA peers for transport
436 	 * mode; for tunnel mode they must already be filled in.
437 	 */
438 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
439 		saidx = &tmpsaidx;
440 		*saidx = isr->saidx;
441 		ip6 = mtod(m, struct ip6_hdr *);
442 		if (saidx->src.sin6.sin6_len == 0) {
443 			sin6 = (struct sockaddr_in6 *)&saidx->src;
444 			sin6->sin6_len = sizeof(*sin6);
445 			sin6->sin6_family = AF_INET6;
446 			sin6->sin6_port = IPSEC_PORT_ANY;
447 			sin6->sin6_addr = ip6->ip6_src;
448 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
449 				/* fix scope id for comparing SPD */
450 				sin6->sin6_addr.s6_addr16[1] = 0;
451 				sin6->sin6_scope_id =
452 				    ntohs(ip6->ip6_src.s6_addr16[1]);
453 			}
454 		}
455 		if (saidx->dst.sin6.sin6_len == 0) {
456 			sin6 = (struct sockaddr_in6 *)&saidx->dst;
457 			sin6->sin6_len = sizeof(*sin6);
458 			sin6->sin6_family = AF_INET6;
459 			sin6->sin6_port = IPSEC_PORT_ANY;
460 			sin6->sin6_addr = ip6->ip6_dst;
461 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
462 				/* fix scope id for comparing SPD */
463 				sin6->sin6_addr.s6_addr16[1] = 0;
464 				sin6->sin6_scope_id =
465 				    ntohs(ip6->ip6_dst.s6_addr16[1]);
466 			}
467 		}
468 	} else
469 		saidx = &sp->req[*pidx]->saidx;
470 	/*
471 	 * Lookup SA and validate it.
472 	 */
473 	sav = key_allocsa_policy(sp, saidx, error);
474 	if (sav == NULL) {
475 		IPSEC6STAT_INC(ips_out_nosa);
476 		if (*error != 0)
477 			return (NULL);
478 		if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
479 			/*
480 			 * We have no SA and policy that doesn't require
481 			 * this IPsec transform, thus we can continue w/o
482 			 * IPsec processing, i.e. return EJUSTRETURN.
483 			 * But first check if there is some bundled transform.
484 			 */
485 			if (sp->tcount > ++(*pidx))
486 				goto next;
487 			*error = EJUSTRETURN;
488 		}
489 		return (NULL);
490 	}
491 	IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
492 	return (sav);
493 }
494 
495 /*
496  * IPsec output logic for IPv6.
497  */
498 static int
ipsec6_perform_request(struct mbuf * m,struct secpolicy * sp,struct inpcb * inp,u_int idx)499 ipsec6_perform_request(struct mbuf *m, struct secpolicy *sp,
500     struct inpcb *inp, u_int idx)
501 {
502 	struct ipsec_ctx_data ctx;
503 	union sockaddr_union *dst;
504 	struct secasvar *sav;
505 	struct ip6_hdr *ip6;
506 	int error, i, off;
507 
508 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
509 
510 	sav = ipsec6_allocsa(m, sp, &idx, &error);
511 	if (sav == NULL) {
512 		if (error == EJUSTRETURN) { /* No IPsec required */
513 			key_freesp(&sp);
514 			return (error);
515 		}
516 		goto bad;
517 	}
518 
519 	/* Fix IP length in case if it is not set yet. */
520 	ip6 = mtod(m, struct ip6_hdr *);
521 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
522 
523 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET6, IPSEC_ENC_BEFORE);
524 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
525 		goto bad;
526 
527 	ip6 = mtod(m, struct ip6_hdr *); /* pfil can change mbuf */
528 	dst = &sav->sah->saidx.dst;
529 
530 	/* Do the appropriate encapsulation, if necessary */
531 	if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
532 	    dst->sa.sa_family != AF_INET6 ||        /* PF mismatch */
533 	    ((dst->sa.sa_family == AF_INET6) &&
534 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
535 	     (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
536 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
537 			/* No jumbogram support. */
538 			error = ENXIO;   /*XXX*/
539 			goto bad;
540 		}
541 		error = ipsec_encap(&m, &sav->sah->saidx);
542 		if (error != 0) {
543 			DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
544 			    "with error %d\n", __func__, ntohl(sav->spi),
545 			    error));
546 			/* XXXAE: IPSEC_OSTAT_INC(tunnel); */
547 			goto bad;
548 		}
549 		inp = NULL;
550 	}
551 
552 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
553 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
554 		goto bad;
555 
556 	switch(dst->sa.sa_family) {
557 #ifdef INET
558 	case AF_INET:
559 		{
560 		struct ip *ip;
561 		ip = mtod(m, struct ip *);
562 		i = ip->ip_hl << 2;
563 		off = offsetof(struct ip, ip_p);
564 		}
565 		break;
566 #endif /* AF_INET */
567 	case AF_INET6:
568 		i = sizeof(struct ip6_hdr);
569 		off = offsetof(struct ip6_hdr, ip6_nxt);
570 		break;
571 	default:
572 		DPRINTF(("%s: unsupported protocol family %u\n",
573 				 __func__, dst->sa.sa_family));
574 		error = EPFNOSUPPORT;
575 		IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
576 		goto bad;
577 	}
578 	error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
579 	return (error);
580 bad:
581 	IPSEC6STAT_INC(ips_out_inval);
582 	if (m != NULL)
583 		m_freem(m);
584 	if (sav != NULL)
585 		key_freesav(&sav);
586 	key_freesp(&sp);
587 	return (error);
588 }
589 
590 int
ipsec6_process_packet(struct mbuf * m,struct secpolicy * sp,struct inpcb * inp)591 ipsec6_process_packet(struct mbuf *m, struct secpolicy *sp,
592     struct inpcb *inp)
593 {
594 
595 	return (ipsec6_perform_request(m, sp, inp, 0));
596 }
597 
598 static int
ipsec6_common_output(struct mbuf * m,struct inpcb * inp,int forwarding)599 ipsec6_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
600 {
601 	struct secpolicy *sp;
602 	int error;
603 
604 	/* Lookup for the corresponding outbound security policy */
605 	sp = ipsec6_checkpolicy(m, inp, &error, !forwarding);
606 	if (sp == NULL) {
607 		if (error == -EINVAL) {
608 			/* Discarded by policy. */
609 			m_freem(m);
610 			return (EACCES);
611 		}
612 		return (0); /* No IPsec required. */
613 	}
614 
615 	if (!forwarding) {
616 		/*
617 		 * Do delayed checksums now because we send before
618 		 * this is done in the normal processing path.
619 		 */
620 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
621 			in6_delayed_cksum(m, m->m_pkthdr.len -
622 			    sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
623 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
624 		}
625 #if defined(SCTP) || defined(SCTP_SUPPORT)
626 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
627 			sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
628 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
629 		}
630 #endif
631 	}
632 	/* NB: callee frees mbuf and releases reference to SP */
633 	error = ipsec6_process_packet(m, sp, inp);
634 	if (error == EJUSTRETURN) {
635 		/*
636 		 * We had a SP with a level of 'use' and no SA. We
637 		 * will just continue to process the packet without
638 		 * IPsec processing and return without error.
639 		 */
640 		return (0);
641 	}
642 	if (error == 0)
643 		return (EINPROGRESS); /* consumed by IPsec */
644 	return (error);
645 }
646 
647 /*
648  * IPSEC_OUTPUT() method implementation for IPv6.
649  * 0 - no IPsec handling needed
650  * other values - mbuf consumed by IPsec.
651  */
652 int
ipsec6_output(struct mbuf * m,struct inpcb * inp)653 ipsec6_output(struct mbuf *m, struct inpcb *inp)
654 {
655 
656 	/*
657 	 * If the packet is resubmitted to ip_output (e.g. after
658 	 * AH, ESP, etc. processing), there will be a tag to bypass
659 	 * the lookup and related policy checking.
660 	 */
661 	if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
662 		return (0);
663 
664 	return (ipsec6_common_output(m, inp, 0));
665 }
666 
667 /*
668  * IPSEC_FORWARD() method implementation for IPv6.
669  * 0 - no IPsec handling needed
670  * other values - mbuf consumed by IPsec.
671  */
672 int
ipsec6_forward(struct mbuf * m)673 ipsec6_forward(struct mbuf *m)
674 {
675 
676 	/*
677 	 * Check if this packet has an active inbound SP and needs to be
678 	 * dropped instead of forwarded.
679 	 */
680 	if (ipsec6_in_reject(m, NULL) != 0) {
681 		m_freem(m);
682 		return (EACCES);
683 	}
684 	return (ipsec6_common_output(m, NULL, 1));
685 }
686 #endif /* INET6 */
687 
688 int
ipsec_process_done(struct mbuf * m,struct secpolicy * sp,struct secasvar * sav,u_int idx)689 ipsec_process_done(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
690     u_int idx)
691 {
692 	struct epoch_tracker et;
693 	struct xform_history *xh;
694 	struct secasindex *saidx;
695 	struct m_tag *mtag;
696 	int error;
697 
698 	saidx = &sav->sah->saidx;
699 	switch (saidx->dst.sa.sa_family) {
700 #ifdef INET
701 	case AF_INET:
702 		/* Fix the header length, for AH processing. */
703 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
704 		break;
705 #endif /* INET */
706 #ifdef INET6
707 	case AF_INET6:
708 		/* Fix the header length, for AH processing. */
709 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
710 			error = ENXIO;
711 			goto bad;
712 		}
713 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
714 			/* No jumbogram support. */
715 			error = ENXIO;	/*?*/
716 			goto bad;
717 		}
718 		mtod(m, struct ip6_hdr *)->ip6_plen =
719 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
720 		break;
721 #endif /* INET6 */
722 	default:
723 		DPRINTF(("%s: unknown protocol family %u\n", __func__,
724 		    saidx->dst.sa.sa_family));
725 		error = ENXIO;
726 		goto bad;
727 	}
728 
729 	/*
730 	 * Add a record of what we've done to the packet.
731 	 */
732 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, sizeof(*xh), M_NOWAIT);
733 	if (mtag == NULL) {
734 		DPRINTF(("%s: could not get packet tag\n", __func__));
735 		error = ENOMEM;
736 		goto bad;
737 	}
738 
739 	xh = (struct xform_history *)(mtag + 1);
740 	xh->dst = saidx->dst;
741 	xh->proto = saidx->proto;
742 	xh->mode = saidx->mode;
743 	xh->spi = sav->spi;
744 	m_tag_prepend(m, mtag);
745 
746 	key_sa_recordxfer(sav, m);		/* record data transfer */
747 
748 	/*
749 	 * If there's another (bundled) SA to apply, do so.
750 	 * Note that this puts a burden on the kernel stack size.
751 	 * If this is a problem we'll need to introduce a queue
752 	 * to set the packet on so we can unwind the stack before
753 	 * doing further processing.
754 	 */
755 	if (++idx < sp->tcount) {
756 		switch (saidx->dst.sa.sa_family) {
757 #ifdef INET
758 		case AF_INET:
759 			key_freesav(&sav);
760 			IPSECSTAT_INC(ips_out_bundlesa);
761 			return (ipsec4_perform_request(m, sp, NULL, idx));
762 			/* NOTREACHED */
763 #endif
764 #ifdef INET6
765 		case AF_INET6:
766 			key_freesav(&sav);
767 			IPSEC6STAT_INC(ips_out_bundlesa);
768 			return (ipsec6_perform_request(m, sp, NULL, idx));
769 			/* NOTREACHED */
770 #endif /* INET6 */
771 		default:
772 			DPRINTF(("%s: unknown protocol family %u\n", __func__,
773 			    saidx->dst.sa.sa_family));
774 			error = EPFNOSUPPORT;
775 			goto bad;
776 		}
777 	}
778 
779 	key_freesp(&sp), sp = NULL;	/* Release reference to SP */
780 #ifdef INET
781 	/*
782 	 * Do UDP encapsulation if SA requires it.
783 	 */
784 	if (sav->natt != NULL) {
785 		error = udp_ipsec_output(m, sav);
786 		if (error != 0)
787 			goto bad;
788 	}
789 #endif /* INET */
790 	/*
791 	 * We're done with IPsec processing, transmit the packet using the
792 	 * appropriate network protocol (IP or IPv6).
793 	 */
794 	NET_EPOCH_ENTER(et);
795 	switch (saidx->dst.sa.sa_family) {
796 #ifdef INET
797 	case AF_INET:
798 		key_freesav(&sav);
799 		error = ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
800 		break;
801 #endif /* INET */
802 #ifdef INET6
803 	case AF_INET6:
804 		key_freesav(&sav);
805 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
806 		break;
807 #endif /* INET6 */
808 	default:
809 		panic("ipsec_process_done");
810 	}
811 	NET_EPOCH_EXIT(et);
812 	return (error);
813 bad:
814 	m_freem(m);
815 	key_freesav(&sav);
816 	if (sp != NULL)
817 		key_freesp(&sp);
818 	return (error);
819 }
820 
821 /*
822  * ipsec_prepend() is optimized version of M_PREPEND().
823  * ipsec_encap() is called by IPsec output routine for tunnel mode SA.
824  * It is expected that after IP encapsulation some IPsec transform will
825  * be performed. Each IPsec transform inserts its variable length header
826  * just after outer IP header using m_makespace(). If given mbuf has not
827  * enough free space at the beginning, we allocate new mbuf and reserve
828  * some space at the beginning and at the end.
829  * This helps avoid allocating of new mbuf and data copying in m_makespace(),
830  * we place outer header in the middle of mbuf's data with reserved leading
831  * and trailing space:
832  *	[ LEADINGSPACE ][ Outer IP header ][ TRAILINGSPACE ]
833  * LEADINGSPACE will be used to add ethernet header, TRAILINGSPACE will
834  * be used to inject AH/ESP/IPCOMP header.
835  */
836 #define	IPSEC_TRAILINGSPACE	(sizeof(struct udphdr) +/* NAT-T */	\
837     max(sizeof(struct newesp) + EALG_MAX_BLOCK_LEN,	/* ESP + IV */	\
838 	sizeof(struct newah) + HASH_MAX_LEN		/* AH + ICV */))
839 static struct mbuf *
ipsec_prepend(struct mbuf * m,int len,int how)840 ipsec_prepend(struct mbuf *m, int len, int how)
841 {
842 	struct mbuf *n;
843 
844 	M_ASSERTPKTHDR(m);
845 	IPSEC_ASSERT(len < MHLEN, ("wrong length"));
846 	if (M_LEADINGSPACE(m) >= len) {
847 		/* No need to allocate new mbuf. */
848 		m->m_data -= len;
849 		m->m_len += len;
850 		m->m_pkthdr.len += len;
851 		return (m);
852 	}
853 	n = m_gethdr(how, m->m_type);
854 	if (n == NULL) {
855 		m_freem(m);
856 		return (NULL);
857 	}
858 	m_move_pkthdr(n, m);
859 	n->m_next = m;
860 	if (len + IPSEC_TRAILINGSPACE < M_SIZE(n))
861 		m_align(n, len + IPSEC_TRAILINGSPACE);
862 	n->m_len = len;
863 	n->m_pkthdr.len += len;
864 	return (n);
865 }
866 
867 static int
ipsec_encap(struct mbuf ** mp,struct secasindex * saidx)868 ipsec_encap(struct mbuf **mp, struct secasindex *saidx)
869 {
870 #ifdef INET6
871 	struct ip6_hdr *ip6;
872 #endif
873 	struct ip *ip;
874 	int setdf;
875 	uint8_t itos, proto;
876 
877 	ip = mtod(*mp, struct ip *);
878 	switch (ip->ip_v) {
879 #ifdef INET
880 	case IPVERSION:
881 		proto = IPPROTO_IPIP;
882 		/*
883 		 * Collect IP_DF state from the inner header
884 		 * and honor system-wide control of how to handle it.
885 		 */
886 		switch (V_ip4_ipsec_dfbit) {
887 		case 0:	/* clear in outer header */
888 		case 1:	/* set in outer header */
889 			setdf = V_ip4_ipsec_dfbit;
890 			break;
891 		default:/* propagate to outer header */
892 			setdf = (ip->ip_off & htons(IP_DF)) != 0;
893 		}
894 		itos = ip->ip_tos;
895 		break;
896 #endif
897 #ifdef INET6
898 	case (IPV6_VERSION >> 4):
899 		proto = IPPROTO_IPV6;
900 		ip6 = mtod(*mp, struct ip6_hdr *);
901 		itos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
902 		setdf = V_ip4_ipsec_dfbit ? 1: 0;
903 		/* scoped address handling */
904 		in6_clearscope(&ip6->ip6_src);
905 		in6_clearscope(&ip6->ip6_dst);
906 		break;
907 #endif
908 	default:
909 		return (EAFNOSUPPORT);
910 	}
911 	switch (saidx->dst.sa.sa_family) {
912 #ifdef INET
913 	case AF_INET:
914 		if (saidx->src.sa.sa_family != AF_INET ||
915 		    saidx->src.sin.sin_addr.s_addr == INADDR_ANY ||
916 		    saidx->dst.sin.sin_addr.s_addr == INADDR_ANY)
917 			return (EINVAL);
918 		*mp = ipsec_prepend(*mp, sizeof(struct ip), M_NOWAIT);
919 		if (*mp == NULL)
920 			return (ENOBUFS);
921 		ip = mtod(*mp, struct ip *);
922 		ip->ip_v = IPVERSION;
923 		ip->ip_hl = sizeof(struct ip) >> 2;
924 		ip->ip_p = proto;
925 		ip->ip_len = htons((*mp)->m_pkthdr.len);
926 		ip->ip_ttl = V_ip_defttl;
927 		ip->ip_sum = 0;
928 		ip->ip_off = setdf ? htons(IP_DF): 0;
929 		ip->ip_src = saidx->src.sin.sin_addr;
930 		ip->ip_dst = saidx->dst.sin.sin_addr;
931 		ip_ecn_ingress(V_ip4_ipsec_ecn, &ip->ip_tos, &itos);
932 		ip_fillid(ip);
933 		break;
934 #endif /* INET */
935 #ifdef INET6
936 	case AF_INET6:
937 		if (saidx->src.sa.sa_family != AF_INET6 ||
938 		    IN6_IS_ADDR_UNSPECIFIED(&saidx->src.sin6.sin6_addr) ||
939 		    IN6_IS_ADDR_UNSPECIFIED(&saidx->dst.sin6.sin6_addr))
940 			return (EINVAL);
941 		*mp = ipsec_prepend(*mp, sizeof(struct ip6_hdr), M_NOWAIT);
942 		if (*mp == NULL)
943 			return (ENOBUFS);
944 		ip6 = mtod(*mp, struct ip6_hdr *);
945 		ip6->ip6_flow = 0;
946 		ip6->ip6_vfc = IPV6_VERSION;
947 		ip6->ip6_hlim = V_ip6_defhlim;
948 		ip6->ip6_nxt = proto;
949 		ip6->ip6_dst = saidx->dst.sin6.sin6_addr;
950 		/* For link-local address embed scope zone id */
951 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
952 			ip6->ip6_dst.s6_addr16[1] =
953 			    htons(saidx->dst.sin6.sin6_scope_id & 0xffff);
954 		ip6->ip6_src = saidx->src.sin6.sin6_addr;
955 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
956 			ip6->ip6_src.s6_addr16[1] =
957 			    htons(saidx->src.sin6.sin6_scope_id & 0xffff);
958 		ip6->ip6_plen = htons((*mp)->m_pkthdr.len - sizeof(*ip6));
959 		ip_ecn_ingress(V_ip6_ipsec_ecn, &proto, &itos);
960 		ip6->ip6_flow |= htonl((uint32_t)proto << 20);
961 		break;
962 #endif /* INET6 */
963 	default:
964 		return (EAFNOSUPPORT);
965 	}
966 	(*mp)->m_flags &= ~(M_BCAST | M_MCAST);
967 	return (0);
968 }
969