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