xref: /freebsd/sys/netipsec/ipsec_output.c (revision b4220bf387e62f59d73308f122f5eea887a59d58)
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 	/* 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 	dst = &sav->sah->saidx.dst;
337 	memset(&inc, 0, sizeof(inc));
338 	switch (dst->sa.sa_family) {
339 	case AF_INET:
340 		inc.inc_faddr = satosin(&dst->sa)->sin_addr;
341 		break;
342 #ifdef INET6
343 	case AF_INET6:
344 		inc.inc6_faddr = satosin6(&dst->sa)->sin6_addr;
345 		inc.inc_flags |= INC_ISIPV6;
346 		break;
347 #endif
348 	default:
349 		key_freesav(&sav);
350 		return (0);
351 	}
352 
353 	key_freesav(&sav);
354 	pmtu = tcp_hc_getmtu(&inc);
355 	/* No entry in hostcache. Use link MTU instead. */
356 	if (pmtu == 0) {
357 		switch (dst->sa.sa_family) {
358 		case AF_INET:
359 			pmtu = tcp_maxmtu(&inc, NULL);
360 			break;
361 #ifdef INET6
362 		case AF_INET6:
363 			pmtu = tcp_maxmtu6(&inc, NULL);
364 			break;
365 #endif
366 		}
367 		if (pmtu == 0)
368 			return (0);
369 
370 		tcp_hc_updatemtu(&inc, pmtu);
371 	}
372 
373 	hlen = ipsec_hdrsiz_internal(sp);
374 	if (m_length(m, NULL) + hlen > pmtu) {
375 		/*
376 		 * If we're forwarding generate ICMP message here,
377 		 * so that it contains pmtu substraced by header size.
378 		 * Set error to EINPROGRESS, in order for the frame
379 		 * to be dropped silently.
380 		 */
381 		if (forwarding) {
382 			if (pmtu > hlen)
383 				icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
384 				    0, pmtu - hlen);
385 			else
386 				m_freem(m);
387 
388 			key_freesp(&sp);
389 			return (EINPROGRESS); /* Pretend that we consumed it. */
390 		} else {
391 			m_freem(m);
392 			key_freesp(&sp);
393 			return (EMSGSIZE);
394 		}
395 	}
396 
397 	return (0);
398 }
399 
400 static int
401 ipsec4_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
402 {
403 	struct secpolicy *sp;
404 	int error;
405 
406 	/* Lookup for the corresponding outbound security policy */
407 	sp = ipsec4_checkpolicy(m, inp, &error, !forwarding);
408 	if (sp == NULL) {
409 		if (error == -EINVAL) {
410 			/* Discarded by policy. */
411 			m_freem(m);
412 			return (EACCES);
413 		}
414 		return (0); /* No IPsec required. */
415 	}
416 
417 	/*
418 	 * Usually we have to have tunnel mode IPsec security policy
419 	 * when we are forwarding a packet. Otherwise we could not handle
420 	 * encrypted replies, because they are not destined for us. But
421 	 * some users are doing source address translation for forwarded
422 	 * packets, and thus, even if they are forwarded, the replies will
423 	 * return back to us.
424 	 */
425 	if (!forwarding) {
426 		/*
427 		 * Do delayed checksums now because we send before
428 		 * this is done in the normal processing path.
429 		 */
430 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
431 			m = mb_unmapped_to_ext(m);
432 			if (m == NULL) {
433 				IPSECSTAT_INC(ips_out_nomem);
434 				key_freesp(&sp);
435 				return (ENOBUFS);
436 			}
437 			in_delayed_cksum(m);
438 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
439 		}
440 #if defined(SCTP) || defined(SCTP_SUPPORT)
441 		if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
442 			struct ip *ip;
443 
444 			m = mb_unmapped_to_ext(m);
445 			if (m == NULL) {
446 				IPSECSTAT_INC(ips_out_nomem);
447 				key_freesp(&sp);
448 				return (ENOBUFS);
449 			}
450 			ip = mtod(m, struct ip *);
451 			sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
452 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
453 		}
454 #endif
455 	}
456 	/* NB: callee frees mbuf and releases reference to SP */
457 	error = ipsec4_check_pmtu(m, sp, forwarding);
458 	if (error != 0) {
459 		if (error == EJUSTRETURN)
460 			return (0);
461 
462 		return (error);
463 	}
464 
465 	error = ipsec4_process_packet(m, sp, inp);
466 	if (error == EJUSTRETURN) {
467 		/*
468 		 * We had a SP with a level of 'use' and no SA. We
469 		 * will just continue to process the packet without
470 		 * IPsec processing and return without error.
471 		 */
472 		return (0);
473 	}
474 	if (error == 0)
475 		return (EINPROGRESS); /* consumed by IPsec */
476 	return (error);
477 }
478 
479 /*
480  * IPSEC_OUTPUT() method implementation for IPv4.
481  * 0 - no IPsec handling needed
482  * other values - mbuf consumed by IPsec.
483  */
484 int
485 ipsec4_output(struct mbuf *m, struct inpcb *inp)
486 {
487 
488 	/*
489 	 * If the packet is resubmitted to ip_output (e.g. after
490 	 * AH, ESP, etc. processing), there will be a tag to bypass
491 	 * the lookup and related policy checking.
492 	 */
493 	if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
494 		return (0);
495 
496 	return (ipsec4_common_output(m, inp, 0));
497 }
498 
499 /*
500  * IPSEC_FORWARD() method implementation for IPv4.
501  * 0 - no IPsec handling needed
502  * other values - mbuf consumed by IPsec.
503  */
504 int
505 ipsec4_forward(struct mbuf *m)
506 {
507 
508 	/*
509 	 * Check if this packet has an active inbound SP and needs to be
510 	 * dropped instead of forwarded.
511 	 */
512 	if (ipsec4_in_reject(m, NULL) != 0) {
513 		m_freem(m);
514 		return (EACCES);
515 	}
516 	return (ipsec4_common_output(m, NULL, 1));
517 }
518 #endif
519 
520 #ifdef INET6
521 static int
522 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
523     const struct in6_addr *ia)
524 {
525 	struct in6_addr ia2;
526 
527 	if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr)) {
528 		memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
529 		ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
530 		return (IN6_ARE_ADDR_EQUAL(ia, &ia2));
531 	}
532 	return (IN6_ARE_ADDR_EQUAL(&sa->sin6_addr, ia));
533 }
534 
535 static struct secasvar *
536 ipsec6_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
537 {
538 	struct secasindex *saidx, tmpsaidx;
539 	struct ipsecrequest *isr;
540 	struct sockaddr_in6 *sin6;
541 	struct secasvar *sav;
542 	struct ip6_hdr *ip6;
543 
544 	/*
545 	 * Check system global policy controls.
546 	 */
547 next:
548 	isr = sp->req[*pidx];
549 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
550 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
551 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
552 		DPRINTF(("%s: IPsec outbound packet dropped due"
553 			" to policy (check your sysctls)\n", __func__));
554 		IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
555 		*error = EHOSTUNREACH;
556 		return (NULL);
557 	}
558 	/*
559 	 * Craft SA index to search for proper SA.  Note that
560 	 * we only fillin unspecified SA peers for transport
561 	 * mode; for tunnel mode they must already be filled in.
562 	 */
563 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
564 		saidx = &tmpsaidx;
565 		*saidx = isr->saidx;
566 		ip6 = mtod(m, struct ip6_hdr *);
567 		if (saidx->src.sin6.sin6_len == 0) {
568 			sin6 = (struct sockaddr_in6 *)&saidx->src;
569 			sin6->sin6_len = sizeof(*sin6);
570 			sin6->sin6_family = AF_INET6;
571 			sin6->sin6_port = IPSEC_PORT_ANY;
572 			sin6->sin6_addr = ip6->ip6_src;
573 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
574 				/* fix scope id for comparing SPD */
575 				sin6->sin6_addr.s6_addr16[1] = 0;
576 				sin6->sin6_scope_id =
577 				    ntohs(ip6->ip6_src.s6_addr16[1]);
578 			}
579 		}
580 		if (saidx->dst.sin6.sin6_len == 0) {
581 			sin6 = (struct sockaddr_in6 *)&saidx->dst;
582 			sin6->sin6_len = sizeof(*sin6);
583 			sin6->sin6_family = AF_INET6;
584 			sin6->sin6_port = IPSEC_PORT_ANY;
585 			sin6->sin6_addr = ip6->ip6_dst;
586 			if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
587 				/* fix scope id for comparing SPD */
588 				sin6->sin6_addr.s6_addr16[1] = 0;
589 				sin6->sin6_scope_id =
590 				    ntohs(ip6->ip6_dst.s6_addr16[1]);
591 			}
592 		}
593 	} else
594 		saidx = &sp->req[*pidx]->saidx;
595 	/*
596 	 * Lookup SA and validate it.
597 	 */
598 	sav = key_allocsa_policy(sp, saidx, error);
599 	if (sav == NULL) {
600 		IPSEC6STAT_INC(ips_out_nosa);
601 		if (*error != 0)
602 			return (NULL);
603 		if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
604 			/*
605 			 * We have no SA and policy that doesn't require
606 			 * this IPsec transform, thus we can continue w/o
607 			 * IPsec processing, i.e. return EJUSTRETURN.
608 			 * But first check if there is some bundled transform.
609 			 */
610 			if (sp->tcount > ++(*pidx))
611 				goto next;
612 			*error = EJUSTRETURN;
613 		}
614 		return (NULL);
615 	}
616 	IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
617 	return (sav);
618 }
619 
620 /*
621  * IPsec output logic for IPv6.
622  */
623 static int
624 ipsec6_perform_request(struct mbuf *m, struct secpolicy *sp,
625     struct inpcb *inp, u_int idx)
626 {
627 	struct ipsec_ctx_data ctx;
628 	union sockaddr_union *dst;
629 	struct secasvar *sav;
630 	struct ip6_hdr *ip6;
631 	int error, i, off;
632 
633 	IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
634 
635 	sav = ipsec6_allocsa(m, sp, &idx, &error);
636 	if (sav == NULL) {
637 		if (error == EJUSTRETURN) { /* No IPsec required */
638 			key_freesp(&sp);
639 			return (error);
640 		}
641 		goto bad;
642 	}
643 
644 	/* Fix IP length in case if it is not set yet. */
645 	ip6 = mtod(m, struct ip6_hdr *);
646 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
647 
648 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET6, IPSEC_ENC_BEFORE);
649 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
650 		goto bad;
651 
652 	ip6 = mtod(m, struct ip6_hdr *); /* pfil can change mbuf */
653 	dst = &sav->sah->saidx.dst;
654 
655 	/* Do the appropriate encapsulation, if necessary */
656 	if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
657 	    dst->sa.sa_family != AF_INET6 ||        /* PF mismatch */
658 	    ((dst->sa.sa_family == AF_INET6) &&
659 	     (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
660 	     (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
661 		if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
662 			/* No jumbogram support. */
663 			error = ENXIO;   /*XXX*/
664 			goto bad;
665 		}
666 		error = ipsec_encap(&m, &sav->sah->saidx);
667 		if (error != 0) {
668 			DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
669 			    "with error %d\n", __func__, ntohl(sav->spi),
670 			    error));
671 			/* XXXAE: IPSEC_OSTAT_INC(tunnel); */
672 			goto bad;
673 		}
674 		inp = NULL;
675 	}
676 
677 	IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
678 	if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
679 		goto bad;
680 
681 	switch(dst->sa.sa_family) {
682 #ifdef INET
683 	case AF_INET:
684 		{
685 		struct ip *ip;
686 		ip = mtod(m, struct ip *);
687 		i = ip->ip_hl << 2;
688 		off = offsetof(struct ip, ip_p);
689 		}
690 		break;
691 #endif /* AF_INET */
692 	case AF_INET6:
693 		i = sizeof(struct ip6_hdr);
694 		off = offsetof(struct ip6_hdr, ip6_nxt);
695 		break;
696 	default:
697 		DPRINTF(("%s: unsupported protocol family %u\n",
698 				 __func__, dst->sa.sa_family));
699 		error = EPFNOSUPPORT;
700 		IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
701 		goto bad;
702 	}
703 	error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
704 	return (error);
705 bad:
706 	IPSEC6STAT_INC(ips_out_inval);
707 	if (m != NULL)
708 		m_freem(m);
709 	if (sav != NULL)
710 		key_freesav(&sav);
711 	key_freesp(&sp);
712 	return (error);
713 }
714 
715 int
716 ipsec6_process_packet(struct mbuf *m, struct secpolicy *sp,
717     struct inpcb *inp)
718 {
719 
720 	return (ipsec6_perform_request(m, sp, inp, 0));
721 }
722 
723 static int
724 ipsec6_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
725 {
726 	struct secpolicy *sp;
727 	int error;
728 
729 	/* Lookup for the corresponding outbound security policy */
730 	sp = ipsec6_checkpolicy(m, inp, &error, !forwarding);
731 	if (sp == NULL) {
732 		if (error == -EINVAL) {
733 			/* Discarded by policy. */
734 			m_freem(m);
735 			return (EACCES);
736 		}
737 		return (0); /* No IPsec required. */
738 	}
739 
740 	if (!forwarding) {
741 		/*
742 		 * Do delayed checksums now because we send before
743 		 * this is done in the normal processing path.
744 		 */
745 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
746 			m = mb_unmapped_to_ext(m);
747 			if (m == NULL) {
748 				IPSEC6STAT_INC(ips_out_nomem);
749 				key_freesp(&sp);
750 				return (ENOBUFS);
751 			}
752 			in6_delayed_cksum(m, m->m_pkthdr.len -
753 			    sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
754 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
755 		}
756 #if defined(SCTP) || defined(SCTP_SUPPORT)
757 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
758 			m = mb_unmapped_to_ext(m);
759 			if (m == NULL) {
760 				IPSEC6STAT_INC(ips_out_nomem);
761 				key_freesp(&sp);
762 				return (ENOBUFS);
763 			}
764 			sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
765 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
766 		}
767 #endif
768 	}
769 	/* NB: callee frees mbuf and releases reference to SP */
770 	error = ipsec6_process_packet(m, sp, inp);
771 	if (error == EJUSTRETURN) {
772 		/*
773 		 * We had a SP with a level of 'use' and no SA. We
774 		 * will just continue to process the packet without
775 		 * IPsec processing and return without error.
776 		 */
777 		return (0);
778 	}
779 	if (error == 0)
780 		return (EINPROGRESS); /* consumed by IPsec */
781 	return (error);
782 }
783 
784 /*
785  * IPSEC_OUTPUT() method implementation for IPv6.
786  * 0 - no IPsec handling needed
787  * other values - mbuf consumed by IPsec.
788  */
789 int
790 ipsec6_output(struct mbuf *m, struct inpcb *inp)
791 {
792 
793 	/*
794 	 * If the packet is resubmitted to ip_output (e.g. after
795 	 * AH, ESP, etc. processing), there will be a tag to bypass
796 	 * the lookup and related policy checking.
797 	 */
798 	if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
799 		return (0);
800 
801 	return (ipsec6_common_output(m, inp, 0));
802 }
803 
804 /*
805  * IPSEC_FORWARD() method implementation for IPv6.
806  * 0 - no IPsec handling needed
807  * other values - mbuf consumed by IPsec.
808  */
809 int
810 ipsec6_forward(struct mbuf *m)
811 {
812 
813 	/*
814 	 * Check if this packet has an active inbound SP and needs to be
815 	 * dropped instead of forwarded.
816 	 */
817 	if (ipsec6_in_reject(m, NULL) != 0) {
818 		m_freem(m);
819 		return (EACCES);
820 	}
821 	return (ipsec6_common_output(m, NULL, 1));
822 }
823 #endif /* INET6 */
824 
825 int
826 ipsec_process_done(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
827     u_int idx)
828 {
829 	struct epoch_tracker et;
830 	struct xform_history *xh;
831 	struct secasindex *saidx;
832 	struct m_tag *mtag;
833 	int error;
834 
835 	saidx = &sav->sah->saidx;
836 	switch (saidx->dst.sa.sa_family) {
837 #ifdef INET
838 	case AF_INET:
839 		/* Fix the header length, for AH processing. */
840 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
841 		break;
842 #endif /* INET */
843 #ifdef INET6
844 	case AF_INET6:
845 		/* Fix the header length, for AH processing. */
846 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
847 			error = ENXIO;
848 			goto bad;
849 		}
850 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
851 			/* No jumbogram support. */
852 			error = ENXIO;	/*?*/
853 			goto bad;
854 		}
855 		mtod(m, struct ip6_hdr *)->ip6_plen =
856 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
857 		break;
858 #endif /* INET6 */
859 	default:
860 		DPRINTF(("%s: unknown protocol family %u\n", __func__,
861 		    saidx->dst.sa.sa_family));
862 		error = ENXIO;
863 		goto bad;
864 	}
865 
866 	/*
867 	 * Add a record of what we've done to the packet.
868 	 */
869 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, sizeof(*xh), M_NOWAIT);
870 	if (mtag == NULL) {
871 		DPRINTF(("%s: could not get packet tag\n", __func__));
872 		error = ENOMEM;
873 		goto bad;
874 	}
875 
876 	xh = (struct xform_history *)(mtag + 1);
877 	xh->dst = saidx->dst;
878 	xh->proto = saidx->proto;
879 	xh->mode = saidx->mode;
880 	xh->spi = sav->spi;
881 	m_tag_prepend(m, mtag);
882 
883 	key_sa_recordxfer(sav, m);		/* record data transfer */
884 
885 	/*
886 	 * If there's another (bundled) SA to apply, do so.
887 	 * Note that this puts a burden on the kernel stack size.
888 	 * If this is a problem we'll need to introduce a queue
889 	 * to set the packet on so we can unwind the stack before
890 	 * doing further processing.
891 	 */
892 	if (++idx < sp->tcount) {
893 		switch (saidx->dst.sa.sa_family) {
894 #ifdef INET
895 		case AF_INET:
896 			key_freesav(&sav);
897 			IPSECSTAT_INC(ips_out_bundlesa);
898 			return (ipsec4_perform_request(m, sp, NULL, idx));
899 			/* NOTREACHED */
900 #endif
901 #ifdef INET6
902 		case AF_INET6:
903 			key_freesav(&sav);
904 			IPSEC6STAT_INC(ips_out_bundlesa);
905 			return (ipsec6_perform_request(m, sp, NULL, idx));
906 			/* NOTREACHED */
907 #endif /* INET6 */
908 		default:
909 			DPRINTF(("%s: unknown protocol family %u\n", __func__,
910 			    saidx->dst.sa.sa_family));
911 			error = EPFNOSUPPORT;
912 			goto bad;
913 		}
914 	}
915 
916 	key_freesp(&sp), sp = NULL;	/* Release reference to SP */
917 #ifdef INET
918 	/*
919 	 * Do UDP encapsulation if SA requires it.
920 	 */
921 	if (sav->natt != NULL) {
922 		error = udp_ipsec_output(m, sav);
923 		if (error != 0)
924 			goto bad;
925 	}
926 #endif /* INET */
927 	/*
928 	 * We're done with IPsec processing, transmit the packet using the
929 	 * appropriate network protocol (IP or IPv6).
930 	 */
931 	NET_EPOCH_ENTER(et);
932 	switch (saidx->dst.sa.sa_family) {
933 #ifdef INET
934 	case AF_INET:
935 		key_freesav(&sav);
936 		error = ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
937 		break;
938 #endif /* INET */
939 #ifdef INET6
940 	case AF_INET6:
941 		key_freesav(&sav);
942 		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
943 		break;
944 #endif /* INET6 */
945 	default:
946 		panic("ipsec_process_done");
947 	}
948 	NET_EPOCH_EXIT(et);
949 	return (error);
950 bad:
951 	m_freem(m);
952 	key_freesav(&sav);
953 	if (sp != NULL)
954 		key_freesp(&sp);
955 	return (error);
956 }
957 
958 /*
959  * ipsec_prepend() is optimized version of M_PREPEND().
960  * ipsec_encap() is called by IPsec output routine for tunnel mode SA.
961  * It is expected that after IP encapsulation some IPsec transform will
962  * be performed. Each IPsec transform inserts its variable length header
963  * just after outer IP header using m_makespace(). If given mbuf has not
964  * enough free space at the beginning, we allocate new mbuf and reserve
965  * some space at the beginning and at the end.
966  * This helps avoid allocating of new mbuf and data copying in m_makespace(),
967  * we place outer header in the middle of mbuf's data with reserved leading
968  * and trailing space:
969  *	[ LEADINGSPACE ][ Outer IP header ][ TRAILINGSPACE ]
970  * LEADINGSPACE will be used to add ethernet header, TRAILINGSPACE will
971  * be used to inject AH/ESP/IPCOMP header.
972  */
973 #define	IPSEC_TRAILINGSPACE	(sizeof(struct udphdr) +/* NAT-T */	\
974     max(sizeof(struct newesp) + EALG_MAX_BLOCK_LEN,	/* ESP + IV */	\
975 	sizeof(struct newah) + HASH_MAX_LEN		/* AH + ICV */))
976 static struct mbuf *
977 ipsec_prepend(struct mbuf *m, int len, int how)
978 {
979 	struct mbuf *n;
980 
981 	M_ASSERTPKTHDR(m);
982 	IPSEC_ASSERT(len < MHLEN, ("wrong length"));
983 	if (M_LEADINGSPACE(m) >= len) {
984 		/* No need to allocate new mbuf. */
985 		m->m_data -= len;
986 		m->m_len += len;
987 		m->m_pkthdr.len += len;
988 		return (m);
989 	}
990 	n = m_gethdr(how, m->m_type);
991 	if (n == NULL) {
992 		m_freem(m);
993 		return (NULL);
994 	}
995 	m_move_pkthdr(n, m);
996 	n->m_next = m;
997 	if (len + IPSEC_TRAILINGSPACE < M_SIZE(n))
998 		m_align(n, len + IPSEC_TRAILINGSPACE);
999 	n->m_len = len;
1000 	n->m_pkthdr.len += len;
1001 	return (n);
1002 }
1003 
1004 static int
1005 ipsec_encap(struct mbuf **mp, struct secasindex *saidx)
1006 {
1007 #ifdef INET6
1008 	struct ip6_hdr *ip6;
1009 #endif
1010 	struct ip *ip;
1011 	int setdf;
1012 	uint8_t itos, proto;
1013 
1014 	ip = mtod(*mp, struct ip *);
1015 	switch (ip->ip_v) {
1016 #ifdef INET
1017 	case IPVERSION:
1018 		proto = IPPROTO_IPIP;
1019 		/*
1020 		 * Collect IP_DF state from the inner header
1021 		 * and honor system-wide control of how to handle it.
1022 		 */
1023 		switch (V_ip4_ipsec_dfbit) {
1024 		case 0:	/* clear in outer header */
1025 		case 1:	/* set in outer header */
1026 			setdf = V_ip4_ipsec_dfbit;
1027 			break;
1028 		default:/* propagate to outer header */
1029 			setdf = (ip->ip_off & htons(IP_DF)) != 0;
1030 		}
1031 		itos = ip->ip_tos;
1032 		break;
1033 #endif
1034 #ifdef INET6
1035 	case (IPV6_VERSION >> 4):
1036 		proto = IPPROTO_IPV6;
1037 		ip6 = mtod(*mp, struct ip6_hdr *);
1038 		itos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1039 		setdf = V_ip4_ipsec_dfbit ? 1: 0;
1040 		/* scoped address handling */
1041 		in6_clearscope(&ip6->ip6_src);
1042 		in6_clearscope(&ip6->ip6_dst);
1043 		break;
1044 #endif
1045 	default:
1046 		return (EAFNOSUPPORT);
1047 	}
1048 	switch (saidx->dst.sa.sa_family) {
1049 #ifdef INET
1050 	case AF_INET:
1051 		if (saidx->src.sa.sa_family != AF_INET ||
1052 		    saidx->src.sin.sin_addr.s_addr == INADDR_ANY ||
1053 		    saidx->dst.sin.sin_addr.s_addr == INADDR_ANY)
1054 			return (EINVAL);
1055 		*mp = ipsec_prepend(*mp, sizeof(struct ip), M_NOWAIT);
1056 		if (*mp == NULL)
1057 			return (ENOBUFS);
1058 		ip = mtod(*mp, struct ip *);
1059 		ip->ip_v = IPVERSION;
1060 		ip->ip_hl = sizeof(struct ip) >> 2;
1061 		ip->ip_p = proto;
1062 		ip->ip_len = htons((*mp)->m_pkthdr.len);
1063 		ip->ip_ttl = V_ip_defttl;
1064 		ip->ip_sum = 0;
1065 		ip->ip_off = setdf ? htons(IP_DF): 0;
1066 		ip->ip_src = saidx->src.sin.sin_addr;
1067 		ip->ip_dst = saidx->dst.sin.sin_addr;
1068 		ip_ecn_ingress(V_ip4_ipsec_ecn, &ip->ip_tos, &itos);
1069 		ip_fillid(ip);
1070 		break;
1071 #endif /* INET */
1072 #ifdef INET6
1073 	case AF_INET6:
1074 		if (saidx->src.sa.sa_family != AF_INET6 ||
1075 		    IN6_IS_ADDR_UNSPECIFIED(&saidx->src.sin6.sin6_addr) ||
1076 		    IN6_IS_ADDR_UNSPECIFIED(&saidx->dst.sin6.sin6_addr))
1077 			return (EINVAL);
1078 		*mp = ipsec_prepend(*mp, sizeof(struct ip6_hdr), M_NOWAIT);
1079 		if (*mp == NULL)
1080 			return (ENOBUFS);
1081 		ip6 = mtod(*mp, struct ip6_hdr *);
1082 		ip6->ip6_flow = 0;
1083 		ip6->ip6_vfc = IPV6_VERSION;
1084 		ip6->ip6_hlim = V_ip6_defhlim;
1085 		ip6->ip6_nxt = proto;
1086 		ip6->ip6_dst = saidx->dst.sin6.sin6_addr;
1087 		/* For link-local address embed scope zone id */
1088 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
1089 			ip6->ip6_dst.s6_addr16[1] =
1090 			    htons(saidx->dst.sin6.sin6_scope_id & 0xffff);
1091 		ip6->ip6_src = saidx->src.sin6.sin6_addr;
1092 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
1093 			ip6->ip6_src.s6_addr16[1] =
1094 			    htons(saidx->src.sin6.sin6_scope_id & 0xffff);
1095 		ip6->ip6_plen = htons((*mp)->m_pkthdr.len - sizeof(*ip6));
1096 		ip_ecn_ingress(V_ip6_ipsec_ecn, &proto, &itos);
1097 		ip6->ip6_flow |= htonl((uint32_t)proto << 20);
1098 		break;
1099 #endif /* INET6 */
1100 	default:
1101 		return (EAFNOSUPPORT);
1102 	}
1103 	(*mp)->m_flags &= ~(M_BCAST | M_MCAST);
1104 	return (0);
1105 }
1106