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