1 //==========================================================================
3 // src/sys/netinet/ip_encap.c
5 //==========================================================================
6 //####BSDCOPYRIGHTBEGIN####
8 // -------------------------------------------
10 // Portions of this software may have been derived from OpenBSD,
11 // FreeBSD or other sources, and are covered by the appropriate
12 // copyright disclaimers included herein.
14 // Portions created by Red Hat are
15 // Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
17 // -------------------------------------------
19 //####BSDCOPYRIGHTEND####
20 //==========================================================================
22 /* $KAME: ip_encap.c,v 1.73 2001/10/02 08:30:58 itojun Exp $ */
25 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
26 * All rights reserved.
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
31 * 1. Redistributions of source code must retain the above copyright
32 * notice, this list of conditions and the following disclaimer.
33 * 2. Redistributions in binary form must reproduce the above copyright
34 * notice, this list of conditions and the following disclaimer in the
35 * documentation and/or other materials provided with the distribution.
36 * 3. Neither the name of the project nor the names of its contributors
37 * may be used to endorse or promote products derived from this software
38 * without specific prior written permission.
40 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * My grandfather said that there's a devil inside tunnelling technology...
55 * We have surprisingly many protocols that want packets with IP protocol
56 * #4 or #41. Here's a list of protocols that want protocol #41:
57 * RFC1933 configured tunnel
58 * RFC1933 automatic tunnel
59 * RFC2401 IPsec tunnel
60 * RFC2473 IPv6 generic packet tunnelling
61 * RFC2529 6over4 tunnel
64 * mobile-ip6 (uses RFC2473)
65 * Here's a list of protocol that want protocol #4:
66 * RFC1853 IPv4-in-IPv4 tunnelling
67 * RFC2003 IPv4 encapsulation within IPv4
68 * RFC2344 reverse tunnelling for mobile-ip4
69 * RFC2401 IPsec tunnel
70 * Well, what can I say. They impose different en/decapsulation mechanism
71 * from each other, so they need separate protocol handler. The only one
72 * we can easily determine by protocol # is IPsec, which always has
73 * AH/ESP/IPComp header right after outer IP header.
75 * So, clearly good old protosw does not work for protocol #4 and #41.
76 * The code will let you match protocol via src/dst address pair.
78 /* XXX is M_NETADDR correct? */
81 * With USE_RADIX the code will use radix table for tunnel lookup, for
82 * tunnels registered with encap_attach() with a addr/mask pair.
83 * Faster on machines with thousands of tunnel registerations (= interfaces).
85 * The code assumes that radix table code can handle non-continuous netmask,
86 * as it will pass radix table memory region with (src + dst) sockaddr pair.
88 * FreeBSD is excluded here as they make max_keylen a static variable, and
89 * thus forbid definition of radix table other than proper domains.
91 #include <sys/param.h>
92 #include <sys/socket.h>
93 #include <sys/sockio.h>
95 #include <sys/errno.h>
96 #include <sys/protosw.h>
97 #include <sys/queue.h>
100 #include <net/route.h>
102 #include <netinet/in.h>
103 #include <netinet/in_systm.h>
104 #include <netinet/ip.h>
105 #include <netinet/ip_var.h>
106 #include <netinet/ip_encap.h>
108 #include <netinet/ip_mroute.h>
109 #endif /* MROUTING */
111 #include <netinet/ip_ipsp.h>
115 #include <netinet/ip6.h>
116 #include <netinet6/ip6_var.h>
117 #include <netinet6/ip6protosw.h>
118 #include <netinet6/in6_var.h>
119 #if (defined(__FreeBSD__) && __FreeBSD__ >= 3) || defined(__OpenBSD__) || (defined(__bsdi__) && _BSDI_VERSION >= 199802)
120 #include <netinet/in_pcb.h>
122 #include <netinet6/in6_pcb.h>
124 #include <netinet/icmp6.h>
128 #include <sys/malloc.h>
130 /* to lookup a pair of address using radix tree */
131 struct sockaddr_pack {
133 u_int8_t sp_family; /* not really used */
134 /* followed by variable-length data */
135 } __attribute__((__packed__));
138 struct sockaddr_pack p;
139 struct sockaddr_in mine;
140 struct sockaddr_in yours;
141 } __attribute__((__packed__));
143 struct sockaddr_pack p;
144 struct sockaddr_in6 mine;
145 struct sockaddr_in6 yours;
146 } __attribute__((__packed__));
148 enum direction { INBOUND, OUTBOUND };
151 static struct encaptab *encap4_lookup __P((struct mbuf *, int, int,
155 static struct encaptab *encap6_lookup __P((struct mbuf *, int, int,
158 static int encap_add __P((struct encaptab *));
159 static int encap_remove __P((struct encaptab *));
160 static int encap_afcheck __P((int, const struct sockaddr *, const struct sockaddr *));
162 static struct radix_node_head *encap_rnh __P((int));
163 static int mask_matchlen __P((const struct sockaddr *));
166 static int mask_match __P((const struct encaptab *, const struct sockaddr *,
167 const struct sockaddr *));
169 static void encap_fillarg __P((struct mbuf *, const struct encaptab *));
171 #ifndef LIST_HEAD_INITIALIZER
172 /* rely upon BSS initialization */
173 LIST_HEAD(, encaptab) encaptab;
175 LIST_HEAD(, encaptab) encaptab = LIST_HEAD_INITIALIZER(&encaptab);
179 extern int max_keylen; /* radix.c */
180 struct radix_node_head *encap_head[2]; /* 0 for AF_INET, 1 for AF_INET6 */
186 static int initialized = 0;
193 * we cannot use LIST_INIT() here, since drivers may want to call
194 * encap_attach(), on driver attach. encap_init() will be called
195 * on AF_INET{,6} initialization, which happens after driver
196 * initialization - using LIST_INIT() here can nuke encap_attach()
199 LIST_INIT(&encaptab);
204 * initialize radix lookup table.
205 * max_keylen initialization should happen before the call to rn_init().
207 rn_inithead((void **)&encap_head[0], sizeof(struct sockaddr_pack) << 3);
208 if (sizeof(struct pack4) > max_keylen)
209 max_keylen = sizeof(struct pack4);
211 rn_inithead((void **)&encap_head[1], sizeof(struct sockaddr_pack) << 3);
212 if (sizeof(struct pack6) > max_keylen)
213 max_keylen = sizeof(struct pack6);
219 static struct encaptab *
220 encap4_lookup(m, off, proto, dir)
228 struct encaptab *ep, *match;
231 struct radix_node_head *rnh = encap_rnh(AF_INET);
232 struct radix_node *rn;
236 if (m->m_len < sizeof(*ip))
237 panic("encap4_lookup");
239 ip = mtod(m, struct ip *);
241 bzero(&pack, sizeof(pack));
242 pack.p.sp_len = sizeof(pack);
243 pack.mine.sin_family = pack.yours.sin_family = AF_INET;
244 pack.mine.sin_len = pack.yours.sin_len = sizeof(struct sockaddr_in);
245 if (dir == INBOUND) {
246 pack.mine.sin_addr = ip->ip_dst;
247 pack.yours.sin_addr = ip->ip_src;
249 pack.mine.sin_addr = ip->ip_src;
250 pack.yours.sin_addr = ip->ip_dst;
257 rn = rnh->rnh_matchaddr((caddr_t)&pack, rnh);
258 if (rn && (rn->rn_flags & RNF_ROOT) == 0) {
259 match = (struct encaptab *)rn;
260 matchprio = mask_matchlen(match->srcmask) +
261 mask_matchlen(match->dstmask);
265 for (ep = LIST_FIRST(&encaptab); ep; ep = LIST_NEXT(ep, chain)) {
266 if (ep->af != AF_INET)
268 if (ep->proto >= 0 && ep->proto != proto)
271 prio = (*ep->func)(m, off, proto, ep->arg);
276 prio = mask_match(ep, (struct sockaddr *)&pack.mine,
277 (struct sockaddr *)&pack.yours);
282 * We prioritize the matches by using bit length of the
283 * matches. mask_match() and user-supplied matching function
284 * should return the bit length of the matches (for example,
285 * if both src/dst are matched for IPv4, 64 should be returned).
286 * 0 or negative return value means "it did not match".
288 * The question is, since we have two "mask" portion, we
289 * cannot really define total order between entries.
290 * For example, which of these should be preferred?
291 * mask_match() returns 48 (32 + 16) for both of them.
292 * src=3ffe::/16, dst=3ffe:501::/32
293 * src=3ffe:501::/32, dst=3ffe::/16
295 * We need to loop through all the possible candidates
296 * to get the best match - the search takes O(n) for
297 * n attachments (i.e. interfaces).
299 * For radix-based lookup, I guess source takes precedence.
300 * See rn_{refines,lexobetter} for the correct answer.
304 if (prio > matchprio) {
316 #if (defined(__FreeBSD__) && __FreeBSD__ >= 4)
317 encap4_input(struct mbuf *m, int off)
320 encap4_input(struct mbuf *m, ...)
322 encap4_input(m, va_alist)
326 #endif /* (defined(__FreeBSD__) && __FreeBSD__ >= 4) */
328 #if !(defined(__FreeBSD__) && __FreeBSD__ >= 4)
333 #endif /* !(defined(__FreeBSD__) && __FreeBSD__ >= 4) */
334 const struct protosw *psw;
335 struct encaptab *match;
337 #if !(defined(__FreeBSD__) && __FreeBSD__ >= 4)
339 off = va_arg(ap, int);
340 #if !defined(__OpenBSD__)
341 proto = va_arg(ap, int);
344 #endif /* !(defined(__FreeBSD__) && __FreeBSD__ >= 4) */
346 #if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ >= 4)
347 proto = mtod(m, struct ip *)->ip_p;
350 match = encap4_lookup(m, off, proto, INBOUND);
353 /* found a match, "match" has the best one */
355 if (psw && psw->pr_input) {
356 encap_fillarg(m, match);
357 #if defined(__FreeBSD__) && __FreeBSD__ >= 4
358 (*psw->pr_input)(m, off);
360 (*psw->pr_input)(m, off, proto);
367 /* for backward compatibility - messy... */
368 #if defined(__NetBSD__)
369 /* last resort: inject to raw socket */
370 rip_input(m, off, proto);
371 #elif defined(__OpenBSD__)
372 # if defined(MROUTING) || defined(IPSEC)
373 if (proto == IPPROTO_IPV4) {
374 ip4_input(m, off, proto);
379 /* last resort: inject to raw socket */
380 rip_input(m, off, proto);
381 #elif (defined(__FreeBSD__) && __FreeBSD__ >= 5)
382 /* last resort: inject to raw socket */
384 #elif defined(__FreeBSD__) && __FreeBSD__ >= 4
386 if (proto == IPPROTO_IPV4) {
392 /* last resort: inject to raw socket */
396 if (proto == IPPROTO_IPV4) {
397 ipip_input(m, off, proto);
402 /* last resort: inject to raw socket */
403 rip_input(m, off, proto);
409 static struct encaptab *
410 encap6_lookup(m, off, proto, dir)
419 struct encaptab *ep, *match;
421 struct radix_node_head *rnh = encap_rnh(AF_INET6);
422 struct radix_node *rn;
426 if (m->m_len < sizeof(*ip6))
427 panic("encap6_lookup");
429 ip6 = mtod(m, struct ip6_hdr *);
431 bzero(&pack, sizeof(pack));
432 pack.p.sp_len = sizeof(pack);
433 pack.mine.sin6_family = pack.yours.sin6_family = AF_INET6;
434 pack.mine.sin6_len = pack.yours.sin6_len = sizeof(struct sockaddr_in6);
435 if (dir == INBOUND) {
436 pack.mine.sin6_addr = ip6->ip6_dst;
437 pack.yours.sin6_addr = ip6->ip6_src;
439 pack.mine.sin6_addr = ip6->ip6_src;
440 pack.yours.sin6_addr = ip6->ip6_dst;
447 rn = rnh->rnh_matchaddr((caddr_t)&pack, rnh);
448 if (rn && (rn->rn_flags & RNF_ROOT) == 0) {
449 match = (struct encaptab *)rn;
450 matchprio = mask_matchlen(match->srcmask) +
451 mask_matchlen(match->dstmask);
455 for (ep = LIST_FIRST(&encaptab); ep; ep = LIST_NEXT(ep, chain)) {
456 if (ep->af != AF_INET6)
458 if (ep->proto >= 0 && ep->proto != proto)
461 prio = (*ep->func)(m, off, proto, ep->arg);
466 prio = mask_match(ep, (struct sockaddr *)&pack.mine,
467 (struct sockaddr *)&pack.yours);
471 /* see encap4_lookup() for issues here */
474 if (prio > matchprio) {
486 encap6_input(mp, offp, proto)
491 struct mbuf *m = *mp;
492 const struct ip6protosw *psw;
493 struct encaptab *match;
495 match = encap6_lookup(m, *offp, proto, INBOUND);
499 psw = (const struct ip6protosw *)match->psw;
500 if (psw && psw->pr_input) {
501 encap_fillarg(m, match);
502 return (*psw->pr_input)(mp, offp, proto);
511 return ip4_input6(mp, offp, 0); /* XXX last argument ignored */
513 /* last resort: inject to raw socket */
514 return rip6_input(mp, offp, proto);
524 struct radix_node_head *rnh = encap_rnh(ep->af);
528 LIST_INSERT_HEAD(&encaptab, ep, chain);
530 if (!ep->func && rnh) {
531 if (!rnh->rnh_addaddr((caddr_t)ep->addrpack,
532 (caddr_t)ep->maskpack, rnh, ep->nodes)) {
542 LIST_REMOVE(ep, chain);
552 struct radix_node_head *rnh = encap_rnh(ep->af);
556 LIST_REMOVE(ep, chain);
558 if (!ep->func && rnh) {
559 if (!rnh->rnh_deladdr((caddr_t)ep->addrpack,
560 (caddr_t)ep->maskpack, rnh))
568 encap_afcheck(af, sp, dp)
570 const struct sockaddr *sp;
571 const struct sockaddr *dp;
574 if (sp->sa_len != dp->sa_len)
576 if (af != sp->sa_family || af != dp->sa_family)
578 } else if (!sp && !dp)
585 if (sp && sp->sa_len != sizeof(struct sockaddr_in))
587 if (dp && dp->sa_len != sizeof(struct sockaddr_in))
592 if (sp && sp->sa_len != sizeof(struct sockaddr_in6))
594 if (dp && dp->sa_len != sizeof(struct sockaddr_in6))
606 * sp (src ptr) is always my side, and dp (dst ptr) is always remote side.
607 * length of mask (sm and dm) is assumed to be same as sp/dp.
608 * Return value will be necessary as input (cookie) for encap_detach().
610 const struct encaptab *
611 encap_attach(af, proto, sp, sm, dp, dm, psw, arg)
614 const struct sockaddr *sp, *sm;
615 const struct sockaddr *dp, *dm;
616 const struct protosw *psw;
628 #if defined(__NetBSD__) || defined(__OpenBSD__)
633 /* sanity check on args */
634 error = encap_afcheck(af, sp, dp);
638 /* check if anyone have already attached with exactly same config */
639 for (ep = LIST_FIRST(&encaptab); ep; ep = LIST_NEXT(ep, chain)) {
642 if (ep->proto != proto)
647 if (!ep->src || !ep->dst || !ep->srcmask || !ep->dstmask)
648 panic("null pointers in encaptab");
650 if (ep->src->sa_len != sp->sa_len ||
651 bcmp(ep->src, sp, sp->sa_len) != 0 ||
652 bcmp(ep->srcmask, sm, sp->sa_len) != 0)
654 if (ep->dst->sa_len != dp->sa_len ||
655 bcmp(ep->dst, dp, dp->sa_len) != 0 ||
656 bcmp(ep->dstmask, dm, dp->sa_len) != 0)
677 /* if l exceeds the value sa_len can possibly express, it's wrong. */
678 if (l > (1 << (8 * sizeof(ep->addrpack->sa_len)))) {
684 ep = malloc(sizeof(*ep), M_NETADDR, M_NOWAIT); /* M_NETADDR ok? */
689 bzero(ep, sizeof(*ep));
690 ep->addrpack = malloc(l, M_NETADDR, M_NOWAIT);
691 if (ep->addrpack == NULL) {
695 ep->maskpack = malloc(l, M_NETADDR, M_NOWAIT);
696 if (ep->maskpack == NULL) {
703 ep->addrpack->sa_len = l & 0xff;
704 ep->maskpack->sa_len = l & 0xff;
707 pack4 = (struct pack4 *)ep->addrpack;
708 ep->src = (struct sockaddr *)&pack4->mine;
709 ep->dst = (struct sockaddr *)&pack4->yours;
710 pack4 = (struct pack4 *)ep->maskpack;
711 ep->srcmask = (struct sockaddr *)&pack4->mine;
712 ep->dstmask = (struct sockaddr *)&pack4->yours;
716 pack6 = (struct pack6 *)ep->addrpack;
717 ep->src = (struct sockaddr *)&pack6->mine;
718 ep->dst = (struct sockaddr *)&pack6->yours;
719 pack6 = (struct pack6 *)ep->maskpack;
720 ep->srcmask = (struct sockaddr *)&pack6->mine;
721 ep->dstmask = (struct sockaddr *)&pack6->yours;
726 bcopy(sp, ep->src, sp->sa_len);
727 bcopy(sm, ep->srcmask, sp->sa_len);
728 bcopy(dp, ep->dst, dp->sa_len);
729 bcopy(dm, ep->dstmask, dp->sa_len);
733 error = encap_add(ep);
743 free(ep->addrpack, M_NETADDR);
745 free(ep->maskpack, M_NETADDR);
753 const struct encaptab *
754 encap_attach_func(af, proto, func, psw, arg)
757 int (*func) __P((const struct mbuf *, int, int, void *));
758 const struct protosw *psw;
765 #if defined(__NetBSD__) || defined(__OpenBSD__)
770 /* sanity check on args */
776 error = encap_afcheck(af, NULL, NULL);
780 ep = malloc(sizeof(*ep), M_NETADDR, M_NOWAIT); /*XXX*/
785 bzero(ep, sizeof(*ep));
793 error = encap_add(ep);
806 /* XXX encap4_ctlinput() is necessary if we set DF=1 on outer IPv4 header */
809 #if defined(HAVE_NRL_INPCB) || (defined(__FreeBSD__) && __FreeBSD__ >= 3)
811 #define in6_rtchange in_rtchange
816 encap6_ctlinput(cmd, sa, d0)
825 struct ip6ctlparam *ip6cp = NULL;
826 const struct sockaddr_in6 *sa6_src = NULL;
830 const struct ip6protosw *psw;
832 if (sa->sa_family != AF_INET6 ||
833 sa->sa_len != sizeof(struct sockaddr_in6))
836 if ((unsigned)cmd >= PRC_NCMDS)
838 if (cmd == PRC_HOSTDEAD)
840 #if defined(__NetBSD__) || defined(__OpenBSD__)
841 else if (cmd == PRC_MSGSIZE)
842 ; /* special code is present, see below */
844 else if (inet6ctlerrmap[cmd] == 0)
847 /* if the parameter is from icmp6, decode it. */
849 ip6cp = (struct ip6ctlparam *)d;
851 ip6 = ip6cp->ip6c_ip6;
852 off = ip6cp->ip6c_off;
853 cmdarg = ip6cp->ip6c_cmdarg;
854 sa6_src = ip6cp->ip6c_src;
855 nxt = ip6cp->ip6c_nxt;
864 #if defined(__NetBSD__) || defined(__OpenBSD__)
865 if (ip6 && cmd == PRC_MSGSIZE) {
867 struct encaptab *match;
870 * Check to see if we have a valid encap configuration.
872 match = encap6_lookup(m, off, nxt, OUTBOUND);
878 * Depending on the value of "valid" and routing table
879 * size (mtudisc_{hi,lo}wat), we will:
880 * - recalcurate the new MTU and create the
881 * corresponding routing entry, or
882 * - ignore the MTU change notification.
884 icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
888 /* inform all listeners */
889 for (ep = LIST_FIRST(&encaptab); ep; ep = LIST_NEXT(ep, chain)) {
890 if (ep->af != AF_INET6)
892 if (ep->proto >= 0 && ep->proto != nxt)
895 /* should optimize by looking at address pairs */
897 /* XXX need to pass ep->arg or ep itself to listeners */
898 psw = (const struct ip6protosw *)ep->psw;
899 if (psw && psw->pr_ctlinput)
900 (*psw->pr_ctlinput)(cmd, sa, d);
903 rip6_ctlinput(cmd, sa, d0);
909 const struct encaptab *cookie;
911 const struct encaptab *ep = cookie;
915 for (p = LIST_FIRST(&encaptab); p; p = LIST_NEXT(p, chain)) {
917 error = encap_remove(p);
921 free(p->addrpack, M_NETADDR);
922 free(p->maskpack, M_NETADDR);
924 free(p, M_NETADDR); /*XXX*/
933 static struct radix_node_head *
940 return encap_head[0];
943 return encap_head[1];
952 const struct sockaddr *sa;
957 p = (const char *)sa;
959 p += 2; /* sa_len + sa_family */
963 l += (*p ? 8 : 0); /* estimate */
972 mask_match(ep, sp, dp)
973 const struct encaptab *ep;
974 const struct sockaddr *sp;
975 const struct sockaddr *dp;
977 struct sockaddr_storage s;
978 struct sockaddr_storage d;
980 const u_int8_t *p, *q;
986 panic("wrong encaptab passed to mask_match");
988 if (sp->sa_len > sizeof(s) || dp->sa_len > sizeof(d))
990 if (sp->sa_family != ep->af || dp->sa_family != ep->af)
992 if (sp->sa_len != ep->src->sa_len || dp->sa_len != ep->dst->sa_len)
997 p = (const u_int8_t *)sp;
998 q = (const u_int8_t *)ep->srcmask;
1000 for (i = 0 ; i < sp->sa_len; i++) {
1003 matchlen += (q[i] ? 8 : 0);
1006 p = (const u_int8_t *)dp;
1007 q = (const u_int8_t *)ep->dstmask;
1009 for (i = 0 ; i < dp->sa_len; i++) {
1011 /* XXX rough estimate */
1012 matchlen += (q[i] ? 8 : 0);
1015 /* need to overwrite len/family portion as we don't compare them */
1016 s.ss_len = sp->sa_len;
1017 s.ss_family = sp->sa_family;
1018 d.ss_len = dp->sa_len;
1019 d.ss_family = dp->sa_family;
1021 if (bcmp(&s, ep->src, ep->src->sa_len) == 0 &&
1022 bcmp(&d, ep->dst, ep->dst->sa_len) == 0) {
1030 encap_fillarg(m, ep)
1032 const struct encaptab *ep;
1036 n = m_aux_add(m, AF_INET, IPPROTO_IPV4);
1038 *mtod(n, void **) = ep->arg;
1039 n->m_len = sizeof(void *);
1051 n = m_aux_find(m, AF_INET, IPPROTO_IPV4);
1053 if (n->m_len == sizeof(void *))
1054 p = *mtod(n, void **);