fd0134e45ac27e02e4e56d1a331e6bb6c98b26f4
[project/odhcpd.git] / src / ndp.c
1 /**
2  * Copyright (C) 2012-2013 Steven Barth <steven@midlink.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License v2 as published by
6  * the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  */
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <signal.h>
18 #include <errno.h>
19
20 #include <fcntl.h>
21 #include <unistd.h>
22 #include <arpa/inet.h>
23 #include <sys/socket.h>
24 #include <net/ethernet.h>
25 #include <netinet/ip6.h>
26 #include <netinet/icmp6.h>
27 #include <netpacket/packet.h>
28
29 #include <linux/rtnetlink.h>
30 #include <linux/filter.h>
31 #include "router.h"
32 #include "ndp.h"
33
34
35
36 static void handle_solicit(void *addr, void *data, size_t len,
37                 struct interface *iface, void *dest);
38 static void handle_rtnetlink(void *addr, void *data, size_t len,
39                 struct interface *iface, void *dest);
40 static ssize_t ping6(struct in6_addr *addr,
41                 const struct interface *iface);
42
43 static uint32_t rtnl_seqid = 0;
44 static int ping_socket = -1;
45 static struct odhcpd_event rtnl_event = {{.fd = -1}, handle_rtnetlink};
46
47
48 // Filter ICMPv6 messages of type neighbor soliciation
49 static struct sock_filter bpf[] = {
50         BPF_STMT(BPF_LD | BPF_B | BPF_ABS, offsetof(struct ip6_hdr, ip6_nxt)),
51         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMPV6, 0, 3),
52         BPF_STMT(BPF_LD | BPF_B | BPF_ABS, sizeof(struct ip6_hdr) +
53                         offsetof(struct icmp6_hdr, icmp6_type)),
54         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_SOLICIT, 0, 1),
55         BPF_STMT(BPF_RET | BPF_K, 0xffffffff),
56         BPF_STMT(BPF_RET | BPF_K, 0),
57 };
58 static const struct sock_fprog bpf_prog = {sizeof(bpf) / sizeof(*bpf), bpf};
59
60
61 // Initialize NDP-proxy
62 int init_ndp(void)
63 {
64         // Setup netlink socket
65         if ((rtnl_event.uloop.fd = odhcpd_open_rtnl()) < 0)
66                 return -1;
67
68         // Receive netlink neighbor and ip-address events
69         uint32_t group = RTNLGRP_IPV6_IFADDR;
70         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK,
71                         NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
72         group = RTNLGRP_IPV6_ROUTE;
73         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK,
74                         NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
75
76         odhcpd_register(&rtnl_event);
77
78         // Open ICMPv6 socket
79         ping_socket = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
80         if (ping_socket < 0) {
81                 syslog(LOG_ERR, "Unable to open raw socket: %s", strerror(errno));
82                         return -1;
83         }
84
85         int val = 2;
86         setsockopt(ping_socket, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
87
88         // This is required by RFC 4861
89         val = 255;
90         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
91         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
92
93         // Filter all packages, we only want to send
94         struct icmp6_filter filt;
95         ICMP6_FILTER_SETBLOCKALL(&filt);
96         setsockopt(ping_socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
97
98
99         // Netlink socket, continued...
100         group = RTNLGRP_NEIGH;
101         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
102
103         return 0;
104 }
105
106
107 static void dump_neigh_table(bool proxy)
108 {
109         struct {
110                 struct nlmsghdr nh;
111                 struct ndmsg ndm;
112         } req = {
113                 {sizeof(req), RTM_GETNEIGH, NLM_F_REQUEST | NLM_F_DUMP,
114                                 ++rtnl_seqid, 0},
115                 {.ndm_family = AF_INET6, .ndm_flags = (proxy) ? NTF_PROXY : 0}
116         };
117         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
118 }
119
120
121 int setup_ndp_interface(struct interface *iface, bool enable)
122 {
123         char procbuf[64];
124         snprintf(procbuf, sizeof(procbuf), "/proc/sys/net/ipv6/conf/%s/proxy_ndp", iface->ifname);
125         int procfd = open(procbuf, O_WRONLY);
126         bool dump_neigh = false;
127
128         if (iface->ndp_event.uloop.fd >= 0) {
129                 uloop_fd_delete(&iface->ndp_event.uloop);
130                 close(iface->ndp_event.uloop.fd);
131                 iface->ndp_event.uloop.fd = -1;
132
133                 write(procfd, "0\n", 2);
134                 dump_neigh = true;
135         }
136
137         if (enable && (iface->ra == RELAYD_SERVER || iface->dhcpv6 == RELAYD_SERVER)) {
138                 // Synthesize initial address events
139                 struct {
140                         struct nlmsghdr nh;
141                         struct ifaddrmsg ifa;
142                 } req2 = {
143                         {sizeof(req2), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
144                                         ++rtnl_seqid, 0},
145                         {.ifa_family = AF_INET6, .ifa_index = iface->ifindex}
146                 };
147                 send(rtnl_event.uloop.fd, &req2, sizeof(req2), MSG_DONTWAIT);
148         }
149
150         if (enable && iface->ndp == RELAYD_RELAY) {
151                 write(procfd, "1\n", 2);
152
153                 int sock = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IPV6));
154                 if (sock < 0) {
155                         syslog(LOG_ERR, "Unable to open packet socket: %s",
156                                         strerror(errno));
157                         return -1;
158                 }
159
160 #ifdef PACKET_RECV_TYPE
161                 int pktt = 1 << PACKET_MULTICAST;
162                 setsockopt(sock, SOL_PACKET, PACKET_RECV_TYPE, &pktt, sizeof(pktt));
163 #endif
164
165                 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER,
166                                 &bpf_prog, sizeof(bpf_prog))) {
167                         syslog(LOG_ERR, "Failed to set BPF: %s", strerror(errno));
168                         return -1;
169                 }
170
171                 struct sockaddr_ll ll = {
172                         .sll_family = AF_PACKET,
173                         .sll_ifindex = iface->ifindex,
174                         .sll_protocol = htons(ETH_P_IPV6),
175                         .sll_hatype = 0,
176                         .sll_pkttype = 0,
177                         .sll_halen = 0,
178                         .sll_addr = {0},
179                 };
180                 bind(sock, (struct sockaddr*)&ll, sizeof(ll));
181
182                 struct packet_mreq mreq = {iface->ifindex, PACKET_MR_ALLMULTI, ETH_ALEN, {0}};
183                 setsockopt(sock, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
184
185                 iface->ndp_event.uloop.fd = sock;
186                 iface->ndp_event.handle_dgram = handle_solicit;
187                 odhcpd_register(&iface->ndp_event);
188
189                 // If we already were enabled dump is unnecessary, if not do dump
190                 if (!dump_neigh)
191                         dump_neigh_table(false);
192                 else
193                         dump_neigh = false;
194         }
195         close(procfd);
196
197         if (dump_neigh)
198                 dump_neigh_table(true);
199
200         return 0;
201 }
202
203
204 // Send an ICMP-ECHO. This is less for actually pinging but for the
205 // neighbor cache to be kept up-to-date.
206 static ssize_t ping6(struct in6_addr *addr,
207                 const struct interface *iface)
208 {
209         struct sockaddr_in6 dest = {AF_INET6, 0, 0, *addr, 0};
210         struct icmp6_hdr echo = {.icmp6_type = ICMP6_ECHO_REQUEST};
211         struct iovec iov = {&echo, sizeof(echo)};
212
213         // Linux seems to not honor IPV6_PKTINFO on raw-sockets, so work around
214         setsockopt(ping_socket, SOL_SOCKET, SO_BINDTODEVICE,
215                         iface->ifname, sizeof(iface->ifname));
216         return odhcpd_send(ping_socket, &dest, &iov, 1, iface);
217 }
218
219
220 // Handle solicitations
221 static void handle_solicit(void *addr, void *data, size_t len,
222                 struct interface *iface, _unused void *dest)
223 {
224         struct ip6_hdr *ip6 = data;
225         struct nd_neighbor_solicit *req = (struct nd_neighbor_solicit*)&ip6[1];
226         struct sockaddr_ll *ll = addr;
227
228         // Solicitation is for duplicate address detection
229         bool ns_is_dad = IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src);
230
231         // Don't forward any non-DAD solicitation for external ifaces
232         // TODO: check if we should even forward DADs for them
233         if (iface->external && !ns_is_dad)
234                 return;
235
236         if (len < sizeof(*ip6) + sizeof(*req))
237                 return; // Invalid reqicitation
238
239         if (IN6_IS_ADDR_LINKLOCAL(&req->nd_ns_target) ||
240                         IN6_IS_ADDR_LOOPBACK(&req->nd_ns_target) ||
241                         IN6_IS_ADDR_MULTICAST(&req->nd_ns_target))
242                 return; // Invalid target
243
244         char ipbuf[INET6_ADDRSTRLEN];
245         inet_ntop(AF_INET6, &req->nd_ns_target, ipbuf, sizeof(ipbuf));
246         syslog(LOG_DEBUG, "Got a NS for %s", ipbuf);
247
248         uint8_t mac[6];
249         odhcpd_get_mac(iface, mac);
250         if (!memcmp(ll->sll_addr, mac, sizeof(mac)))
251                 return; // Looped back
252
253         struct interface *c;
254         list_for_each_entry(c, &interfaces, head)
255                 if (iface->ndp == RELAYD_RELAY && iface != c &&
256                                 (!ns_is_dad || !c->external == false))
257                         ping6(&req->nd_ns_target, c);
258 }
259
260
261 void odhcpd_setup_route(const struct in6_addr *addr, int prefixlen,
262                 const struct interface *iface, const struct in6_addr *gw, bool add)
263 {
264         struct req {
265                 struct nlmsghdr nh;
266                 struct rtmsg rtm;
267                 struct rtattr rta_dst;
268                 struct in6_addr dst_addr;
269                 struct rtattr rta_oif;
270                 uint32_t ifindex;
271                 struct rtattr rta_table;
272                 uint32_t table;
273                 struct rtattr rta_gw;
274                 struct in6_addr gw;
275         } req = {
276                 {sizeof(req), 0, NLM_F_REQUEST, ++rtnl_seqid, 0},
277                 {AF_INET6, prefixlen, 0, 0, 0, 0, 0, 0, 0},
278                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_DST},
279                 *addr,
280                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_OIF},
281                 iface->ifindex,
282                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_TABLE},
283                 RT_TABLE_MAIN,
284                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_GATEWAY},
285                 IN6ADDR_ANY_INIT,
286         };
287
288         if (gw)
289                 req.gw = *gw;
290
291         if (add) {
292                 req.nh.nlmsg_type = RTM_NEWROUTE;
293                 req.nh.nlmsg_flags |= (NLM_F_CREATE | NLM_F_REPLACE);
294                 req.rtm.rtm_protocol = RTPROT_BOOT;
295                 req.rtm.rtm_scope = (gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
296                 req.rtm.rtm_type = RTN_UNICAST;
297         } else {
298                 req.nh.nlmsg_type = RTM_DELROUTE;
299                 req.rtm.rtm_scope = RT_SCOPE_NOWHERE;
300         }
301
302         size_t reqlen = (gw) ? sizeof(req) : offsetof(struct req, rta_gw);
303         send(rtnl_event.uloop.fd, &req, reqlen, MSG_DONTWAIT);
304 }
305
306 // Use rtnetlink to modify kernel routes
307 static void setup_route(struct in6_addr *addr, struct interface *iface,
308                 bool add)
309 {
310         char namebuf[INET6_ADDRSTRLEN];
311         inet_ntop(AF_INET6, addr, namebuf, sizeof(namebuf));
312         syslog(LOG_NOTICE, "%s about %s on %s", (add) ? "Learned" : "Forgot",
313                         namebuf, (iface) ? iface->ifname : "<pending>");
314
315         if (!iface || !iface->learn_routes)
316                 return;
317
318         odhcpd_setup_route(addr, 128, iface, NULL, add);
319 }
320
321
322 // Handler for neighbor cache entries from the kernel. This is our source
323 // to learn and unlearn hosts on interfaces.
324 static void handle_rtnetlink(_unused void *addr, void *data, size_t len,
325                 _unused struct interface *iface, _unused void *dest)
326 {
327         bool dump_neigh = false;
328         struct in6_addr last_solicited = IN6ADDR_ANY_INIT;
329
330         for (struct nlmsghdr *nh = data; NLMSG_OK(nh, len);
331                         nh = NLMSG_NEXT(nh, len)) {
332                 struct rtmsg *rtm = NLMSG_DATA(nh);
333                 if ((nh->nlmsg_type == RTM_NEWROUTE ||
334                                 nh->nlmsg_type == RTM_DELROUTE) &&
335                                 rtm->rtm_dst_len == 0)
336                         raise(SIGUSR1); // Inform about a change in default route
337
338                 struct ndmsg *ndm = NLMSG_DATA(nh);
339                 struct ifaddrmsg *ifa = NLMSG_DATA(nh);
340                 if (nh->nlmsg_type != RTM_NEWNEIGH
341                                 && nh->nlmsg_type != RTM_DELNEIGH
342                                 && nh->nlmsg_type != RTM_NEWADDR
343                                 && nh->nlmsg_type != RTM_DELADDR)
344                         continue; // Unrelated message type
345                 bool is_addr = (nh->nlmsg_type == RTM_NEWADDR
346                                 || nh->nlmsg_type == RTM_DELADDR);
347
348                 // Family and ifindex are on the same offset for NEIGH and ADDR
349                 if (NLMSG_PAYLOAD(nh, 0) < sizeof(*ndm)
350                                 || ndm->ndm_family != AF_INET6)
351                         continue; //
352
353                 // Lookup interface
354                 struct interface *iface;
355                 if (!(iface = odhcpd_get_interface_by_index(ndm->ndm_ifindex)))
356                         continue;
357
358                 // Data to retrieve
359                 size_t rta_offset = (is_addr) ? sizeof(*ifa) : sizeof(*ndm);
360                 uint16_t atype = (is_addr) ? IFA_ADDRESS : NDA_DST;
361                 ssize_t alen = NLMSG_PAYLOAD(nh, rta_offset);
362                 struct in6_addr *addr = NULL;
363
364                 for (struct rtattr *rta = (void*)(((uint8_t*)ndm) + rta_offset);
365                                 RTA_OK(rta, alen); rta = RTA_NEXT(rta, alen))
366                         if (rta->rta_type == atype &&
367                                         RTA_PAYLOAD(rta) >= sizeof(*addr))
368                                 addr = RTA_DATA(rta);
369
370                 // Address not specified or unrelated
371                 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
372                                 IN6_IS_ADDR_MULTICAST(addr))
373                         continue;
374
375                 // Check for states
376                 bool add;
377                 if (is_addr)
378                         add = (nh->nlmsg_type == RTM_NEWADDR);
379                 else
380                         add = (nh->nlmsg_type == RTM_NEWNEIGH && (ndm->ndm_state &
381                                 (NUD_REACHABLE | NUD_STALE | NUD_DELAY | NUD_PROBE
382                                                 | NUD_PERMANENT | NUD_NOARP)));
383
384                 if (iface->ndp == RELAYD_RELAY) {
385                         // Replay change to all neighbor cache
386                         struct {
387                                 struct nlmsghdr nh;
388                                 struct ndmsg ndm;
389                                 struct nlattr nla_dst;
390                                 struct in6_addr dst;
391                         } req = {
392                                 {sizeof(req), RTM_DELNEIGH, NLM_F_REQUEST,
393                                                 ++rtnl_seqid, 0},
394                                 {.ndm_family = AF_INET6, .ndm_flags = NTF_PROXY},
395                                 {sizeof(struct nlattr) + sizeof(struct in6_addr), NDA_DST},
396                                 *addr
397                         };
398
399                         if (ndm->ndm_flags & NTF_PROXY) {
400                                 // Dump & flush proxy entries
401                                 if (nh->nlmsg_type == RTM_NEWNEIGH) {
402                                         req.ndm.ndm_ifindex = iface->ifindex;
403                                         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
404                                         dump_neigh = true;
405                                 }
406                         } else if (add) {
407                                 struct interface *c;
408                                 list_for_each_entry(c, &interfaces, head) {
409                                         if (iface == c)
410                                                 continue;
411
412                                         if (c->ndp == RELAYD_RELAY) {
413                                                 req.nh.nlmsg_type = RTM_NEWNEIGH;
414                                                 req.nh.nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
415
416                                                 req.ndm.ndm_ifindex = c->ifindex;
417                                                 send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
418                                         } else { // Delete NDP cache from interfaces without relay
419                                                 req.nh.nlmsg_type = RTM_DELNEIGH;
420                                                 req.nh.nlmsg_flags &= ~(NLM_F_CREATE | NLM_F_REPLACE);
421
422                                                 req.ndm.ndm_ifindex = c->ifindex;
423                                                 send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
424                                         }
425                                 }
426
427                                 setup_route(addr, iface, true);
428                         } else {
429                                 if (nh->nlmsg_type == RTM_NEWNEIGH) {
430                                         // might be locally originating
431                                         if (!IN6_ARE_ADDR_EQUAL(&last_solicited, addr)) {
432                                                 last_solicited = *addr;
433
434                                                 struct interface *c;
435                                                 list_for_each_entry(c, &interfaces, head)
436                                                         if (iface->ndp == RELAYD_RELAY && iface != c &&
437                                                                         !c->external == false)
438                                                                 ping6(addr, c);
439                                         }
440                                 } else {
441                                         struct interface *c;
442                                         list_for_each_entry(c, &interfaces, head) {
443                                                 if (c->ndp == RELAYD_RELAY && iface != c) {
444                                                         req.ndm.ndm_ifindex = c->ifindex;
445                                                         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
446                                                 }
447                                         }
448                                         setup_route(addr, iface, false);
449
450                                         // also: dump to add proxies back in case it moved elsewhere
451                                         dump_neigh = true;
452                                 }
453                         }
454                 }
455
456                 if (is_addr) {
457                         if (iface->ra == RELAYD_SERVER)
458                                 raise(SIGUSR1); // Inform about a change in addresses
459
460                         if (iface->dhcpv6 == RELAYD_SERVER)
461                                 iface->ia_reconf = true;
462
463                         if (iface->ndp == RELAYD_RELAY && iface->master) {
464                                 // Replay address changes on all slave interfaces
465                                 nh->nlmsg_flags = NLM_F_REQUEST;
466
467                                 if (nh->nlmsg_type == RTM_NEWADDR)
468                                         nh->nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
469
470                                 struct interface *c;
471                                 list_for_each_entry(c, &interfaces, head) {
472                                         if (c->ndp == RELAYD_RELAY && !c->master) {
473                                                 ifa->ifa_index = c->ifindex;
474                                                 send(rtnl_event.uloop.fd, nh, nh->nlmsg_len, MSG_DONTWAIT);
475                                         }
476                                 }
477                         }
478                 }
479         }
480
481         if (dump_neigh)
482                 dump_neigh_table(false);
483 }