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