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