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