xref: /freebsd/sys/netipsec/ipsec_output.c (revision aa79fe245de7616cda41b69a296a5ce209c95c45)
1 /*-
2  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 /*
30  * IPsec output processing.
31  */
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_ipsec.h"
35 #include "opt_enc.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/mbuf.h>
40 #include <sys/domain.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/errno.h>
44 #include <sys/syslog.h>
45 #include <sys/vimage.h>
46 
47 #include <net/if.h>
48 #include <net/pfil.h>
49 #include <net/route.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/ip_var.h>
55 #include <netinet/in_var.h>
56 #include <netinet/ip_ecn.h>
57 #ifdef INET6
58 #include <netinet6/ip6_ecn.h>
59 #endif
60 
61 #include <netinet/ip6.h>
62 #ifdef INET6
63 #include <netinet6/ip6_var.h>
64 #endif
65 #include <netinet/in_pcb.h>
66 #ifdef INET6
67 #include <netinet/icmp6.h>
68 #include <netinet6/vinet6.h>
69 #endif
70 
71 #include <netipsec/ipsec.h>
72 #ifdef INET6
73 #include <netipsec/ipsec6.h>
74 #endif
75 #include <netipsec/ah_var.h>
76 #include <netipsec/esp_var.h>
77 #include <netipsec/ipcomp_var.h>
78 
79 #include <netipsec/xform.h>
80 
81 #include <netipsec/key.h>
82 #include <netipsec/keydb.h>
83 #include <netipsec/key_debug.h>
84 
85 #include <machine/in_cksum.h>
86 
87 #ifdef IPSEC_NAT_T
88 #include <netinet/udp.h>
89 #endif
90 
91 #ifdef DEV_ENC
92 #include <net/if_enc.h>
93 #endif
94 
95 
96 int
97 ipsec_process_done(struct mbuf *m, struct ipsecrequest *isr)
98 {
99 	INIT_VNET_IPSEC(curvnet);
100 	struct tdb_ident *tdbi;
101 	struct m_tag *mtag;
102 	struct secasvar *sav;
103 	struct secasindex *saidx;
104 	int error;
105 
106 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
107 	IPSEC_ASSERT(isr != NULL, ("null ISR"));
108 	sav = isr->sav;
109 	IPSEC_ASSERT(sav != NULL, ("null SA"));
110 	IPSEC_ASSERT(sav->sah != NULL, ("null SAH"));
111 
112 	saidx = &sav->sah->saidx;
113 	switch (saidx->dst.sa.sa_family) {
114 #ifdef INET
115 	case AF_INET:
116 		/* Fix the header length, for AH processing. */
117 		mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
118 		break;
119 #endif /* INET */
120 #ifdef INET6
121 	case AF_INET6:
122 		/* Fix the header length, for AH processing. */
123 		if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
124 			error = ENXIO;
125 			goto bad;
126 		}
127 		if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
128 			/* No jumbogram support. */
129 			error = ENXIO;	/*?*/
130 			goto bad;
131 		}
132 		mtod(m, struct ip6_hdr *)->ip6_plen =
133 			htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
134 		break;
135 #endif /* INET6 */
136 	default:
137 		DPRINTF(("%s: unknown protocol family %u\n", __func__,
138 		    saidx->dst.sa.sa_family));
139 		error = ENXIO;
140 		goto bad;
141 	}
142 
143 	/*
144 	 * Add a record of what we've done or what needs to be done to the
145 	 * packet.
146 	 */
147 	mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE,
148 			sizeof(struct tdb_ident), M_NOWAIT);
149 	if (mtag == NULL) {
150 		DPRINTF(("%s: could not get packet tag\n", __func__));
151 		error = ENOMEM;
152 		goto bad;
153 	}
154 
155 	tdbi = (struct tdb_ident *)(mtag + 1);
156 	tdbi->dst = saidx->dst;
157 	tdbi->proto = saidx->proto;
158 	tdbi->spi = sav->spi;
159 	m_tag_prepend(m, mtag);
160 
161 	/*
162 	 * If there's another (bundled) SA to apply, do so.
163 	 * Note that this puts a burden on the kernel stack size.
164 	 * If this is a problem we'll need to introduce a queue
165 	 * to set the packet on so we can unwind the stack before
166 	 * doing further processing.
167 	 */
168 	if (isr->next) {
169 		V_ipsec4stat.ips_out_bundlesa++;
170 		return ipsec4_process_packet(m, isr->next, 0, 0);
171 	}
172 	key_sa_recordxfer(sav, m);		/* record data transfer */
173 
174 	/*
175 	 * We're done with IPsec processing, transmit the packet using the
176 	 * appropriate network protocol (IP or IPv6). SPD lookup will be
177 	 * performed again there.
178 	 */
179 	switch (saidx->dst.sa.sa_family) {
180 #ifdef INET
181 	struct ip *ip;
182 	case AF_INET:
183 		ip = mtod(m, struct ip *);
184 		ip->ip_len = ntohs(ip->ip_len);
185 		ip->ip_off = ntohs(ip->ip_off);
186 
187 #ifdef IPSEC_NAT_T
188 		/*
189 		 * If NAT-T is enabled, now that all IPsec processing is done
190 		 * insert UDP encapsulation header after IP header.
191 		 */
192 		if (sav->natt_type) {
193 #ifdef _IP_VHL
194 			const int hlen = IP_VHL_HL(ip->ip_vhl);
195 #else
196 			const int hlen = (ip->ip_hl << 2);
197 #endif
198 			int size, off;
199 			struct mbuf *mi;
200 			struct udphdr *udp;
201 
202 			size = sizeof(struct udphdr);
203 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE) {
204 				/*
205 				 * draft-ietf-ipsec-nat-t-ike-0[01].txt and
206 				 * draft-ietf-ipsec-udp-encaps-(00/)01.txt,
207 				 * ignoring possible AH mode
208 				 * non-IKE marker + non-ESP marker
209 				 * from draft-ietf-ipsec-udp-encaps-00.txt.
210 				 */
211 				size += sizeof(u_int64_t);
212 			}
213 			mi = m_makespace(m, hlen, size, &off);
214 			if (mi == NULL) {
215 				DPRINTF(("%s: m_makespace for udphdr failed\n",
216 				    __func__));
217 				error = ENOBUFS;
218 				goto bad;
219 			}
220 
221 			udp = (struct udphdr *)(mtod(mi, caddr_t) + off);
222 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
223 				udp->uh_sport = htons(UDP_ENCAP_ESPINUDP_PORT);
224 			else
225 				udp->uh_sport =
226 					KEY_PORTFROMSADDR(&sav->sah->saidx.src);
227 			udp->uh_dport = KEY_PORTFROMSADDR(&sav->sah->saidx.dst);
228 			udp->uh_sum = 0;
229 			udp->uh_ulen = htons(m->m_pkthdr.len - hlen);
230 			ip->ip_len = m->m_pkthdr.len;
231 			ip->ip_p = IPPROTO_UDP;
232 
233 			if (sav->natt_type == UDP_ENCAP_ESPINUDP_NON_IKE)
234 				*(u_int64_t *)(udp + 1) = 0;
235 		}
236 #endif /* IPSEC_NAT_T */
237 
238 		return ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
239 #endif /* INET */
240 #ifdef INET6
241 	case AF_INET6:
242 		/*
243 		 * We don't need massage, IPv6 header fields are always in
244 		 * net endian.
245 		 */
246 		return ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
247 #endif /* INET6 */
248 	}
249 	panic("ipsec_process_done");
250 bad:
251 	m_freem(m);
252 	KEY_FREESAV(&sav);
253 	return (error);
254 }
255 
256 static struct ipsecrequest *
257 ipsec_nextisr(
258 	struct mbuf *m,
259 	struct ipsecrequest *isr,
260 	int af,
261 	struct secasindex *saidx,
262 	int *error
263 )
264 {
265 #define IPSEC_OSTAT(x,y,z) (isr->saidx.proto == IPPROTO_ESP ? (x)++ : \
266 			    isr->saidx.proto == IPPROTO_AH ? (y)++ : (z)++)
267 	INIT_VNET_IPSEC(curvnet);
268 	struct secasvar *sav;
269 
270 	IPSECREQUEST_LOCK_ASSERT(isr);
271 
272 	IPSEC_ASSERT(af == AF_INET || af == AF_INET6,
273 		("invalid address family %u", af));
274 again:
275 	/*
276 	 * Craft SA index to search for proper SA.  Note that
277 	 * we only fillin unspecified SA peers for transport
278 	 * mode; for tunnel mode they must already be filled in.
279 	 */
280 	*saidx = isr->saidx;
281 	if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
282 		/* Fillin unspecified SA peers only for transport mode */
283 		if (af == AF_INET) {
284 			struct sockaddr_in *sin;
285 			struct ip *ip = mtod(m, struct ip *);
286 
287 			if (saidx->src.sa.sa_len == 0) {
288 				sin = &saidx->src.sin;
289 				sin->sin_len = sizeof(*sin);
290 				sin->sin_family = AF_INET;
291 				sin->sin_port = IPSEC_PORT_ANY;
292 				sin->sin_addr = ip->ip_src;
293 			}
294 			if (saidx->dst.sa.sa_len == 0) {
295 				sin = &saidx->dst.sin;
296 				sin->sin_len = sizeof(*sin);
297 				sin->sin_family = AF_INET;
298 				sin->sin_port = IPSEC_PORT_ANY;
299 				sin->sin_addr = ip->ip_dst;
300 			}
301 		} else {
302 			struct sockaddr_in6 *sin6;
303 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
304 
305 			if (saidx->src.sin6.sin6_len == 0) {
306 				sin6 = (struct sockaddr_in6 *)&saidx->src;
307 				sin6->sin6_len = sizeof(*sin6);
308 				sin6->sin6_family = AF_INET6;
309 				sin6->sin6_port = IPSEC_PORT_ANY;
310 				sin6->sin6_addr = ip6->ip6_src;
311 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
312 					/* fix scope id for comparing SPD */
313 					sin6->sin6_addr.s6_addr16[1] = 0;
314 					sin6->sin6_scope_id =
315 					    ntohs(ip6->ip6_src.s6_addr16[1]);
316 				}
317 			}
318 			if (saidx->dst.sin6.sin6_len == 0) {
319 				sin6 = (struct sockaddr_in6 *)&saidx->dst;
320 				sin6->sin6_len = sizeof(*sin6);
321 				sin6->sin6_family = AF_INET6;
322 				sin6->sin6_port = IPSEC_PORT_ANY;
323 				sin6->sin6_addr = ip6->ip6_dst;
324 				if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
325 					/* fix scope id for comparing SPD */
326 					sin6->sin6_addr.s6_addr16[1] = 0;
327 					sin6->sin6_scope_id =
328 					    ntohs(ip6->ip6_dst.s6_addr16[1]);
329 				}
330 			}
331 		}
332 	}
333 
334 	/*
335 	 * Lookup SA and validate it.
336 	 */
337 	*error = key_checkrequest(isr, saidx);
338 	if (*error != 0) {
339 		/*
340 		 * IPsec processing is required, but no SA found.
341 		 * I assume that key_acquire() had been called
342 		 * to get/establish the SA. Here I discard
343 		 * this packet because it is responsibility for
344 		 * upper layer to retransmit the packet.
345 		 */
346 		V_ipsec4stat.ips_out_nosa++;
347 		goto bad;
348 	}
349 	sav = isr->sav;
350 	if (sav == NULL) {
351 		IPSEC_ASSERT(ipsec_get_reqlevel(isr) == IPSEC_LEVEL_USE,
352 			("no SA found, but required; level %u",
353 			ipsec_get_reqlevel(isr)));
354 		IPSECREQUEST_UNLOCK(isr);
355 		isr = isr->next;
356 		/*
357 		 * If isr is NULL, we found a 'use' policy w/o SA.
358 		 * Return w/o error and w/o isr so we can drop out
359 		 * and continue w/o IPsec processing.
360 		 */
361 		if (isr == NULL)
362 			return isr;
363 		IPSECREQUEST_LOCK(isr);
364 		goto again;
365 	}
366 
367 	/*
368 	 * Check system global policy controls.
369 	 */
370 	if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
371 	    (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
372 	    (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
373 		DPRINTF(("%s: IPsec outbound packet dropped due"
374 			" to policy (check your sysctls)\n", __func__));
375 		IPSEC_OSTAT(V_espstat.esps_pdrops, V_ahstat.ahs_pdrops,
376 		    V_ipcompstat.ipcomps_pdrops);
377 		*error = EHOSTUNREACH;
378 		goto bad;
379 	}
380 
381 	/*
382 	 * Sanity check the SA contents for the caller
383 	 * before they invoke the xform output method.
384 	 */
385 	if (sav->tdb_xform == NULL) {
386 		DPRINTF(("%s: no transform for SA\n", __func__));
387 		IPSEC_OSTAT(V_espstat.esps_noxform, V_ahstat.ahs_noxform,
388 		    V_ipcompstat.ipcomps_noxform);
389 		*error = EHOSTUNREACH;
390 		goto bad;
391 	}
392 	return isr;
393 bad:
394 	IPSEC_ASSERT(*error != 0, ("error return w/ no error code"));
395 	IPSECREQUEST_UNLOCK(isr);
396 	return NULL;
397 #undef IPSEC_OSTAT
398 }
399 
400 #ifdef INET
401 /*
402  * IPsec output logic for IPv4.
403  */
404 int
405 ipsec4_process_packet(
406 	struct mbuf *m,
407 	struct ipsecrequest *isr,
408 	int flags,
409 	int tunalready)
410 {
411 	INIT_VNET_IPSEC(curvnet);
412 	struct secasindex saidx;
413 	struct secasvar *sav;
414 	struct ip *ip;
415 	int error, i, off;
416 
417 	IPSEC_ASSERT(m != NULL, ("null mbuf"));
418 	IPSEC_ASSERT(isr != NULL, ("null isr"));
419 
420 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
421 
422 	isr = ipsec_nextisr(m, isr, AF_INET, &saidx, &error);
423 	if (isr == NULL) {
424 		if (error != 0)
425 			goto bad;
426 		return EJUSTRETURN;
427 	}
428 
429 	sav = isr->sav;
430 
431 #ifdef DEV_ENC
432 	encif->if_opackets++;
433 	encif->if_obytes += m->m_pkthdr.len;
434 
435 	/* pass the mbuf to enc0 for bpf processing */
436 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_BEFORE);
437 	/* pass the mbuf to enc0 for packet filtering */
438 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
439 		goto bad;
440 #endif
441 
442 	if (!tunalready) {
443 		union sockaddr_union *dst = &sav->sah->saidx.dst;
444 		int setdf;
445 
446 		/*
447 		 * Collect IP_DF state from the outer header.
448 		 */
449 		if (dst->sa.sa_family == AF_INET) {
450 			if (m->m_len < sizeof (struct ip) &&
451 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
452 				error = ENOBUFS;
453 				goto bad;
454 			}
455 			ip = mtod(m, struct ip *);
456 			/* Honor system-wide control of how to handle IP_DF */
457 			switch (V_ip4_ipsec_dfbit) {
458 			case 0:			/* clear in outer header */
459 			case 1:			/* set in outer header */
460 				setdf = V_ip4_ipsec_dfbit;
461 				break;
462 			default:		/* propagate to outer header */
463 				setdf = ntohs(ip->ip_off & IP_DF);
464 				break;
465 			}
466 		} else {
467 			ip = NULL;		/* keep compiler happy */
468 			setdf = 0;
469 		}
470 		/* Do the appropriate encapsulation, if necessary */
471 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
472 		    dst->sa.sa_family != AF_INET ||	    /* PF mismatch */
473 #if 0
474 		    (sav->flags & SADB_X_SAFLAGS_TUNNEL) || /* Tunnel requ'd */
475 		    sav->tdb_xform->xf_type == XF_IP4 ||    /* ditto */
476 #endif
477 		    (dst->sa.sa_family == AF_INET &&	    /* Proxy */
478 		     dst->sin.sin_addr.s_addr != INADDR_ANY &&
479 		     dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
480 			struct mbuf *mp;
481 
482 			/* Fix IPv4 header checksum and length */
483 			if (m->m_len < sizeof (struct ip) &&
484 			    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
485 				error = ENOBUFS;
486 				goto bad;
487 			}
488 			ip = mtod(m, struct ip *);
489 			ip->ip_len = htons(m->m_pkthdr.len);
490 			ip->ip_sum = 0;
491 #ifdef _IP_VHL
492 			if (ip->ip_vhl == IP_VHL_BORING)
493 				ip->ip_sum = in_cksum_hdr(ip);
494 			else
495 				ip->ip_sum = in_cksum(m,
496 					_IP_VHL_HL(ip->ip_vhl) << 2);
497 #else
498 			ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
499 #endif
500 
501 			/* Encapsulate the packet */
502 			error = ipip_output(m, isr, &mp, 0, 0);
503 			if (mp == NULL && !error) {
504 				/* Should never happen. */
505 				DPRINTF(("%s: ipip_output returns no mbuf and "
506 					"no error!", __func__));
507 				error = EFAULT;
508 			}
509 			if (error) {
510 				if (mp) {
511 					/* XXX: Should never happen! */
512 					m_freem(mp);
513 				}
514 				m = NULL; /* ipip_output() already freed it */
515 				goto bad;
516 			}
517 			m = mp, mp = NULL;
518 			/*
519 			 * ipip_output clears IP_DF in the new header.  If
520 			 * we need to propagate IP_DF from the outer header,
521 			 * then we have to do it here.
522 			 *
523 			 * XXX shouldn't assume what ipip_output does.
524 			 */
525 			if (dst->sa.sa_family == AF_INET && setdf) {
526 				if (m->m_len < sizeof (struct ip) &&
527 				    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
528 					error = ENOBUFS;
529 					goto bad;
530 				}
531 				ip = mtod(m, struct ip *);
532 				ip->ip_off = ntohs(ip->ip_off);
533 				ip->ip_off |= IP_DF;
534 				ip->ip_off = htons(ip->ip_off);
535 			}
536 		}
537 	}
538 
539 #ifdef DEV_ENC
540 	/* pass the mbuf to enc0 for bpf processing */
541 	ipsec_bpf(m, sav, AF_INET, ENC_OUT|ENC_AFTER);
542 	/* pass the mbuf to enc0 for packet filtering */
543 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
544 		goto bad;
545 #endif
546 
547 	/*
548 	 * Dispatch to the appropriate IPsec transform logic.  The
549 	 * packet will be returned for transmission after crypto
550 	 * processing, etc. are completed.  For encapsulation we
551 	 * bypass this call because of the explicit call done above
552 	 * (necessary to deal with IP_DF handling for IPv4).
553 	 *
554 	 * NB: m & sav are ``passed to caller'' who's reponsible for
555 	 *     for reclaiming their resources.
556 	 */
557 	if (sav->tdb_xform->xf_type != XF_IP4) {
558 		ip = mtod(m, struct ip *);
559 		i = ip->ip_hl << 2;
560 		off = offsetof(struct ip, ip_p);
561 		error = (*sav->tdb_xform->xf_output)(m, isr, NULL, i, off);
562 	} else {
563 		error = ipsec_process_done(m, isr);
564 	}
565 	IPSECREQUEST_UNLOCK(isr);
566 	return error;
567 bad:
568 	if (isr)
569 		IPSECREQUEST_UNLOCK(isr);
570 	if (m)
571 		m_freem(m);
572 	return error;
573 }
574 #endif
575 
576 #ifdef INET6
577 /*
578  * Chop IP6 header from the payload.
579  */
580 static struct mbuf *
581 ipsec6_splithdr(struct mbuf *m)
582 {
583 	struct mbuf *mh;
584 	struct ip6_hdr *ip6;
585 	int hlen;
586 
587 	IPSEC_ASSERT(m->m_len >= sizeof (struct ip6_hdr),
588 		("first mbuf too short, len %u", m->m_len));
589 	ip6 = mtod(m, struct ip6_hdr *);
590 	hlen = sizeof(struct ip6_hdr);
591 	if (m->m_len > hlen) {
592 		MGETHDR(mh, M_DONTWAIT, MT_DATA);
593 		if (!mh) {
594 			m_freem(m);
595 			return NULL;
596 		}
597 		M_MOVE_PKTHDR(mh, m);
598 		MH_ALIGN(mh, hlen);
599 		m->m_len -= hlen;
600 		m->m_data += hlen;
601 		mh->m_next = m;
602 		m = mh;
603 		m->m_len = hlen;
604 		bcopy((caddr_t)ip6, mtod(m, caddr_t), hlen);
605 	} else if (m->m_len < hlen) {
606 		m = m_pullup(m, hlen);
607 		if (!m)
608 			return NULL;
609 	}
610 	return m;
611 }
612 
613 /*
614  * IPsec output logic for IPv6, transport mode.
615  */
616 int
617 ipsec6_output_trans(
618 	struct ipsec_output_state *state,
619 	u_char *nexthdrp,
620 	struct mbuf *mprev,
621 	struct secpolicy *sp,
622 	int flags,
623 	int *tun)
624 {
625 	INIT_VNET_IPSEC(curvnet);
626 	struct ipsecrequest *isr;
627 	struct secasindex saidx;
628 	int error = 0;
629 	struct mbuf *m;
630 
631 	IPSEC_ASSERT(state != NULL, ("null state"));
632 	IPSEC_ASSERT(state->m != NULL, ("null m"));
633 	IPSEC_ASSERT(nexthdrp != NULL, ("null nexthdrp"));
634 	IPSEC_ASSERT(mprev != NULL, ("null mprev"));
635 	IPSEC_ASSERT(sp != NULL, ("null sp"));
636 	IPSEC_ASSERT(tun != NULL, ("null tun"));
637 
638 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
639 		printf("%s: applied SP\n", __func__);
640 		kdebug_secpolicy(sp));
641 
642 	isr = sp->req;
643 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
644 		/* the rest will be handled by ipsec6_output_tunnel() */
645 		*tun = 1;		/* need tunnel-mode processing */
646 		return 0;
647 	}
648 
649 	*tun = 0;
650 	m = state->m;
651 
652 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
653 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
654 	if (isr == NULL) {
655 		if (error != 0) {
656 #ifdef notdef
657 			/* XXX should notification be done for all errors ? */
658 			/*
659 			 * Notify the fact that the packet is discarded
660 			 * to ourselves. I believe this is better than
661 			 * just silently discarding. (jinmei@kame.net)
662 			 * XXX: should we restrict the error to TCP packets?
663 			 * XXX: should we directly notify sockets via
664 			 *      pfctlinputs?
665 			 */
666 			icmp6_error(m, ICMP6_DST_UNREACH,
667 				    ICMP6_DST_UNREACH_ADMIN, 0);
668 			m = NULL;	/* NB: icmp6_error frees mbuf */
669 #endif
670 			goto bad;
671 		}
672 		return EJUSTRETURN;
673 	}
674 
675 	error = (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
676 						  sizeof (struct ip6_hdr),
677 						  offsetof(struct ip6_hdr,
678 							   ip6_nxt));
679 	IPSECREQUEST_UNLOCK(isr);
680 	return error;
681 bad:
682 	if (isr)
683 		IPSECREQUEST_UNLOCK(isr);
684 	if (m)
685 		m_freem(m);
686 	state->m = NULL;
687 	return error;
688 }
689 
690 static int
691 ipsec6_encapsulate(struct mbuf *m, struct secasvar *sav)
692 {
693 	INIT_VNET_IPSEC(curvnet);
694 	struct ip6_hdr *oip6;
695 	struct ip6_hdr *ip6;
696 	size_t plen;
697 
698 	/* can't tunnel between different AFs */
699 	if (sav->sah->saidx.src.sa.sa_family != AF_INET6 ||
700 	    sav->sah->saidx.dst.sa.sa_family != AF_INET6) {
701 		m_freem(m);
702 		return EINVAL;
703 	}
704 	IPSEC_ASSERT(m->m_len == sizeof (struct ip6_hdr),
705 		("mbuf wrong size; len %u", m->m_len));
706 
707 
708 	/*
709 	 * grow the mbuf to accomodate the new IPv6 header.
710 	 */
711 	plen = m->m_pkthdr.len;
712 	if (M_LEADINGSPACE(m->m_next) < sizeof(struct ip6_hdr)) {
713 		struct mbuf *n;
714 		MGET(n, M_DONTWAIT, MT_DATA);
715 		if (!n) {
716 			m_freem(m);
717 			return ENOBUFS;
718 		}
719 		n->m_len = sizeof(struct ip6_hdr);
720 		n->m_next = m->m_next;
721 		m->m_next = n;
722 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
723 		oip6 = mtod(n, struct ip6_hdr *);
724 	} else {
725 		m->m_next->m_len += sizeof(struct ip6_hdr);
726 		m->m_next->m_data -= sizeof(struct ip6_hdr);
727 		m->m_pkthdr.len += sizeof(struct ip6_hdr);
728 		oip6 = mtod(m->m_next, struct ip6_hdr *);
729 	}
730 	ip6 = mtod(m, struct ip6_hdr *);
731 	bcopy((caddr_t)ip6, (caddr_t)oip6, sizeof(struct ip6_hdr));
732 
733 	/* Fake link-local scope-class addresses */
734 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_src))
735 		oip6->ip6_src.s6_addr16[1] = 0;
736 	if (IN6_IS_SCOPE_LINKLOCAL(&oip6->ip6_dst))
737 		oip6->ip6_dst.s6_addr16[1] = 0;
738 
739 	/* construct new IPv6 header. see RFC 2401 5.1.2.2 */
740 	/* ECN consideration. */
741 	ip6_ecn_ingress(V_ip6_ipsec_ecn, &ip6->ip6_flow, &oip6->ip6_flow);
742 	if (plen < IPV6_MAXPACKET - sizeof(struct ip6_hdr))
743 		ip6->ip6_plen = htons(plen);
744 	else {
745 		/* ip6->ip6_plen will be updated in ip6_output() */
746 	}
747 	ip6->ip6_nxt = IPPROTO_IPV6;
748 	ip6->ip6_src = sav->sah->saidx.src.sin6.sin6_addr;
749 	ip6->ip6_dst = sav->sah->saidx.dst.sin6.sin6_addr;
750 	ip6->ip6_hlim = IPV6_DEFHLIM;
751 
752 	/* XXX Should ip6_src be updated later ? */
753 
754 	return 0;
755 }
756 
757 /*
758  * IPsec output logic for IPv6, tunnel mode.
759  */
760 int
761 ipsec6_output_tunnel(struct ipsec_output_state *state, struct secpolicy *sp, int flags)
762 {
763 	INIT_VNET_INET6(curvnet);
764 	INIT_VNET_IPSEC(curvnet);
765 	struct ip6_hdr *ip6;
766 	struct ipsecrequest *isr;
767 	struct secasindex saidx;
768 	int error;
769 	struct sockaddr_in6* dst6;
770 	struct mbuf *m;
771 
772 	IPSEC_ASSERT(state != NULL, ("null state"));
773 	IPSEC_ASSERT(state->m != NULL, ("null m"));
774 	IPSEC_ASSERT(sp != NULL, ("null sp"));
775 
776 	KEYDEBUG(KEYDEBUG_IPSEC_DATA,
777 		printf("%s: applied SP\n", __func__);
778 		kdebug_secpolicy(sp));
779 
780 	m = state->m;
781 	/*
782 	 * transport mode ipsec (before the 1st tunnel mode) is already
783 	 * processed by ipsec6_output_trans().
784 	 */
785 	for (isr = sp->req; isr; isr = isr->next) {
786 		if (isr->saidx.mode == IPSEC_MODE_TUNNEL)
787 			break;
788 	}
789 
790 	IPSECREQUEST_LOCK(isr);		/* insure SA contents don't change */
791 	isr = ipsec_nextisr(m, isr, AF_INET6, &saidx, &error);
792 	if (isr == NULL) {
793 		if (error != 0)
794 			goto bad;
795 		return EJUSTRETURN;
796 	}
797 
798 #ifdef DEV_ENC
799 	encif->if_opackets++;
800 	encif->if_obytes += m->m_pkthdr.len;
801 
802 	/* pass the mbuf to enc0 for bpf processing */
803 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_BEFORE);
804 	/* pass the mbuf to enc0 for packet filtering */
805 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_BEFORE)) != 0)
806 		goto bad;
807 #endif
808 
809 	/*
810 	 * There may be the case that SA status will be changed when
811 	 * we are refering to one. So calling splsoftnet().
812 	 */
813 	if (isr->saidx.mode == IPSEC_MODE_TUNNEL) {
814 		/*
815 		 * build IPsec tunnel.
816 		 */
817 		/* XXX should be processed with other familiy */
818 		if (isr->sav->sah->saidx.src.sa.sa_family != AF_INET6) {
819 			ipseclog((LOG_ERR, "%s: family mismatched between "
820 			    "inner and outer, spi=%u\n", __func__,
821 			    ntohl(isr->sav->spi)));
822 			V_ipsec6stat.ips_out_inval++;
823 			error = EAFNOSUPPORT;
824 			goto bad;
825 		}
826 
827 		m = ipsec6_splithdr(m);
828 		if (!m) {
829 			V_ipsec6stat.ips_out_nomem++;
830 			error = ENOMEM;
831 			goto bad;
832 		}
833 		error = ipsec6_encapsulate(m, isr->sav);
834 		if (error) {
835 			m = NULL;
836 			goto bad;
837 		}
838 		ip6 = mtod(m, struct ip6_hdr *);
839 
840 		state->ro = &isr->sav->sah->sa_route;
841 		state->dst = (struct sockaddr *)&state->ro->ro_dst;
842 		dst6 = (struct sockaddr_in6 *)state->dst;
843 		if (state->ro->ro_rt
844 		 && ((state->ro->ro_rt->rt_flags & RTF_UP) == 0
845 		  || !IN6_ARE_ADDR_EQUAL(&dst6->sin6_addr, &ip6->ip6_dst))) {
846 			RTFREE(state->ro->ro_rt);
847 			state->ro->ro_rt = NULL;
848 		}
849 		if (state->ro->ro_rt == NULL) {
850 			bzero(dst6, sizeof(*dst6));
851 			dst6->sin6_family = AF_INET6;
852 			dst6->sin6_len = sizeof(*dst6);
853 			dst6->sin6_addr = ip6->ip6_dst;
854 			rtalloc(state->ro);
855 		}
856 		if (state->ro->ro_rt == NULL) {
857 			V_ip6stat.ip6s_noroute++;
858 			V_ipsec6stat.ips_out_noroute++;
859 			error = EHOSTUNREACH;
860 			goto bad;
861 		}
862 
863 		/* adjust state->dst if tunnel endpoint is offlink */
864 		if (state->ro->ro_rt->rt_flags & RTF_GATEWAY) {
865 			state->dst = (struct sockaddr *)state->ro->ro_rt->rt_gateway;
866 			dst6 = (struct sockaddr_in6 *)state->dst;
867 		}
868 	}
869 
870 	m = ipsec6_splithdr(m);
871 	if (!m) {
872 		V_ipsec6stat.ips_out_nomem++;
873 		error = ENOMEM;
874 		goto bad;
875 	}
876 	ip6 = mtod(m, struct ip6_hdr *);
877 
878 #ifdef DEV_ENC
879 	/* pass the mbuf to enc0 for bpf processing */
880 	ipsec_bpf(m, isr->sav, AF_INET6, ENC_OUT|ENC_AFTER);
881 	/* pass the mbuf to enc0 for packet filtering */
882 	if ((error = ipsec_filter(&m, PFIL_OUT, ENC_OUT|ENC_AFTER)) != 0)
883 		goto bad;
884 #endif
885 
886 	error = (*isr->sav->tdb_xform->xf_output)(m, isr, NULL,
887 		sizeof (struct ip6_hdr),
888 		offsetof(struct ip6_hdr, ip6_nxt));
889 	IPSECREQUEST_UNLOCK(isr);
890 	return error;
891 bad:
892 	if (isr)
893 		IPSECREQUEST_UNLOCK(isr);
894 	if (m)
895 		m_freem(m);
896 	state->m = NULL;
897 	return error;
898 }
899 #endif /*INET6*/
900