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