xref: /freebsd/sys/netipsec/ipsec_output.c (revision be181ee2a28aa2b4b0e76684bce9f673ef668874)
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 <ae@FreeBSD.org>
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 #include <netinet/ip_icmp.h>
65 #include <netinet/tcp_var.h>
66 
67 #include <netinet/ip6.h>
68 #ifdef INET6
69 #include <netinet6/ip6_var.h>
70 #include <netinet6/scope6_var.h>
71 #endif
72 #include <netinet/in_pcb.h>
73 #ifdef INET6
74 #include <netinet/icmp6.h>
75 #endif
76 #if defined(SCTP) || defined(SCTP_SUPPORT)
77 #include <netinet/sctp_crc32.h>
78 #endif
79 
80 #include <netinet/udp.h>
81 #include <netipsec/ah.h>
82 #include <netipsec/esp.h>
83 #include <netipsec/ipsec.h>
84 #ifdef INET6
85 #include <netipsec/ipsec6.h>
86 #endif
87 #include <netipsec/ipsec_support.h>
88 #include <netipsec/ah_var.h>
89 #include <netipsec/esp_var.h>
90 #include <netipsec/ipcomp_var.h>
91 
92 #include <netipsec/xform.h>
93 
94 #include <netipsec/key.h>
95 #include <netipsec/keydb.h>
96 #include <netipsec/key_debug.h>
97 
98 #include <machine/in_cksum.h>
99 
100 #define	IPSEC_OSTAT_INC(proto, name)	do {		\
101 	if ((proto) == IPPROTO_ESP)	\
102 		ESPSTAT_INC(esps_##name);	\
103 	else if ((proto) == IPPROTO_AH)\
104 		AHSTAT_INC(ahs_##name);		\
105 	else					\
106 		IPCOMPSTAT_INC(ipcomps_##name);	\
107 } while (0)
108 
109 static int ipsec_encap(struct mbuf **mp, struct secasindex *saidx);
110 static size_t ipsec_get_pmtu(struct secasvar *sav);
111 
112 #ifdef INET
113 static struct secasvar *
114 ipsec4_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
115 {
116 	struct secasindex *saidx, tmpsaidx;
117 	struct ipsecrequest *isr;
118 	struct sockaddr_in *sin;
119 	struct secasvar *sav;
120 	struct ip *ip;
121 
122 	/*
123 	 * Check system global policy controls.
124 	 */
125 next:
126 	isr = sp->req[*pidx];
127 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
128 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
129 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
130 		DPRINTF(("%s: IPsec outbound packet dropped due"
131 			" to policy (check your sysctls)\n", __func__));
132 		IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
133 		*error = EHOSTUNREACH;
134 		return (NULL);
135 	}
136 	/*
137 	 * Craft SA index to search for proper SA.  Note that
138 	 * we only initialize unspecified SA peers for transport
139 	 * mode; for tunnel mode they must already be filled in.
140 	 */
141 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
142 		saidx = &tmpsaidx;
143 		*saidx = isr->saidx;
144 		ip = mtod(m, struct ip *);
145 		if (saidx->src.sa.sa_len == 0) {
146 			sin = &saidx->src.sin;
147 			sin->sin_len = sizeof(*sin);
148 			sin->sin_family = AF_INET;
149 			sin->sin_port = IPSEC_PORT_ANY;
150 			sin->sin_addr = ip->ip_src;
151 		}
152 		if (saidx->dst.sa.sa_len == 0) {
153 			sin = &saidx->dst.sin;
154 			sin->sin_len = sizeof(*sin);
155 			sin->sin_family = AF_INET;
156 			sin->sin_port = IPSEC_PORT_ANY;
157 			sin->sin_addr = ip->ip_dst;
158 		}
159 	} else
160 		saidx = &sp->req[*pidx]->saidx;
161 	/*
162 	 * Lookup SA and validate it.
163 	 */
164 	sav = key_allocsa_policy(sp, saidx, error);
165 	if (sav == NULL) {
166 		IPSECSTAT_INC(ips_out_nosa);
167 		if (*error != 0)
168 			return (NULL);
169 		if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
170 			/*
171 			 * We have no SA and policy that doesn't require
172 			 * this IPsec transform, thus we can continue w/o
173 			 * IPsec processing, i.e. return EJUSTRETURN.
174 			 * But first check if there is some bundled transform.
175 			 */
176 			if (sp->tcount > ++(*pidx))
177 				goto next;
178 			*error = EJUSTRETURN;
179 		}
180 		return (NULL);
181 	}
182 	IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
183 	return (sav);
184 }
185 
186 /*
187  * IPsec output logic for IPv4.
188  */
189 static int
190 ipsec4_perform_request(struct mbuf *m, struct secpolicy *sp,
191     struct inpcb *inp, u_int idx)
192 {
193 	struct ipsec_ctx_data ctx;
194 	union sockaddr_union *dst;
195 	struct secasvar *sav;
196 	struct ip *ip;
197 	int error, i, off;
198 
199 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
200 
201 	/*
202 	 * We hold the reference to SP. Content of SP couldn't be changed.
203 	 * Craft secasindex and do lookup for suitable SA.
204 	 * Then do encapsulation if needed and call xform's output.
205 	 * We need to store SP in the xform callback parameters.
206 	 * In xform callback we will extract SP and it can be used to
207 	 * determine next transform. At the end of transform we can
208 	 * release reference to SP.
209 	 */
210 	sav = ipsec4_allocsa(m, sp, &idx, &error);
211 	if (sav == NULL) {
212 		if (error == EJUSTRETURN) { /* No IPsec required */
213 			key_freesp(&sp);
214 			return (error);
215 		}
216 		goto bad;
217 	}
218 	/*
219 	 * XXXAE: most likely ip_sum at this point is wrong.
220 	 */
221 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET, IPSEC_ENC_BEFORE);
222 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
223 		goto bad;
224 
225 	ip = mtod(m, struct ip *);
226 	dst = &sav->sah->saidx.dst;
227 	/* Do the appropriate encapsulation, if necessary */
228 	if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
229 	    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
230 	    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
231 	     dst->sin.sin_addr.s_addr != INADDR_ANY &&
232 	     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
233 		/* Fix IPv4 header checksum and length */
234 		ip->ip_len = htons(m->m_pkthdr.len);
235 		ip->ip_sum = 0;
236 		ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
237 		error = ipsec_encap(&m, &sav->sah->saidx);
238 		if (error != 0) {
239 			DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
240 			    "with error %d\n", __func__, ntohl(sav->spi),
241 			    error));
242 			/* XXXAE: IPSEC_OSTAT_INC(tunnel); */
243 			goto bad;
244 		}
245 		inp = NULL;
246 	}
247 
248 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
249 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
250 		goto bad;
251 
252 	/*
253 	 * Dispatch to the appropriate IPsec transform logic.  The
254 	 * packet will be returned for transmission after crypto
255 	 * processing, etc. are completed.
256 	 *
257 	 * NB: m & sav are ``passed to caller'' who's responsible for
258 	 *     reclaiming their resources.
259 	 */
260 	switch(dst->sa.sa_family) {
261 	case AF_INET:
262 		ip = mtod(m, struct ip *);
263 		i = ip->ip_hl << 2;
264 		off = offsetof(struct ip, ip_p);
265 		break;
266 #ifdef INET6
267 	case AF_INET6:
268 		i = sizeof(struct ip6_hdr);
269 		off = offsetof(struct ip6_hdr, ip6_nxt);
270 		break;
271 #endif /* INET6 */
272 	default:
273 		DPRINTF(("%s: unsupported protocol family %u\n",
274 		    __func__, dst->sa.sa_family));
275 		error = EPFNOSUPPORT;
276 		IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
277 		goto bad;
278 	}
279 	error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
280 	return (error);
281 bad:
282 	IPSECSTAT_INC(ips_out_inval);
283 	if (m != NULL)
284 		m_freem(m);
285 	if (sav != NULL)
286 		key_freesav(&sav);
287 	key_freesp(&sp);
288 	return (error);
289 }
290 
291 int
292 ipsec4_process_packet(struct mbuf *m, struct secpolicy *sp,
293     struct inpcb *inp)
294 {
295 
296 	return (ipsec4_perform_request(m, sp, inp, 0));
297 }
298 
299 int
300 ipsec4_check_pmtu(struct mbuf *m, struct secpolicy *sp, int forwarding)
301 {
302 	struct secasvar *sav;
303 	struct ip *ip;
304 	size_t hlen, pmtu;
305 	uint32_t idx;
306 	int error;
307 
308 	/* Don't check PMTU if the frame won't have DF bit set. */
309 	if (!V_ip4_ipsec_dfbit)
310 		return (0);
311 	if (V_ip4_ipsec_dfbit == 1)
312 		goto setdf;
313 
314 	/* V_ip4_ipsec_dfbit > 1 - we will copy it from inner header. */
315 	ip = mtod(m, struct ip *);
316 	if (!(ip->ip_off & htons(IP_DF)))
317 		return (0);
318 
319 setdf:
320 	idx = sp->tcount - 1;
321 	sav = ipsec4_allocsa(m, sp, &idx, &error);
322 	if (sav == NULL) {
323 		key_freesp(&sp);
324 		/*
325 		 * No matching SA was found and SADB_ACQUIRE message was generated.
326 		 * Since we have matched a SP to this packet drop it silently.
327 		 */
328 		if (error == 0)
329 			error = EINPROGRESS;
330 		if (error != EJUSTRETURN)
331 			m_freem(m);
332 
333 		return (error);
334 	}
335 
336 	pmtu = ipsec_get_pmtu(sav);
337 	if (pmtu == 0) {
338 		key_freesav(&sav);
339 		return (0);
340 	}
341 
342 	hlen = ipsec_hdrsiz_internal(sp);
343 	key_freesav(&sav);
344 
345 	if (m_length(m, NULL) + hlen > pmtu) {
346 		/*
347 		 * If we're forwarding generate ICMP message here,
348 		 * so that it contains pmtu subtracted by header size.
349 		 * Set error to EINPROGRESS, in order for the frame
350 		 * to be dropped silently.
351 		 */
352 		if (forwarding) {
353 			if (pmtu > hlen)
354 				icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
355 				    0, pmtu - hlen);
356 			else
357 				m_freem(m);
358 
359 			key_freesp(&sp);
360 			return (EINPROGRESS); /* Pretend that we consumed it. */
361 		} else {
362 			m_freem(m);
363 			key_freesp(&sp);
364 			return (EMSGSIZE);
365 		}
366 	}
367 
368 	return (0);
369 }
370 
371 static int
372 ipsec4_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
373 {
374 	struct secpolicy *sp;
375 	int error;
376 
377 	/* Lookup for the corresponding outbound security policy */
378 	sp = ipsec4_checkpolicy(m, inp, &error, !forwarding);
379 	if (sp == NULL) {
380 		if (error == -EINVAL) {
381 			/* Discarded by policy. */
382 			m_freem(m);
383 			return (EACCES);
384 		}
385 		return (0); /* No IPsec required. */
386 	}
387 
388 	/*
389 	 * Usually we have to have tunnel mode IPsec security policy
390 	 * when we are forwarding a packet. Otherwise we could not handle
391 	 * encrypted replies, because they are not destined for us. But
392 	 * some users are doing source address translation for forwarded
393 	 * packets, and thus, even if they are forwarded, the replies will
394 	 * return back to us.
395 	 */
396 	if (!forwarding) {
397 		/*
398 		 * Do delayed checksums now because we send before
399 		 * this is done in the normal processing path.
400 		 */
401 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
402 			in_delayed_cksum(m);
403 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
404 		}
405 #if defined(SCTP) || defined(SCTP_SUPPORT)
406 		if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
407 			struct ip *ip;
408 
409 			ip = mtod(m, struct ip *);
410 			sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
411 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
412 		}
413 #endif
414 	}
415 	/* NB: callee frees mbuf and releases reference to SP */
416 	error = ipsec4_check_pmtu(m, sp, forwarding);
417 	if (error != 0) {
418 		if (error == EJUSTRETURN)
419 			return (0);
420 
421 		return (error);
422 	}
423 
424 	error = ipsec4_process_packet(m, sp, inp);
425 	if (error == EJUSTRETURN) {
426 		/*
427 		 * We had a SP with a level of 'use' and no SA. We
428 		 * will just continue to process the packet without
429 		 * IPsec processing and return without error.
430 		 */
431 		return (0);
432 	}
433 	if (error == 0)
434 		return (EINPROGRESS); /* consumed by IPsec */
435 	return (error);
436 }
437 
438 /*
439  * IPSEC_OUTPUT() method implementation for IPv4.
440  * 0 - no IPsec handling needed
441  * other values - mbuf consumed by IPsec.
442  */
443 int
444 ipsec4_output(struct mbuf *m, struct inpcb *inp)
445 {
446 
447 	/*
448 	 * If the packet is resubmitted to ip_output (e.g. after
449 	 * AH, ESP, etc. processing), there will be a tag to bypass
450 	 * the lookup and related policy checking.
451 	 */
452 	if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
453 		return (0);
454 
455 	return (ipsec4_common_output(m, inp, 0));
456 }
457 
458 /*
459  * IPSEC_FORWARD() method implementation for IPv4.
460  * 0 - no IPsec handling needed
461  * other values - mbuf consumed by IPsec.
462  */
463 int
464 ipsec4_forward(struct mbuf *m)
465 {
466 
467 	/*
468 	 * Check if this packet has an active inbound SP and needs to be
469 	 * dropped instead of forwarded.
470 	 */
471 	if (ipsec4_in_reject(m, NULL) != 0) {
472 		m_freem(m);
473 		return (EACCES);
474 	}
475 	return (ipsec4_common_output(m, NULL, 1));
476 }
477 #endif
478 
479 #ifdef INET6
480 static int
481 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
482     const struct in6_addr *ia)
483 {
484 	struct in6_addr ia2;
485 
486 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr)) {
487 		memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
488 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
489 		return (IN6_ARE_ADDR_EQUAL(ia, &ia2));
490 	}
491 	return (IN6_ARE_ADDR_EQUAL(&sa->sin6_addr, ia));
492 }
493 
494 static struct secasvar *
495 ipsec6_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
496 {
497 	struct secasindex *saidx, tmpsaidx;
498 	struct ipsecrequest *isr;
499 	struct sockaddr_in6 *sin6;
500 	struct secasvar *sav;
501 	struct ip6_hdr *ip6;
502 
503 	/*
504 	 * Check system global policy controls.
505 	 */
506 next:
507 	isr = sp->req[*pidx];
508 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
509 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
510 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
511 		DPRINTF(("%s: IPsec outbound packet dropped due"
512 			" to policy (check your sysctls)\n", __func__));
513 		IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
514 		*error = EHOSTUNREACH;
515 		return (NULL);
516 	}
517 	/*
518 	 * Craft SA index to search for proper SA.  Note that
519 	 * we only fillin unspecified SA peers for transport
520 	 * mode; for tunnel mode they must already be filled in.
521 	 */
522 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
523 		saidx = &tmpsaidx;
524 		*saidx = isr->saidx;
525 		ip6 = mtod(m, struct ip6_hdr *);
526 		if (saidx->src.sin6.sin6_len == 0) {
527 			sin6 = (struct sockaddr_in6 *)&saidx->src;
528 			sin6->sin6_len = sizeof(*sin6);
529 			sin6->sin6_family = AF_INET6;
530 			sin6->sin6_port = IPSEC_PORT_ANY;
531 			sin6->sin6_addr = ip6->ip6_src;
532 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
533 				/* fix scope id for comparing SPD */
534 				sin6->sin6_addr.s6_addr16[1] = 0;
535 				sin6->sin6_scope_id =
536 				    ntohs(ip6->ip6_src.s6_addr16[1]);
537 			}
538 		}
539 		if (saidx->dst.sin6.sin6_len == 0) {
540 			sin6 = (struct sockaddr_in6 *)&saidx->dst;
541 			sin6->sin6_len = sizeof(*sin6);
542 			sin6->sin6_family = AF_INET6;
543 			sin6->sin6_port = IPSEC_PORT_ANY;
544 			sin6->sin6_addr = ip6->ip6_dst;
545 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
546 				/* fix scope id for comparing SPD */
547 				sin6->sin6_addr.s6_addr16[1] = 0;
548 				sin6->sin6_scope_id =
549 				    ntohs(ip6->ip6_dst.s6_addr16[1]);
550 			}
551 		}
552 	} else
553 		saidx = &sp->req[*pidx]->saidx;
554 	/*
555 	 * Lookup SA and validate it.
556 	 */
557 	sav = key_allocsa_policy(sp, saidx, error);
558 	if (sav == NULL) {
559 		IPSEC6STAT_INC(ips_out_nosa);
560 		if (*error != 0)
561 			return (NULL);
562 		if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
563 			/*
564 			 * We have no SA and policy that doesn't require
565 			 * this IPsec transform, thus we can continue w/o
566 			 * IPsec processing, i.e. return EJUSTRETURN.
567 			 * But first check if there is some bundled transform.
568 			 */
569 			if (sp->tcount > ++(*pidx))
570 				goto next;
571 			*error = EJUSTRETURN;
572 		}
573 		return (NULL);
574 	}
575 	IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
576 	return (sav);
577 }
578 
579 /*
580  * IPsec output logic for IPv6.
581  */
582 static int
583 ipsec6_perform_request(struct mbuf *m, struct secpolicy *sp,
584     struct inpcb *inp, u_int idx)
585 {
586 	struct ipsec_ctx_data ctx;
587 	union sockaddr_union *dst;
588 	struct secasvar *sav;
589 	struct ip6_hdr *ip6;
590 	int error, i, off;
591 
592 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
593 
594 	sav = ipsec6_allocsa(m, sp, &idx, &error);
595 	if (sav == NULL) {
596 		if (error == EJUSTRETURN) { /* No IPsec required */
597 			key_freesp(&sp);
598 			return (error);
599 		}
600 		goto bad;
601 	}
602 
603 	/* Fix IP length in case if it is not set yet. */
604 	ip6 = mtod(m, struct ip6_hdr *);
605 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
606 
607 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET6, IPSEC_ENC_BEFORE);
608 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
609 		goto bad;
610 
611 	ip6 = mtod(m, struct ip6_hdr *); /* pfil can change mbuf */
612 	dst = &sav->sah->saidx.dst;
613 
614 	/* Do the appropriate encapsulation, if necessary */
615 	if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
616 	    dst->sa.sa_family != AF_INET6 ||        /* PF mismatch */
617 	    ((dst->sa.sa_family == AF_INET6) &&
618 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
619 	     (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
620 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
621 			/* No jumbogram support. */
622 			error = ENXIO;   /*XXX*/
623 			goto bad;
624 		}
625 		error = ipsec_encap(&m, &sav->sah->saidx);
626 		if (error != 0) {
627 			DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
628 			    "with error %d\n", __func__, ntohl(sav->spi),
629 			    error));
630 			/* XXXAE: IPSEC_OSTAT_INC(tunnel); */
631 			goto bad;
632 		}
633 		inp = NULL;
634 	}
635 
636 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
637 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
638 		goto bad;
639 
640 	switch(dst->sa.sa_family) {
641 #ifdef INET
642 	case AF_INET:
643 		{
644 		struct ip *ip;
645 		ip = mtod(m, struct ip *);
646 		i = ip->ip_hl << 2;
647 		off = offsetof(struct ip, ip_p);
648 		}
649 		break;
650 #endif /* AF_INET */
651 	case AF_INET6:
652 		i = sizeof(struct ip6_hdr);
653 		off = offsetof(struct ip6_hdr, ip6_nxt);
654 		break;
655 	default:
656 		DPRINTF(("%s: unsupported protocol family %u\n",
657 				 __func__, dst->sa.sa_family));
658 		error = EPFNOSUPPORT;
659 		IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
660 		goto bad;
661 	}
662 	error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
663 	return (error);
664 bad:
665 	IPSEC6STAT_INC(ips_out_inval);
666 	if (m != NULL)
667 		m_freem(m);
668 	if (sav != NULL)
669 		key_freesav(&sav);
670 	key_freesp(&sp);
671 	return (error);
672 }
673 
674 int
675 ipsec6_process_packet(struct mbuf *m, struct secpolicy *sp,
676     struct inpcb *inp)
677 {
678 
679 	return (ipsec6_perform_request(m, sp, inp, 0));
680 }
681 
682 /*
683  * IPv6 implementation is based on IPv4 implementation.
684  */
685 int
686 ipsec6_check_pmtu(struct mbuf *m, struct secpolicy *sp, int forwarding)
687 {
688 	struct secasvar *sav;
689 	size_t hlen, pmtu;
690 	uint32_t idx;
691 	int error;
692 
693 	/*
694 	 * According to RFC8200 L3 fragmentation is supposed to be done only on
695 	 * locally generated packets. During L3 forwarding packets that are too
696 	 * big are always supposed to be dropped, with an ICMPv6 packet being
697 	 * sent back.
698 	 */
699 	if (!forwarding)
700 		return (0);
701 
702 	idx = sp->tcount - 1;
703 	sav = ipsec6_allocsa(m, sp, &idx, &error);
704 	if (sav == NULL) {
705 		key_freesp(&sp);
706 		/*
707 		 * No matching SA was found and SADB_ACQUIRE message was generated.
708 		 * Since we have matched a SP to this packet drop it silently.
709 		 */
710 		if (error == 0)
711 			error = EINPROGRESS;
712 		if (error != EJUSTRETURN)
713 			m_freem(m);
714 
715 		return (error);
716 	}
717 
718 	pmtu = ipsec_get_pmtu(sav);
719 	if (pmtu == 0) {
720 		key_freesav(&sav);
721 		return (0);
722 	}
723 
724 	hlen = ipsec_hdrsiz_internal(sp);
725 	key_freesav(&sav);
726 
727 	if (m_length(m, NULL) + hlen > pmtu) {
728 		/*
729 		 * If we're forwarding generate ICMPv6 message here,
730 		 * so that it contains pmtu subtracted by header size.
731 		 * Set error to EINPROGRESS, in order for the frame
732 		 * to be dropped silently.
733 		 */
734 		if (forwarding) {
735 			if (pmtu > hlen)
736 				icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0, pmtu - hlen);
737 			else
738 				m_freem(m);
739 
740 			key_freesp(&sp);
741 			return (EINPROGRESS); /* Pretend that we consumed it. */
742 		}
743 	}
744 
745 	return (0);
746 }
747 
748 static int
749 ipsec6_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
750 {
751 	struct secpolicy *sp;
752 	int error;
753 
754 	/* Lookup for the corresponding outbound security policy */
755 	sp = ipsec6_checkpolicy(m, inp, &error, !forwarding);
756 	if (sp == NULL) {
757 		if (error == -EINVAL) {
758 			/* Discarded by policy. */
759 			m_freem(m);
760 			return (EACCES);
761 		}
762 		return (0); /* No IPsec required. */
763 	}
764 
765 	if (!forwarding) {
766 		/*
767 		 * Do delayed checksums now because we send before
768 		 * this is done in the normal processing path.
769 		 */
770 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
771 			in6_delayed_cksum(m, m->m_pkthdr.len -
772 			    sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
773 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
774 		}
775 #if defined(SCTP) || defined(SCTP_SUPPORT)
776 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
777 			sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
778 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
779 		}
780 #endif
781 	}
782 
783 	error = ipsec6_check_pmtu(m, sp, forwarding);
784 	if (error != 0) {
785 		if (error == EJUSTRETURN)
786 			return (0);
787 
788 		return (error);
789 	}
790 
791 	/* NB: callee frees mbuf and releases reference to SP */
792 	error = ipsec6_process_packet(m, sp, inp);
793 	if (error == EJUSTRETURN) {
794 		/*
795 		 * We had a SP with a level of 'use' and no SA. We
796 		 * will just continue to process the packet without
797 		 * IPsec processing and return without error.
798 		 */
799 		return (0);
800 	}
801 	if (error == 0)
802 		return (EINPROGRESS); /* consumed by IPsec */
803 	return (error);
804 }
805 
806 /*
807  * IPSEC_OUTPUT() method implementation for IPv6.
808  * 0 - no IPsec handling needed
809  * other values - mbuf consumed by IPsec.
810  */
811 int
812 ipsec6_output(struct mbuf *m, struct inpcb *inp)
813 {
814 
815 	/*
816 	 * If the packet is resubmitted to ip_output (e.g. after
817 	 * AH, ESP, etc. processing), there will be a tag to bypass
818 	 * the lookup and related policy checking.
819 	 */
820 	if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
821 		return (0);
822 
823 	return (ipsec6_common_output(m, inp, 0));
824 }
825 
826 /*
827  * IPSEC_FORWARD() method implementation for IPv6.
828  * 0 - no IPsec handling needed
829  * other values - mbuf consumed by IPsec.
830  */
831 int
832 ipsec6_forward(struct mbuf *m)
833 {
834 
835 	/*
836 	 * Check if this packet has an active inbound SP and needs to be
837 	 * dropped instead of forwarded.
838 	 */
839 	if (ipsec6_in_reject(m, NULL) != 0) {
840 		m_freem(m);
841 		return (EACCES);
842 	}
843 	return (ipsec6_common_output(m, NULL, 1));
844 }
845 #endif /* INET6 */
846 
847 int
848 ipsec_process_done(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
849     u_int idx)
850 {
851 	struct epoch_tracker et;
852 	struct xform_history *xh;
853 	struct secasindex *saidx;
854 	struct m_tag *mtag;
855 	int error;
856 
857 	saidx = &sav->sah->saidx;
858 	switch (saidx->dst.sa.sa_family) {
859 #ifdef INET
860 	case AF_INET:
861 		/* Fix the header length, for AH processing. */
862 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
863 		break;
864 #endif /* INET */
865 #ifdef INET6
866 	case AF_INET6:
867 		/* Fix the header length, for AH processing. */
868 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
869 			error = ENXIO;
870 			goto bad;
871 		}
872 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
873 			/* No jumbogram support. */
874 			error = ENXIO;	/*?*/
875 			goto bad;
876 		}
877 		mtod(m, struct ip6_hdr *)->ip6_plen =
878 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
879 		break;
880 #endif /* INET6 */
881 	default:
882 		DPRINTF(("%s: unknown protocol family %u\n", __func__,
883 		    saidx->dst.sa.sa_family));
884 		error = ENXIO;
885 		goto bad;
886 	}
887 
888 	/*
889 	 * Add a record of what we've done to the packet.
890 	 */
891 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, sizeof(*xh), M_NOWAIT);
892 	if (mtag == NULL) {
893 		DPRINTF(("%s: could not get packet tag\n", __func__));
894 		error = ENOMEM;
895 		goto bad;
896 	}
897 
898 	xh = (struct xform_history *)(mtag + 1);
899 	xh->dst = saidx->dst;
900 	xh->proto = saidx->proto;
901 	xh->mode = saidx->mode;
902 	xh->spi = sav->spi;
903 	m_tag_prepend(m, mtag);
904 
905 	key_sa_recordxfer(sav, m);		/* record data transfer */
906 
907 	/*
908 	 * If there's another (bundled) SA to apply, do so.
909 	 * Note that this puts a burden on the kernel stack size.
910 	 * If this is a problem we'll need to introduce a queue
911 	 * to set the packet on so we can unwind the stack before
912 	 * doing further processing.
913 	 */
914 	if (++idx < sp->tcount) {
915 		switch (saidx->dst.sa.sa_family) {
916 #ifdef INET
917 		case AF_INET:
918 			key_freesav(&sav);
919 			IPSECSTAT_INC(ips_out_bundlesa);
920 			return (ipsec4_perform_request(m, sp, NULL, idx));
921 			/* NOTREACHED */
922 #endif
923 #ifdef INET6
924 		case AF_INET6:
925 			key_freesav(&sav);
926 			IPSEC6STAT_INC(ips_out_bundlesa);
927 			return (ipsec6_perform_request(m, sp, NULL, idx));
928 			/* NOTREACHED */
929 #endif /* INET6 */
930 		default:
931 			DPRINTF(("%s: unknown protocol family %u\n", __func__,
932 			    saidx->dst.sa.sa_family));
933 			error = EPFNOSUPPORT;
934 			goto bad;
935 		}
936 	}
937 
938 	key_freesp(&sp), sp = NULL;	/* Release reference to SP */
939 #ifdef INET
940 	/*
941 	 * Do UDP encapsulation if SA requires it.
942 	 */
943 	if (sav->natt != NULL) {
944 		error = udp_ipsec_output(m, sav);
945 		if (error != 0)
946 			goto bad;
947 	}
948 #endif /* INET */
949 	/*
950 	 * We're done with IPsec processing, transmit the packet using the
951 	 * appropriate network protocol (IP or IPv6).
952 	 */
953 	NET_EPOCH_ENTER(et);
954 	switch (saidx->dst.sa.sa_family) {
955 #ifdef INET
956 	case AF_INET:
957 		key_freesav(&sav);
958 		error = ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
959 		break;
960 #endif /* INET */
961 #ifdef INET6
962 	case AF_INET6:
963 		key_freesav(&sav);
964 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
965 		break;
966 #endif /* INET6 */
967 	default:
968 		panic("ipsec_process_done");
969 	}
970 	NET_EPOCH_EXIT(et);
971 	return (error);
972 bad:
973 	m_freem(m);
974 	key_freesav(&sav);
975 	if (sp != NULL)
976 		key_freesp(&sp);
977 	return (error);
978 }
979 
980 /*
981  * ipsec_prepend() is optimized version of M_PREPEND().
982  * ipsec_encap() is called by IPsec output routine for tunnel mode SA.
983  * It is expected that after IP encapsulation some IPsec transform will
984  * be performed. Each IPsec transform inserts its variable length header
985  * just after outer IP header using m_makespace(). If given mbuf has not
986  * enough free space at the beginning, we allocate new mbuf and reserve
987  * some space at the beginning and at the end.
988  * This helps avoid allocating of new mbuf and data copying in m_makespace(),
989  * we place outer header in the middle of mbuf's data with reserved leading
990  * and trailing space:
991  *	[ LEADINGSPACE ][ Outer IP header ][ TRAILINGSPACE ]
992  * LEADINGSPACE will be used to add ethernet header, TRAILINGSPACE will
993  * be used to inject AH/ESP/IPCOMP header.
994  */
995 #define	IPSEC_TRAILINGSPACE	(sizeof(struct udphdr) +/* NAT-T */	\
996     max(sizeof(struct newesp) + EALG_MAX_BLOCK_LEN,	/* ESP + IV */	\
997 	sizeof(struct newah) + HASH_MAX_LEN		/* AH + ICV */))
998 static struct mbuf *
999 ipsec_prepend(struct mbuf *m, int len, int how)
1000 {
1001 	struct mbuf *n;
1002 
1003 	M_ASSERTPKTHDR(m);
1004 	IPSEC_ASSERT(len < MHLEN, ("wrong length"));
1005 	if (M_LEADINGSPACE(m) >= len) {
1006 		/* No need to allocate new mbuf. */
1007 		m->m_data -= len;
1008 		m->m_len += len;
1009 		m->m_pkthdr.len += len;
1010 		return (m);
1011 	}
1012 	n = m_gethdr(how, m->m_type);
1013 	if (n == NULL) {
1014 		m_freem(m);
1015 		return (NULL);
1016 	}
1017 	m_move_pkthdr(n, m);
1018 	n->m_next = m;
1019 	if (len + IPSEC_TRAILINGSPACE < M_SIZE(n))
1020 		m_align(n, len + IPSEC_TRAILINGSPACE);
1021 	n->m_len = len;
1022 	n->m_pkthdr.len += len;
1023 	return (n);
1024 }
1025 
1026 static size_t
1027 ipsec_get_pmtu(struct secasvar *sav)
1028 {
1029 	union sockaddr_union *dst;
1030 	struct in_conninfo inc;
1031 	size_t pmtu;
1032 
1033 	dst = &sav->sah->saidx.dst;
1034 	memset(&inc, 0, sizeof(inc));
1035 
1036 	switch (dst->sa.sa_family) {
1037 #ifdef INET
1038 	case AF_INET:
1039 		inc.inc_faddr = satosin(&dst->sa)->sin_addr;
1040 		break;
1041 #endif
1042 #ifdef INET6
1043 	case AF_INET6:
1044 		inc.inc6_faddr = satosin6(&dst->sa)->sin6_addr;
1045 		inc.inc_flags |= INC_ISIPV6;
1046 		break;
1047 #endif
1048 	default:
1049 		return (0);
1050 	}
1051 
1052 	pmtu = tcp_hc_getmtu(&inc);
1053 	if (pmtu != 0)
1054 		return (pmtu);
1055 
1056 	/* No entry in hostcache. Assume that PMTU is equal to link's MTU */
1057 	switch (dst->sa.sa_family) {
1058 #ifdef INET
1059 	case AF_INET:
1060 		pmtu = tcp_maxmtu(&inc, NULL);
1061 		break;
1062 #endif
1063 #ifdef INET6
1064 	case AF_INET6:
1065 		pmtu = tcp_maxmtu6(&inc, NULL);
1066 		break;
1067 #endif
1068 	default:
1069 		return (0);
1070 	}
1071 	if (pmtu == 0)
1072 		return (0);
1073 
1074 	tcp_hc_updatemtu(&inc, pmtu);
1075 
1076 	return (pmtu);
1077 }
1078 
1079 static int
1080 ipsec_encap(struct mbuf **mp, struct secasindex *saidx)
1081 {
1082 #ifdef INET6
1083 	struct ip6_hdr *ip6;
1084 #endif
1085 	struct ip *ip;
1086 #ifdef INET
1087 	int setdf;
1088 #endif
1089 	uint8_t itos, proto;
1090 
1091 	ip = mtod(*mp, struct ip *);
1092 	switch (ip->ip_v) {
1093 #ifdef INET
1094 	case IPVERSION:
1095 		proto = IPPROTO_IPIP;
1096 		/*
1097 		 * Collect IP_DF state from the inner header
1098 		 * and honor system-wide control of how to handle it.
1099 		 */
1100 		switch (V_ip4_ipsec_dfbit) {
1101 		case 0:	/* clear in outer header */
1102 		case 1:	/* set in outer header */
1103 			setdf = V_ip4_ipsec_dfbit;
1104 			break;
1105 		default:/* propagate to outer header */
1106 			setdf = (ip->ip_off & htons(IP_DF)) != 0;
1107 		}
1108 		itos = ip->ip_tos;
1109 		break;
1110 #endif
1111 #ifdef INET6
1112 	case (IPV6_VERSION >> 4):
1113 		proto = IPPROTO_IPV6;
1114 		ip6 = mtod(*mp, struct ip6_hdr *);
1115 		itos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1116 		/* scoped address handling */
1117 		in6_clearscope(&ip6->ip6_src);
1118 		in6_clearscope(&ip6->ip6_dst);
1119 		break;
1120 #endif
1121 	default:
1122 		return (EAFNOSUPPORT);
1123 	}
1124 	switch (saidx->dst.sa.sa_family) {
1125 #ifdef INET
1126 	case AF_INET:
1127 		if (saidx->src.sa.sa_family != AF_INET ||
1128 		    saidx->src.sin.sin_addr.s_addr == INADDR_ANY ||
1129 		    saidx->dst.sin.sin_addr.s_addr == INADDR_ANY)
1130 			return (EINVAL);
1131 		*mp = ipsec_prepend(*mp, sizeof(struct ip), M_NOWAIT);
1132 		if (*mp == NULL)
1133 			return (ENOBUFS);
1134 		ip = mtod(*mp, struct ip *);
1135 		ip->ip_v = IPVERSION;
1136 		ip->ip_hl = sizeof(struct ip) >> 2;
1137 		ip->ip_p = proto;
1138 		ip->ip_len = htons((*mp)->m_pkthdr.len);
1139 		ip->ip_ttl = V_ip_defttl;
1140 		ip->ip_sum = 0;
1141 		ip->ip_off = setdf ? htons(IP_DF): 0;
1142 		ip->ip_src = saidx->src.sin.sin_addr;
1143 		ip->ip_dst = saidx->dst.sin.sin_addr;
1144 		ip_ecn_ingress(V_ip4_ipsec_ecn, &ip->ip_tos, &itos);
1145 		ip_fillid(ip);
1146 		break;
1147 #endif /* INET */
1148 #ifdef INET6
1149 	case AF_INET6:
1150 		if (saidx->src.sa.sa_family != AF_INET6 ||
1151 		    IN6_IS_ADDR_UNSPECIFIED(&saidx->src.sin6.sin6_addr) ||
1152 		    IN6_IS_ADDR_UNSPECIFIED(&saidx->dst.sin6.sin6_addr))
1153 			return (EINVAL);
1154 		*mp = ipsec_prepend(*mp, sizeof(struct ip6_hdr), M_NOWAIT);
1155 		if (*mp == NULL)
1156 			return (ENOBUFS);
1157 		ip6 = mtod(*mp, struct ip6_hdr *);
1158 		ip6->ip6_flow = 0;
1159 		ip6->ip6_vfc = IPV6_VERSION;
1160 		ip6->ip6_hlim = V_ip6_defhlim;
1161 		ip6->ip6_nxt = proto;
1162 		ip6->ip6_dst = saidx->dst.sin6.sin6_addr;
1163 		/* For link-local address embed scope zone id */
1164 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
1165 			ip6->ip6_dst.s6_addr16[1] =
1166 			    htons(saidx->dst.sin6.sin6_scope_id & 0xffff);
1167 		ip6->ip6_src = saidx->src.sin6.sin6_addr;
1168 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
1169 			ip6->ip6_src.s6_addr16[1] =
1170 			    htons(saidx->src.sin6.sin6_scope_id & 0xffff);
1171 		ip6->ip6_plen = htons((*mp)->m_pkthdr.len - sizeof(*ip6));
1172 		ip_ecn_ingress(V_ip6_ipsec_ecn, &proto, &itos);
1173 		ip6->ip6_flow |= htonl((uint32_t)proto << 20);
1174 		break;
1175 #endif /* INET6 */
1176 	default:
1177 		return (EAFNOSUPPORT);
1178 	}
1179 	(*mp)->m_flags &= ~(M_BCAST | M_MCAST);
1180 	return (0);
1181 }
1182