]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netipsec/ipsec_output.c
ipsec: fix typo in comment
[FreeBSD/FreeBSD.git] / sys / netipsec / ipsec_output.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
5  * Copyright (c) 2016 Andrey V. Elsukov <ae@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31
32 /*
33  * IPsec output processing.
34  */
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_ipsec.h"
38 #include "opt_sctp.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/mbuf.h>
43 #include <sys/domain.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/errno.h>
47 #include <sys/hhook.h>
48 #include <sys/syslog.h>
49
50 #include <net/if.h>
51 #include <net/if_enc.h>
52 #include <net/if_var.h>
53 #include <net/vnet.h>
54
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_var.h>
59 #include <netinet/in_var.h>
60 #include <netinet/ip_ecn.h>
61 #ifdef INET6
62 #include <netinet6/ip6_ecn.h>
63 #endif
64 #include <netinet/ip_icmp.h>
65 #include <netinet/tcp_var.h>
66
67 #include <netinet/ip6.h>
68 #ifdef INET6
69 #include <netinet6/ip6_var.h>
70 #include <netinet6/scope6_var.h>
71 #endif
72 #include <netinet/in_pcb.h>
73 #ifdef INET6
74 #include <netinet/icmp6.h>
75 #endif
76 #if defined(SCTP) || defined(SCTP_SUPPORT)
77 #include <netinet/sctp_crc32.h>
78 #endif
79
80 #include <netinet/udp.h>
81 #include <netipsec/ah.h>
82 #include <netipsec/esp.h>
83 #include <netipsec/ipsec.h>
84 #ifdef INET6
85 #include <netipsec/ipsec6.h>
86 #endif
87 #include <netipsec/ah_var.h>
88 #include <netipsec/esp_var.h>
89 #include <netipsec/ipcomp_var.h>
90
91 #include <netipsec/xform.h>
92
93 #include <netipsec/key.h>
94 #include <netipsec/keydb.h>
95 #include <netipsec/key_debug.h>
96
97 #include <machine/in_cksum.h>
98
99 #define IPSEC_OSTAT_INC(proto, name)    do {            \
100         if ((proto) == IPPROTO_ESP)     \
101                 ESPSTAT_INC(esps_##name);       \
102         else if ((proto) == IPPROTO_AH)\
103                 AHSTAT_INC(ahs_##name);         \
104         else                                    \
105                 IPCOMPSTAT_INC(ipcomps_##name); \
106 } while (0)
107
108 static int ipsec_encap(struct mbuf **mp, struct secasindex *saidx);
109 static size_t ipsec_get_pmtu(struct secasvar *sav);
110
111 #ifdef INET
112 static struct secasvar *
113 ipsec4_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
114 {
115         struct secasindex *saidx, tmpsaidx;
116         struct ipsecrequest *isr;
117         struct sockaddr_in *sin;
118         struct secasvar *sav;
119         struct ip *ip;
120
121         /*
122          * Check system global policy controls.
123          */
124 next:
125         isr = sp->req[*pidx];
126         if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
127             (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
128             (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
129                 DPRINTF(("%s: IPsec outbound packet dropped due"
130                         " to policy (check your sysctls)\n", __func__));
131                 IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
132                 *error = EHOSTUNREACH;
133                 return (NULL);
134         }
135         /*
136          * Craft SA index to search for proper SA.  Note that
137          * we only initialize unspecified SA peers for transport
138          * mode; for tunnel mode they must already be filled in.
139          */
140         if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
141                 saidx = &tmpsaidx;
142                 *saidx = isr->saidx;
143                 ip = mtod(m, struct ip *);
144                 if (saidx->src.sa.sa_len == 0) {
145                         sin = &saidx->src.sin;
146                         sin->sin_len = sizeof(*sin);
147                         sin->sin_family = AF_INET;
148                         sin->sin_port = IPSEC_PORT_ANY;
149                         sin->sin_addr = ip->ip_src;
150                 }
151                 if (saidx->dst.sa.sa_len == 0) {
152                         sin = &saidx->dst.sin;
153                         sin->sin_len = sizeof(*sin);
154                         sin->sin_family = AF_INET;
155                         sin->sin_port = IPSEC_PORT_ANY;
156                         sin->sin_addr = ip->ip_dst;
157                 }
158         } else
159                 saidx = &sp->req[*pidx]->saidx;
160         /*
161          * Lookup SA and validate it.
162          */
163         sav = key_allocsa_policy(sp, saidx, error);
164         if (sav == NULL) {
165                 IPSECSTAT_INC(ips_out_nosa);
166                 if (*error != 0)
167                         return (NULL);
168                 if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
169                         /*
170                          * We have no SA and policy that doesn't require
171                          * this IPsec transform, thus we can continue w/o
172                          * IPsec processing, i.e. return EJUSTRETURN.
173                          * But first check if there is some bundled transform.
174                          */
175                         if (sp->tcount > ++(*pidx))
176                                 goto next;
177                         *error = EJUSTRETURN;
178                 }
179                 return (NULL);
180         }
181         IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
182         return (sav);
183 }
184
185 /*
186  * IPsec output logic for IPv4.
187  */
188 static int
189 ipsec4_perform_request(struct mbuf *m, struct secpolicy *sp,
190     struct inpcb *inp, u_int idx)
191 {
192         struct ipsec_ctx_data ctx;
193         union sockaddr_union *dst;
194         struct secasvar *sav;
195         struct ip *ip;
196         int error, i, off;
197
198         IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
199
200         /*
201          * We hold the reference to SP. Content of SP couldn't be changed.
202          * Craft secasindex and do lookup for suitable SA.
203          * Then do encapsulation if needed and call xform's output.
204          * We need to store SP in the xform callback parameters.
205          * In xform callback we will extract SP and it can be used to
206          * determine next transform. At the end of transform we can
207          * release reference to SP.
208          */
209         sav = ipsec4_allocsa(m, sp, &idx, &error);
210         if (sav == NULL) {
211                 if (error == EJUSTRETURN) { /* No IPsec required */
212                         key_freesp(&sp);
213                         return (error);
214                 }
215                 goto bad;
216         }
217         /*
218          * XXXAE: most likely ip_sum at this point is wrong.
219          */
220         IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET, IPSEC_ENC_BEFORE);
221         if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
222                 goto bad;
223
224         ip = mtod(m, struct ip *);
225         dst = &sav->sah->saidx.dst;
226         /* Do the appropriate encapsulation, if necessary */
227         if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
228             dst->sa.sa_family != AF_INET ||         /* PF mismatch */
229             (dst->sa.sa_family == AF_INET &&        /* Proxy */
230              dst->sin.sin_addr.s_addr != INADDR_ANY &&
231              dst->sin.sin_addr.s_addr != ip->ip_dst.s_addr)) {
232                 /* Fix IPv4 header checksum and length */
233                 ip->ip_len = htons(m->m_pkthdr.len);
234                 ip->ip_sum = 0;
235                 ip->ip_sum = in_cksum(m, ip->ip_hl << 2);
236                 error = ipsec_encap(&m, &sav->sah->saidx);
237                 if (error != 0) {
238                         DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
239                             "with error %d\n", __func__, ntohl(sav->spi),
240                             error));
241                         /* XXXAE: IPSEC_OSTAT_INC(tunnel); */
242                         goto bad;
243                 }
244                 inp = NULL;
245         }
246
247         IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
248         if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
249                 goto bad;
250
251         /*
252          * Dispatch to the appropriate IPsec transform logic.  The
253          * packet will be returned for transmission after crypto
254          * processing, etc. are completed.
255          *
256          * NB: m & sav are ``passed to caller'' who's responsible for
257          *     reclaiming their resources.
258          */
259         switch(dst->sa.sa_family) {
260         case AF_INET:
261                 ip = mtod(m, struct ip *);
262                 i = ip->ip_hl << 2;
263                 off = offsetof(struct ip, ip_p);
264                 break;
265 #ifdef INET6
266         case AF_INET6:
267                 i = sizeof(struct ip6_hdr);
268                 off = offsetof(struct ip6_hdr, ip6_nxt);
269                 break;
270 #endif /* INET6 */
271         default:
272                 DPRINTF(("%s: unsupported protocol family %u\n",
273                     __func__, dst->sa.sa_family));
274                 error = EPFNOSUPPORT;
275                 IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
276                 goto bad;
277         }
278         error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
279         return (error);
280 bad:
281         IPSECSTAT_INC(ips_out_inval);
282         if (m != NULL)
283                 m_freem(m);
284         if (sav != NULL)
285                 key_freesav(&sav);
286         key_freesp(&sp);
287         return (error);
288 }
289
290 int
291 ipsec4_process_packet(struct mbuf *m, struct secpolicy *sp,
292     struct inpcb *inp)
293 {
294
295         return (ipsec4_perform_request(m, sp, inp, 0));
296 }
297
298 int
299 ipsec4_check_pmtu(struct mbuf *m, struct secpolicy *sp, int forwarding)
300 {
301         struct secasvar *sav;
302         struct ip *ip;
303         size_t hlen, pmtu;
304         uint32_t idx;
305         int error;
306
307         /* Don't check PMTU if the frame won't have DF bit set. */
308         if (!V_ip4_ipsec_dfbit)
309                 return (0);
310         if (V_ip4_ipsec_dfbit == 1)
311                 goto setdf;
312
313         /* V_ip4_ipsec_dfbit > 1 - we will copy it from inner header. */
314         ip = mtod(m, struct ip *);
315         if (!(ip->ip_off & htons(IP_DF)))
316                 return (0);
317
318 setdf:
319         idx = sp->tcount - 1;
320         sav = ipsec4_allocsa(m, sp, &idx, &error);
321         if (sav == NULL) {
322                 key_freesp(&sp);
323                 /*
324                  * No matching SA was found and SADB_ACQUIRE message was generated.
325                  * Since we have matched a SP to this packet drop it silently.
326                  */
327                 if (error == 0)
328                         error = EINPROGRESS;
329                 if (error != EJUSTRETURN)
330                         m_freem(m);
331
332                 return (error);
333         }
334
335         pmtu = ipsec_get_pmtu(sav);
336         if (pmtu == 0) {
337                 key_freesav(&sav);
338                 return (0);
339         }
340
341         hlen = ipsec_hdrsiz_internal(sp);
342         key_freesav(&sav);
343
344         if (m_length(m, NULL) + hlen > pmtu) {
345                 /*
346                  * If we're forwarding generate ICMP message here,
347                  * so that it contains pmtu subtraced by header size.
348                  * Set error to EINPROGRESS, in order for the frame
349                  * to be dropped silently.
350                  */
351                 if (forwarding) {
352                         if (pmtu > hlen)
353                                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
354                                     0, pmtu - hlen);
355                         else
356                                 m_freem(m);
357
358                         key_freesp(&sp);
359                         return (EINPROGRESS); /* Pretend that we consumed it. */
360                 } else {
361                         m_freem(m);
362                         key_freesp(&sp);
363                         return (EMSGSIZE);
364                 }
365         }
366
367         return (0);
368 }
369
370 static int
371 ipsec4_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
372 {
373         struct secpolicy *sp;
374         int error;
375
376         /* Lookup for the corresponding outbound security policy */
377         sp = ipsec4_checkpolicy(m, inp, &error, !forwarding);
378         if (sp == NULL) {
379                 if (error == -EINVAL) {
380                         /* Discarded by policy. */
381                         m_freem(m);
382                         return (EACCES);
383                 }
384                 return (0); /* No IPsec required. */
385         }
386
387         /*
388          * Usually we have to have tunnel mode IPsec security policy
389          * when we are forwarding a packet. Otherwise we could not handle
390          * encrypted replies, because they are not destined for us. But
391          * some users are doing source address translation for forwarded
392          * packets, and thus, even if they are forwarded, the replies will
393          * return back to us.
394          */
395         if (!forwarding) {
396                 /*
397                  * Do delayed checksums now because we send before
398                  * this is done in the normal processing path.
399                  */
400                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
401                         m = mb_unmapped_to_ext(m);
402                         if (m == NULL) {
403                                 IPSECSTAT_INC(ips_out_nomem);
404                                 key_freesp(&sp);
405                                 return (ENOBUFS);
406                         }
407                         in_delayed_cksum(m);
408                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
409                 }
410 #if defined(SCTP) || defined(SCTP_SUPPORT)
411                 if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
412                         struct ip *ip;
413
414                         m = mb_unmapped_to_ext(m);
415                         if (m == NULL) {
416                                 IPSECSTAT_INC(ips_out_nomem);
417                                 key_freesp(&sp);
418                                 return (ENOBUFS);
419                         }
420                         ip = mtod(m, struct ip *);
421                         sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
422                         m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
423                 }
424 #endif
425         }
426         /* NB: callee frees mbuf and releases reference to SP */
427         error = ipsec4_check_pmtu(m, sp, forwarding);
428         if (error != 0) {
429                 if (error == EJUSTRETURN)
430                         return (0);
431
432                 return (error);
433         }
434
435         error = ipsec4_process_packet(m, sp, inp);
436         if (error == EJUSTRETURN) {
437                 /*
438                  * We had a SP with a level of 'use' and no SA. We
439                  * will just continue to process the packet without
440                  * IPsec processing and return without error.
441                  */
442                 return (0);
443         }
444         if (error == 0)
445                 return (EINPROGRESS); /* consumed by IPsec */
446         return (error);
447 }
448
449 /*
450  * IPSEC_OUTPUT() method implementation for IPv4.
451  * 0 - no IPsec handling needed
452  * other values - mbuf consumed by IPsec.
453  */
454 int
455 ipsec4_output(struct mbuf *m, struct inpcb *inp)
456 {
457
458         /*
459          * If the packet is resubmitted to ip_output (e.g. after
460          * AH, ESP, etc. processing), there will be a tag to bypass
461          * the lookup and related policy checking.
462          */
463         if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
464                 return (0);
465
466         return (ipsec4_common_output(m, inp, 0));
467 }
468
469 /*
470  * IPSEC_FORWARD() method implementation for IPv4.
471  * 0 - no IPsec handling needed
472  * other values - mbuf consumed by IPsec.
473  */
474 int
475 ipsec4_forward(struct mbuf *m)
476 {
477
478         /*
479          * Check if this packet has an active inbound SP and needs to be
480          * dropped instead of forwarded.
481          */
482         if (ipsec4_in_reject(m, NULL) != 0) {
483                 m_freem(m);
484                 return (EACCES);
485         }
486         return (ipsec4_common_output(m, NULL, 1));
487 }
488 #endif
489
490 #ifdef INET6
491 static int
492 in6_sa_equal_addrwithscope(const struct sockaddr_in6 *sa,
493     const struct in6_addr *ia)
494 {
495         struct in6_addr ia2;
496
497         if (IN6_IS_SCOPE_LINKLOCAL(&sa->sin6_addr)) {
498                 memcpy(&ia2, &sa->sin6_addr, sizeof(ia2));
499                 ia2.s6_addr16[1] = htons(sa->sin6_scope_id);
500                 return (IN6_ARE_ADDR_EQUAL(ia, &ia2));
501         }
502         return (IN6_ARE_ADDR_EQUAL(&sa->sin6_addr, ia));
503 }
504
505 static struct secasvar *
506 ipsec6_allocsa(struct mbuf *m, struct secpolicy *sp, u_int *pidx, int *error)
507 {
508         struct secasindex *saidx, tmpsaidx;
509         struct ipsecrequest *isr;
510         struct sockaddr_in6 *sin6;
511         struct secasvar *sav;
512         struct ip6_hdr *ip6;
513
514         /*
515          * Check system global policy controls.
516          */
517 next:
518         isr = sp->req[*pidx];
519         if ((isr->saidx.proto == IPPROTO_ESP && !V_esp_enable) ||
520             (isr->saidx.proto == IPPROTO_AH && !V_ah_enable) ||
521             (isr->saidx.proto == IPPROTO_IPCOMP && !V_ipcomp_enable)) {
522                 DPRINTF(("%s: IPsec outbound packet dropped due"
523                         " to policy (check your sysctls)\n", __func__));
524                 IPSEC_OSTAT_INC(isr->saidx.proto, pdrops);
525                 *error = EHOSTUNREACH;
526                 return (NULL);
527         }
528         /*
529          * Craft SA index to search for proper SA.  Note that
530          * we only fillin unspecified SA peers for transport
531          * mode; for tunnel mode they must already be filled in.
532          */
533         if (isr->saidx.mode == IPSEC_MODE_TRANSPORT) {
534                 saidx = &tmpsaidx;
535                 *saidx = isr->saidx;
536                 ip6 = mtod(m, struct ip6_hdr *);
537                 if (saidx->src.sin6.sin6_len == 0) {
538                         sin6 = (struct sockaddr_in6 *)&saidx->src;
539                         sin6->sin6_len = sizeof(*sin6);
540                         sin6->sin6_family = AF_INET6;
541                         sin6->sin6_port = IPSEC_PORT_ANY;
542                         sin6->sin6_addr = ip6->ip6_src;
543                         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
544                                 /* fix scope id for comparing SPD */
545                                 sin6->sin6_addr.s6_addr16[1] = 0;
546                                 sin6->sin6_scope_id =
547                                     ntohs(ip6->ip6_src.s6_addr16[1]);
548                         }
549                 }
550                 if (saidx->dst.sin6.sin6_len == 0) {
551                         sin6 = (struct sockaddr_in6 *)&saidx->dst;
552                         sin6->sin6_len = sizeof(*sin6);
553                         sin6->sin6_family = AF_INET6;
554                         sin6->sin6_port = IPSEC_PORT_ANY;
555                         sin6->sin6_addr = ip6->ip6_dst;
556                         if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst)) {
557                                 /* fix scope id for comparing SPD */
558                                 sin6->sin6_addr.s6_addr16[1] = 0;
559                                 sin6->sin6_scope_id =
560                                     ntohs(ip6->ip6_dst.s6_addr16[1]);
561                         }
562                 }
563         } else
564                 saidx = &sp->req[*pidx]->saidx;
565         /*
566          * Lookup SA and validate it.
567          */
568         sav = key_allocsa_policy(sp, saidx, error);
569         if (sav == NULL) {
570                 IPSEC6STAT_INC(ips_out_nosa);
571                 if (*error != 0)
572                         return (NULL);
573                 if (ipsec_get_reqlevel(sp, *pidx) != IPSEC_LEVEL_REQUIRE) {
574                         /*
575                          * We have no SA and policy that doesn't require
576                          * this IPsec transform, thus we can continue w/o
577                          * IPsec processing, i.e. return EJUSTRETURN.
578                          * But first check if there is some bundled transform.
579                          */
580                         if (sp->tcount > ++(*pidx))
581                                 goto next;
582                         *error = EJUSTRETURN;
583                 }
584                 return (NULL);
585         }
586         IPSEC_ASSERT(sav->tdb_xform != NULL, ("SA with NULL tdb_xform"));
587         return (sav);
588 }
589
590 /*
591  * IPsec output logic for IPv6.
592  */
593 static int
594 ipsec6_perform_request(struct mbuf *m, struct secpolicy *sp,
595     struct inpcb *inp, u_int idx)
596 {
597         struct ipsec_ctx_data ctx;
598         union sockaddr_union *dst;
599         struct secasvar *sav;
600         struct ip6_hdr *ip6;
601         int error, i, off;
602
603         IPSEC_ASSERT(idx < sp->tcount, ("Wrong IPsec request index %d", idx));
604
605         sav = ipsec6_allocsa(m, sp, &idx, &error);
606         if (sav == NULL) {
607                 if (error == EJUSTRETURN) { /* No IPsec required */
608                         key_freesp(&sp);
609                         return (error);
610                 }
611                 goto bad;
612         }
613
614         /* Fix IP length in case if it is not set yet. */
615         ip6 = mtod(m, struct ip6_hdr *);
616         ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
617
618         IPSEC_INIT_CTX(&ctx, &m, inp, sav, AF_INET6, IPSEC_ENC_BEFORE);
619         if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
620                 goto bad;
621
622         ip6 = mtod(m, struct ip6_hdr *); /* pfil can change mbuf */
623         dst = &sav->sah->saidx.dst;
624
625         /* Do the appropriate encapsulation, if necessary */
626         if (sp->req[idx]->saidx.mode == IPSEC_MODE_TUNNEL || /* Tunnel requ'd */
627             dst->sa.sa_family != AF_INET6 ||        /* PF mismatch */
628             ((dst->sa.sa_family == AF_INET6) &&
629              (!IN6_IS_ADDR_UNSPECIFIED(&dst->sin6.sin6_addr)) &&
630              (!in6_sa_equal_addrwithscope(&dst->sin6, &ip6->ip6_dst)))) {
631                 if (m->m_pkthdr.len - sizeof(*ip6) > IPV6_MAXPACKET) {
632                         /* No jumbogram support. */
633                         error = ENXIO;   /*XXX*/
634                         goto bad;
635                 }
636                 error = ipsec_encap(&m, &sav->sah->saidx);
637                 if (error != 0) {
638                         DPRINTF(("%s: encapsulation for SPI 0x%08x failed "
639                             "with error %d\n", __func__, ntohl(sav->spi),
640                             error));
641                         /* XXXAE: IPSEC_OSTAT_INC(tunnel); */
642                         goto bad;
643                 }
644                 inp = NULL;
645         }
646
647         IPSEC_INIT_CTX(&ctx, &m, inp, sav, dst->sa.sa_family, IPSEC_ENC_AFTER);
648         if ((error = ipsec_run_hhooks(&ctx, HHOOK_TYPE_IPSEC_OUT)) != 0)
649                 goto bad;
650
651         switch(dst->sa.sa_family) {
652 #ifdef INET
653         case AF_INET:
654                 {
655                 struct ip *ip;
656                 ip = mtod(m, struct ip *);
657                 i = ip->ip_hl << 2;
658                 off = offsetof(struct ip, ip_p);
659                 }
660                 break;
661 #endif /* AF_INET */
662         case AF_INET6:
663                 i = sizeof(struct ip6_hdr);
664                 off = offsetof(struct ip6_hdr, ip6_nxt);
665                 break;
666         default:
667                 DPRINTF(("%s: unsupported protocol family %u\n",
668                                  __func__, dst->sa.sa_family));
669                 error = EPFNOSUPPORT;
670                 IPSEC_OSTAT_INC(sav->sah->saidx.proto, nopf);
671                 goto bad;
672         }
673         error = (*sav->tdb_xform->xf_output)(m, sp, sav, idx, i, off);
674         return (error);
675 bad:
676         IPSEC6STAT_INC(ips_out_inval);
677         if (m != NULL)
678                 m_freem(m);
679         if (sav != NULL)
680                 key_freesav(&sav);
681         key_freesp(&sp);
682         return (error);
683 }
684
685 int
686 ipsec6_process_packet(struct mbuf *m, struct secpolicy *sp,
687     struct inpcb *inp)
688 {
689
690         return (ipsec6_perform_request(m, sp, inp, 0));
691 }
692
693 /*
694  * IPv6 implementation is based on IPv4 implementation.
695  */
696 int
697 ipsec6_check_pmtu(struct mbuf *m, struct secpolicy *sp, int forwarding)
698 {
699         struct secasvar *sav;
700         size_t hlen, pmtu;
701         uint32_t idx;
702         int error;
703
704         /*
705          * According to RFC8200 L3 fragmentation is supposed to be done only on
706          * locally generated packets. During L3 forwarding packets that are too
707          * big are always supposed to be dropped, with an ICMPv6 packet being
708          * sent back.
709          */
710         if (!forwarding)
711                 return (0);
712
713         idx = sp->tcount - 1;
714         sav = ipsec6_allocsa(m, sp, &idx, &error);
715         if (sav == NULL) {
716                 key_freesp(&sp);
717                 /*
718                  * No matching SA was found and SADB_ACQUIRE message was generated.
719                  * Since we have matched a SP to this packet drop it silently.
720                  */
721                 if (error == 0)
722                         error = EINPROGRESS;
723                 if (error != EJUSTRETURN)
724                         m_freem(m);
725
726                 return (error);
727         }
728
729         pmtu = ipsec_get_pmtu(sav);
730         if (pmtu == 0) {
731                 key_freesav(&sav);
732                 return (0);
733         }
734
735         hlen = ipsec_hdrsiz_internal(sp);
736         key_freesav(&sav);
737
738         if (m_length(m, NULL) + hlen > pmtu) {
739                 /*
740                  * If we're forwarding generate ICMPv6 message here,
741                  * so that it contains pmtu subtracted by header size.
742                  * Set error to EINPROGRESS, in order for the frame
743                  * to be dropped silently.
744                  */
745                 if (forwarding) {
746                         if (pmtu > hlen)
747                                 icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0, pmtu - hlen);
748                         else
749                                 m_freem(m);
750
751                         key_freesp(&sp);
752                         return (EINPROGRESS); /* Pretend that we consumed it. */
753                 }
754         }
755
756         return (0);
757 }
758
759 static int
760 ipsec6_common_output(struct mbuf *m, struct inpcb *inp, int forwarding)
761 {
762         struct secpolicy *sp;
763         int error;
764
765         /* Lookup for the corresponding outbound security policy */
766         sp = ipsec6_checkpolicy(m, inp, &error, !forwarding);
767         if (sp == NULL) {
768                 if (error == -EINVAL) {
769                         /* Discarded by policy. */
770                         m_freem(m);
771                         return (EACCES);
772                 }
773                 return (0); /* No IPsec required. */
774         }
775
776         if (!forwarding) {
777                 /*
778                  * Do delayed checksums now because we send before
779                  * this is done in the normal processing path.
780                  */
781                 if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
782                         m = mb_unmapped_to_ext(m);
783                         if (m == NULL) {
784                                 IPSEC6STAT_INC(ips_out_nomem);
785                                 key_freesp(&sp);
786                                 return (ENOBUFS);
787                         }
788                         in6_delayed_cksum(m, m->m_pkthdr.len -
789                             sizeof(struct ip6_hdr), sizeof(struct ip6_hdr));
790                         m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
791                 }
792 #if defined(SCTP) || defined(SCTP_SUPPORT)
793                 if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
794                         m = mb_unmapped_to_ext(m);
795                         if (m == NULL) {
796                                 IPSEC6STAT_INC(ips_out_nomem);
797                                 key_freesp(&sp);
798                                 return (ENOBUFS);
799                         }
800                         sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
801                         m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
802                 }
803 #endif
804         }
805
806         error = ipsec6_check_pmtu(m, sp, forwarding);
807         if (error != 0) {
808                 if (error == EJUSTRETURN)
809                         return (0);
810
811                 return (error);
812         }
813
814         /* NB: callee frees mbuf and releases reference to SP */
815         error = ipsec6_process_packet(m, sp, inp);
816         if (error == EJUSTRETURN) {
817                 /*
818                  * We had a SP with a level of 'use' and no SA. We
819                  * will just continue to process the packet without
820                  * IPsec processing and return without error.
821                  */
822                 return (0);
823         }
824         if (error == 0)
825                 return (EINPROGRESS); /* consumed by IPsec */
826         return (error);
827 }
828
829 /*
830  * IPSEC_OUTPUT() method implementation for IPv6.
831  * 0 - no IPsec handling needed
832  * other values - mbuf consumed by IPsec.
833  */
834 int
835 ipsec6_output(struct mbuf *m, struct inpcb *inp)
836 {
837
838         /*
839          * If the packet is resubmitted to ip_output (e.g. after
840          * AH, ESP, etc. processing), there will be a tag to bypass
841          * the lookup and related policy checking.
842          */
843         if (m_tag_find(m, PACKET_TAG_IPSEC_OUT_DONE, NULL) != NULL)
844                 return (0);
845
846         return (ipsec6_common_output(m, inp, 0));
847 }
848
849 /*
850  * IPSEC_FORWARD() method implementation for IPv6.
851  * 0 - no IPsec handling needed
852  * other values - mbuf consumed by IPsec.
853  */
854 int
855 ipsec6_forward(struct mbuf *m)
856 {
857
858         /*
859          * Check if this packet has an active inbound SP and needs to be
860          * dropped instead of forwarded.
861          */
862         if (ipsec6_in_reject(m, NULL) != 0) {
863                 m_freem(m);
864                 return (EACCES);
865         }
866         return (ipsec6_common_output(m, NULL, 1));
867 }
868 #endif /* INET6 */
869
870 int
871 ipsec_process_done(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
872     u_int idx)
873 {
874         struct epoch_tracker et;
875         struct xform_history *xh;
876         struct secasindex *saidx;
877         struct m_tag *mtag;
878         int error;
879
880         saidx = &sav->sah->saidx;
881         switch (saidx->dst.sa.sa_family) {
882 #ifdef INET
883         case AF_INET:
884                 /* Fix the header length, for AH processing. */
885                 mtod(m, struct ip *)->ip_len = htons(m->m_pkthdr.len);
886                 break;
887 #endif /* INET */
888 #ifdef INET6
889         case AF_INET6:
890                 /* Fix the header length, for AH processing. */
891                 if (m->m_pkthdr.len < sizeof (struct ip6_hdr)) {
892                         error = ENXIO;
893                         goto bad;
894                 }
895                 if (m->m_pkthdr.len - sizeof (struct ip6_hdr) > IPV6_MAXPACKET) {
896                         /* No jumbogram support. */
897                         error = ENXIO;  /*?*/
898                         goto bad;
899                 }
900                 mtod(m, struct ip6_hdr *)->ip6_plen =
901                         htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
902                 break;
903 #endif /* INET6 */
904         default:
905                 DPRINTF(("%s: unknown protocol family %u\n", __func__,
906                     saidx->dst.sa.sa_family));
907                 error = ENXIO;
908                 goto bad;
909         }
910
911         /*
912          * Add a record of what we've done to the packet.
913          */
914         mtag = m_tag_get(PACKET_TAG_IPSEC_OUT_DONE, sizeof(*xh), M_NOWAIT);
915         if (mtag == NULL) {
916                 DPRINTF(("%s: could not get packet tag\n", __func__));
917                 error = ENOMEM;
918                 goto bad;
919         }
920
921         xh = (struct xform_history *)(mtag + 1);
922         xh->dst = saidx->dst;
923         xh->proto = saidx->proto;
924         xh->mode = saidx->mode;
925         xh->spi = sav->spi;
926         m_tag_prepend(m, mtag);
927
928         key_sa_recordxfer(sav, m);              /* record data transfer */
929
930         /*
931          * If there's another (bundled) SA to apply, do so.
932          * Note that this puts a burden on the kernel stack size.
933          * If this is a problem we'll need to introduce a queue
934          * to set the packet on so we can unwind the stack before
935          * doing further processing.
936          */
937         if (++idx < sp->tcount) {
938                 switch (saidx->dst.sa.sa_family) {
939 #ifdef INET
940                 case AF_INET:
941                         key_freesav(&sav);
942                         IPSECSTAT_INC(ips_out_bundlesa);
943                         return (ipsec4_perform_request(m, sp, NULL, idx));
944                         /* NOTREACHED */
945 #endif
946 #ifdef INET6
947                 case AF_INET6:
948                         key_freesav(&sav);
949                         IPSEC6STAT_INC(ips_out_bundlesa);
950                         return (ipsec6_perform_request(m, sp, NULL, idx));
951                         /* NOTREACHED */
952 #endif /* INET6 */
953                 default:
954                         DPRINTF(("%s: unknown protocol family %u\n", __func__,
955                             saidx->dst.sa.sa_family));
956                         error = EPFNOSUPPORT;
957                         goto bad;
958                 }
959         }
960
961         key_freesp(&sp), sp = NULL;     /* Release reference to SP */
962 #ifdef INET
963         /*
964          * Do UDP encapsulation if SA requires it.
965          */
966         if (sav->natt != NULL) {
967                 error = udp_ipsec_output(m, sav);
968                 if (error != 0)
969                         goto bad;
970         }
971 #endif /* INET */
972         /*
973          * We're done with IPsec processing, transmit the packet using the
974          * appropriate network protocol (IP or IPv6).
975          */
976         NET_EPOCH_ENTER(et);
977         switch (saidx->dst.sa.sa_family) {
978 #ifdef INET
979         case AF_INET:
980                 key_freesav(&sav);
981                 error = ip_output(m, NULL, NULL, IP_RAWOUTPUT, NULL, NULL);
982                 break;
983 #endif /* INET */
984 #ifdef INET6
985         case AF_INET6:
986                 key_freesav(&sav);
987                 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
988                 break;
989 #endif /* INET6 */
990         default:
991                 panic("ipsec_process_done");
992         }
993         NET_EPOCH_EXIT(et);
994         return (error);
995 bad:
996         m_freem(m);
997         key_freesav(&sav);
998         if (sp != NULL)
999                 key_freesp(&sp);
1000         return (error);
1001 }
1002
1003 /*
1004  * ipsec_prepend() is optimized version of M_PREPEND().
1005  * ipsec_encap() is called by IPsec output routine for tunnel mode SA.
1006  * It is expected that after IP encapsulation some IPsec transform will
1007  * be performed. Each IPsec transform inserts its variable length header
1008  * just after outer IP header using m_makespace(). If given mbuf has not
1009  * enough free space at the beginning, we allocate new mbuf and reserve
1010  * some space at the beginning and at the end.
1011  * This helps avoid allocating of new mbuf and data copying in m_makespace(),
1012  * we place outer header in the middle of mbuf's data with reserved leading
1013  * and trailing space:
1014  *      [ LEADINGSPACE ][ Outer IP header ][ TRAILINGSPACE ]
1015  * LEADINGSPACE will be used to add ethernet header, TRAILINGSPACE will
1016  * be used to inject AH/ESP/IPCOMP header.
1017  */
1018 #define IPSEC_TRAILINGSPACE     (sizeof(struct udphdr) +/* NAT-T */     \
1019     max(sizeof(struct newesp) + EALG_MAX_BLOCK_LEN,     /* ESP + IV */  \
1020         sizeof(struct newah) + HASH_MAX_LEN             /* AH + ICV */))
1021 static struct mbuf *
1022 ipsec_prepend(struct mbuf *m, int len, int how)
1023 {
1024         struct mbuf *n;
1025
1026         M_ASSERTPKTHDR(m);
1027         IPSEC_ASSERT(len < MHLEN, ("wrong length"));
1028         if (M_LEADINGSPACE(m) >= len) {
1029                 /* No need to allocate new mbuf. */
1030                 m->m_data -= len;
1031                 m->m_len += len;
1032                 m->m_pkthdr.len += len;
1033                 return (m);
1034         }
1035         n = m_gethdr(how, m->m_type);
1036         if (n == NULL) {
1037                 m_freem(m);
1038                 return (NULL);
1039         }
1040         m_move_pkthdr(n, m);
1041         n->m_next = m;
1042         if (len + IPSEC_TRAILINGSPACE < M_SIZE(n))
1043                 m_align(n, len + IPSEC_TRAILINGSPACE);
1044         n->m_len = len;
1045         n->m_pkthdr.len += len;
1046         return (n);
1047 }
1048
1049 static size_t
1050 ipsec_get_pmtu(struct secasvar *sav)
1051 {
1052         union sockaddr_union *dst;
1053         struct in_conninfo inc;
1054         size_t pmtu;
1055
1056         dst = &sav->sah->saidx.dst;
1057         memset(&inc, 0, sizeof(inc));
1058
1059         switch (dst->sa.sa_family) {
1060 #ifdef INET
1061         case AF_INET:
1062                 inc.inc_faddr = satosin(&dst->sa)->sin_addr;
1063                 break;
1064 #endif
1065 #ifdef INET6
1066         case AF_INET6:
1067                 inc.inc6_faddr = satosin6(&dst->sa)->sin6_addr;
1068                 inc.inc_flags |= INC_ISIPV6;
1069                 break;
1070 #endif
1071         default:
1072                 return (0);
1073         }
1074
1075         pmtu = tcp_hc_getmtu(&inc);
1076         if (pmtu != 0)
1077                 return (pmtu);
1078
1079         /* No entry in hostcache. Assume that PMTU is equal to link's MTU */
1080         switch (dst->sa.sa_family) {
1081 #ifdef INET
1082         case AF_INET:
1083                 pmtu = tcp_maxmtu(&inc, NULL);
1084                 break;
1085 #endif
1086 #ifdef INET6
1087         case AF_INET6:
1088                 pmtu = tcp_maxmtu6(&inc, NULL);
1089                 break;
1090 #endif
1091         default:
1092                 return (0);
1093         }
1094         if (pmtu == 0)
1095                 return (0);
1096
1097         tcp_hc_updatemtu(&inc, pmtu);
1098
1099         return (pmtu);
1100 }
1101
1102 static int
1103 ipsec_encap(struct mbuf **mp, struct secasindex *saidx)
1104 {
1105 #ifdef INET6
1106         struct ip6_hdr *ip6;
1107 #endif
1108         struct ip *ip;
1109         int setdf;
1110         uint8_t itos, proto;
1111
1112         ip = mtod(*mp, struct ip *);
1113         switch (ip->ip_v) {
1114 #ifdef INET
1115         case IPVERSION:
1116                 proto = IPPROTO_IPIP;
1117                 /*
1118                  * Collect IP_DF state from the inner header
1119                  * and honor system-wide control of how to handle it.
1120                  */
1121                 switch (V_ip4_ipsec_dfbit) {
1122                 case 0: /* clear in outer header */
1123                 case 1: /* set in outer header */
1124                         setdf = V_ip4_ipsec_dfbit;
1125                         break;
1126                 default:/* propagate to outer header */
1127                         setdf = (ip->ip_off & htons(IP_DF)) != 0;
1128                 }
1129                 itos = ip->ip_tos;
1130                 break;
1131 #endif
1132 #ifdef INET6
1133         case (IPV6_VERSION >> 4):
1134                 proto = IPPROTO_IPV6;
1135                 ip6 = mtod(*mp, struct ip6_hdr *);
1136                 itos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1137                 setdf = V_ip4_ipsec_dfbit ? 1: 0;
1138                 /* scoped address handling */
1139                 in6_clearscope(&ip6->ip6_src);
1140                 in6_clearscope(&ip6->ip6_dst);
1141                 break;
1142 #endif
1143         default:
1144                 return (EAFNOSUPPORT);
1145         }
1146         switch (saidx->dst.sa.sa_family) {
1147 #ifdef INET
1148         case AF_INET:
1149                 if (saidx->src.sa.sa_family != AF_INET ||
1150                     saidx->src.sin.sin_addr.s_addr == INADDR_ANY ||
1151                     saidx->dst.sin.sin_addr.s_addr == INADDR_ANY)
1152                         return (EINVAL);
1153                 *mp = ipsec_prepend(*mp, sizeof(struct ip), M_NOWAIT);
1154                 if (*mp == NULL)
1155                         return (ENOBUFS);
1156                 ip = mtod(*mp, struct ip *);
1157                 ip->ip_v = IPVERSION;
1158                 ip->ip_hl = sizeof(struct ip) >> 2;
1159                 ip->ip_p = proto;
1160                 ip->ip_len = htons((*mp)->m_pkthdr.len);
1161                 ip->ip_ttl = V_ip_defttl;
1162                 ip->ip_sum = 0;
1163                 ip->ip_off = setdf ? htons(IP_DF): 0;
1164                 ip->ip_src = saidx->src.sin.sin_addr;
1165                 ip->ip_dst = saidx->dst.sin.sin_addr;
1166                 ip_ecn_ingress(V_ip4_ipsec_ecn, &ip->ip_tos, &itos);
1167                 ip_fillid(ip);
1168                 break;
1169 #endif /* INET */
1170 #ifdef INET6
1171         case AF_INET6:
1172                 if (saidx->src.sa.sa_family != AF_INET6 ||
1173                     IN6_IS_ADDR_UNSPECIFIED(&saidx->src.sin6.sin6_addr) ||
1174                     IN6_IS_ADDR_UNSPECIFIED(&saidx->dst.sin6.sin6_addr))
1175                         return (EINVAL);
1176                 *mp = ipsec_prepend(*mp, sizeof(struct ip6_hdr), M_NOWAIT);
1177                 if (*mp == NULL)
1178                         return (ENOBUFS);
1179                 ip6 = mtod(*mp, struct ip6_hdr *);
1180                 ip6->ip6_flow = 0;
1181                 ip6->ip6_vfc = IPV6_VERSION;
1182                 ip6->ip6_hlim = V_ip6_defhlim;
1183                 ip6->ip6_nxt = proto;
1184                 ip6->ip6_dst = saidx->dst.sin6.sin6_addr;
1185                 /* For link-local address embed scope zone id */
1186                 if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_dst))
1187                         ip6->ip6_dst.s6_addr16[1] =
1188                             htons(saidx->dst.sin6.sin6_scope_id & 0xffff);
1189                 ip6->ip6_src = saidx->src.sin6.sin6_addr;
1190                 if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src))
1191                         ip6->ip6_src.s6_addr16[1] =
1192                             htons(saidx->src.sin6.sin6_scope_id & 0xffff);
1193                 ip6->ip6_plen = htons((*mp)->m_pkthdr.len - sizeof(*ip6));
1194                 ip_ecn_ingress(V_ip6_ipsec_ecn, &proto, &itos);
1195                 ip6->ip6_flow |= htonl((uint32_t)proto << 20);
1196                 break;
1197 #endif /* INET6 */
1198         default:
1199                 return (EAFNOSUPPORT);
1200         }
1201         (*mp)->m_flags &= ~(M_BCAST | M_MCAST);
1202         return (0);
1203 }