config: Prioritize ifname resolving via ubus over ifname/networkid attributes
[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 "dhcpv6.h"
33 #include "ndp.h"
34
35
36
37 static void handle_solicit(void *addr, void *data, size_t len,
38                 struct interface *iface, void *dest);
39 static void handle_rtnetlink(void *addr, void *data, size_t len,
40                 struct interface *iface, void *dest);
41 static void catch_rtnetlink(int error);
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, catch_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         int val = 256 * 1024;
65
66         // Setup netlink socket
67         if ((rtnl_event.uloop.fd = odhcpd_open_rtnl()) < 0)
68                 return -1;
69
70         if (setsockopt(rtnl_event.uloop.fd, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)))
71                 setsockopt(rtnl_event.uloop.fd, SOL_SOCKET, SO_RCVBUFFORCE, &val, sizeof(val));
72
73         // Receive netlink neighbor and ip-address events
74         uint32_t group = RTNLGRP_IPV6_IFADDR;
75         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK,
76                         NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
77         group = RTNLGRP_IPV6_ROUTE;
78         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK,
79                         NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
80
81         odhcpd_register(&rtnl_event);
82
83         // Open ICMPv6 socket
84         ping_socket = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
85         if (ping_socket < 0) {
86                 syslog(LOG_ERR, "Unable to open raw socket: %s", strerror(errno));
87                         return -1;
88         }
89
90         val = 2;
91         setsockopt(ping_socket, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
92
93         // This is required by RFC 4861
94         val = 255;
95         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
96         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
97
98         // Filter all packages, we only want to send
99         struct icmp6_filter filt;
100         ICMP6_FILTER_SETBLOCKALL(&filt);
101         setsockopt(ping_socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
102
103
104         // Netlink socket, continued...
105         group = RTNLGRP_NEIGH;
106         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
107
108         return 0;
109 }
110
111
112 static void dump_neigh_table(bool proxy)
113 {
114         struct {
115                 struct nlmsghdr nh;
116                 struct ndmsg ndm;
117         } req = {
118                 {sizeof(req), RTM_GETNEIGH, NLM_F_REQUEST | NLM_F_DUMP,
119                                 ++rtnl_seqid, 0},
120                 {.ndm_family = AF_INET6, .ndm_flags = (proxy) ? NTF_PROXY : 0}
121         };
122         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
123         odhcpd_process(&rtnl_event);
124 }
125
126
127 int setup_ndp_interface(struct interface *iface, bool enable)
128 {
129         char procbuf[64];
130         snprintf(procbuf, sizeof(procbuf), "/proc/sys/net/ipv6/conf/%s/proxy_ndp", iface->ifname);
131         int procfd = open(procbuf, O_WRONLY);
132         bool dump_neigh = false;
133
134         if (iface->ndp_event.uloop.fd > 0) {
135                 uloop_fd_delete(&iface->ndp_event.uloop);
136                 close(iface->ndp_event.uloop.fd);
137                 iface->ndp_event.uloop.fd = -1;
138
139                 if (!enable || iface->ndp != RELAYD_RELAY)
140                         if (write(procfd, "0\n", 2) < 0) {}
141
142                 dump_neigh = true;
143         }
144
145         if (enable && (iface->ra == RELAYD_SERVER ||
146                         iface->dhcpv6 == RELAYD_SERVER || iface->ndp == RELAYD_RELAY)) {
147                 // Synthesize initial address events
148                 struct {
149                         struct nlmsghdr nh;
150                         struct ifaddrmsg ifa;
151                 } req2 = {
152                         {sizeof(req2), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
153                                         ++rtnl_seqid, 0},
154                         {.ifa_family = AF_INET6, .ifa_index = iface->ifindex}
155                 };
156                 send(rtnl_event.uloop.fd, &req2, sizeof(req2), MSG_DONTWAIT);
157         }
158
159         if (enable && iface->ndp == RELAYD_RELAY) {
160                 if (write(procfd, "1\n", 2) < 0) {}
161                 close(procfd);
162
163                 int sock = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IPV6));
164                 if (sock < 0) {
165                         syslog(LOG_ERR, "Unable to open packet socket: %s",
166                                         strerror(errno));
167                         return -1;
168                 }
169
170 #ifdef PACKET_RECV_TYPE
171                 int pktt = 1 << PACKET_MULTICAST;
172                 setsockopt(sock, SOL_PACKET, PACKET_RECV_TYPE, &pktt, sizeof(pktt));
173 #endif
174
175                 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER,
176                                 &bpf_prog, sizeof(bpf_prog))) {
177                         syslog(LOG_ERR, "Failed to set BPF: %s", strerror(errno));
178                         return -1;
179                 }
180
181                 struct sockaddr_ll ll = {
182                         .sll_family = AF_PACKET,
183                         .sll_ifindex = iface->ifindex,
184                         .sll_protocol = htons(ETH_P_IPV6),
185                         .sll_hatype = 0,
186                         .sll_pkttype = 0,
187                         .sll_halen = 0,
188                         .sll_addr = {0},
189                 };
190                 bind(sock, (struct sockaddr*)&ll, sizeof(ll));
191
192                 struct packet_mreq mreq = {iface->ifindex, PACKET_MR_ALLMULTI, ETH_ALEN, {0}};
193                 setsockopt(sock, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
194
195                 iface->ndp_event.uloop.fd = sock;
196                 iface->ndp_event.handle_dgram = handle_solicit;
197                 odhcpd_register(&iface->ndp_event);
198
199                 // If we already were enabled dump is unnecessary, if not do dump
200                 if (!dump_neigh)
201                         dump_neigh_table(false);
202                 else
203                         dump_neigh = false;
204         } else {
205                 close(procfd);
206         }
207
208         if (dump_neigh)
209                 dump_neigh_table(true);
210
211         return 0;
212 }
213
214
215 // Send an ICMP-ECHO. This is less for actually pinging but for the
216 // neighbor cache to be kept up-to-date.
217 static void ping6(struct in6_addr *addr,
218                 const struct interface *iface)
219 {
220         struct sockaddr_in6 dest = {AF_INET6, 0, 0, *addr, iface->ifindex};
221         struct icmp6_hdr echo = {.icmp6_type = ICMP6_ECHO_REQUEST};
222         struct iovec iov = {&echo, sizeof(echo)};
223
224         odhcpd_setup_route(addr, 128, iface, NULL, 128, true);
225         odhcpd_send(ping_socket, &dest, &iov, 1, iface);
226         odhcpd_setup_route(addr, 128, iface, NULL, 128, false);
227 }
228
229
230 // Handle solicitations
231 static void handle_solicit(void *addr, void *data, size_t len,
232                 struct interface *iface, _unused void *dest)
233 {
234         struct ip6_hdr *ip6 = data;
235         struct nd_neighbor_solicit *req = (struct nd_neighbor_solicit*)&ip6[1];
236         struct sockaddr_ll *ll = addr;
237
238         // Solicitation is for duplicate address detection
239         bool ns_is_dad = IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src);
240
241         // Don't forward any non-DAD solicitation for external ifaces
242         // TODO: check if we should even forward DADs for them
243         if (iface->external && !ns_is_dad)
244                 return;
245
246         if (len < sizeof(*ip6) + sizeof(*req))
247                 return; // Invalid reqicitation
248
249         if (IN6_IS_ADDR_LINKLOCAL(&req->nd_ns_target) ||
250                         IN6_IS_ADDR_LOOPBACK(&req->nd_ns_target) ||
251                         IN6_IS_ADDR_MULTICAST(&req->nd_ns_target))
252                 return; // Invalid target
253
254         char ipbuf[INET6_ADDRSTRLEN];
255         inet_ntop(AF_INET6, &req->nd_ns_target, ipbuf, sizeof(ipbuf));
256         syslog(LOG_DEBUG, "Got a NS for %s", ipbuf);
257
258         uint8_t mac[6];
259         odhcpd_get_mac(iface, mac);
260         if (!memcmp(ll->sll_addr, mac, sizeof(mac)))
261                 return; // Looped back
262
263         struct interface *c;
264         list_for_each_entry(c, &interfaces, head)
265                 if (iface->ndp == RELAYD_RELAY && iface != c &&
266                                 (ns_is_dad || !c->external))
267                         ping6(&req->nd_ns_target, c);
268 }
269
270 // Use rtnetlink to modify kernel routes
271 static void setup_route(struct in6_addr *addr, struct interface *iface, bool add)
272 {
273         char namebuf[INET6_ADDRSTRLEN];
274         inet_ntop(AF_INET6, addr, namebuf, sizeof(namebuf));
275         syslog(LOG_NOTICE, "%s about %s on %s",
276                         (add) ? "Learned" : "Forgot", namebuf, iface->ifname);
277
278         if (iface->learn_routes)
279                 odhcpd_setup_route(addr, 128, iface, NULL, 1024, add);
280 }
281
282 // compare prefixes
283 static int prefixcmp(const void *va, const void *vb)
284 {
285         const struct odhcpd_ipaddr *a = va, *b = vb;
286         uint32_t a_pref = ((a->addr.s6_addr[0] & 0xfe) != 0xfc) ? a->preferred : 1;
287         uint32_t b_pref = ((b->addr.s6_addr[0] & 0xfe) != 0xfc) ? b->preferred : 1;
288         return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
289 }
290
291 // Check address update
292 static void check_updates(struct interface *iface)
293 {
294         struct odhcpd_ipaddr addr[8] = {{IN6ADDR_ANY_INIT, 0, 0, 0, 0}};
295         time_t now = odhcpd_time();
296         ssize_t len = odhcpd_get_interface_addresses(iface->ifindex, addr, 8);
297
298         if (len < 0)
299                 return;
300
301         qsort(addr, len, sizeof(*addr), prefixcmp);
302
303         for (int i = 0; i < len; ++i) {
304                 addr[i].addr.s6_addr32[3] = 0;
305
306                 if (addr[i].preferred < UINT32_MAX - now)
307                         addr[i].preferred += now;
308
309                 if (addr[i].valid < UINT32_MAX - now)
310                         addr[i].valid += now;
311         }
312
313         bool change = len != (ssize_t)iface->ia_addr_len;
314         for (ssize_t i = 0; !change && i < len; ++i)
315                 if (!IN6_ARE_ADDR_EQUAL(&addr[i].addr, &iface->ia_addr[i].addr) ||
316                                 (addr[i].preferred > 0) != (iface->ia_addr[i].preferred > 0) ||
317                                 addr[i].valid < iface->ia_addr[i].valid ||
318                                 addr[i].preferred < iface->ia_addr[i].preferred)
319                         change = true;
320
321         if (change)
322                 dhcpv6_ia_preupdate(iface);
323
324         memcpy(iface->ia_addr, addr, len * sizeof(*addr));
325         iface->ia_addr_len = len;
326
327         if (change)
328                 dhcpv6_ia_postupdate(iface, now);
329
330         if (change)
331                 raise(SIGUSR1);
332 }
333
334
335 // Handler for neighbor cache entries from the kernel. This is our source
336 // to learn and unlearn hosts on interfaces.
337 static void handle_rtnetlink(_unused void *addr, void *data, size_t len,
338                 _unused struct interface *iface, _unused void *dest)
339 {
340         bool dump_neigh = false;
341         struct in6_addr last_solicited = IN6ADDR_ANY_INIT;
342
343         for (struct nlmsghdr *nh = data; NLMSG_OK(nh, len);
344                         nh = NLMSG_NEXT(nh, len)) {
345                 struct ndmsg *ndm = NLMSG_DATA(nh);
346                 struct rtmsg *rtm = NLMSG_DATA(nh);
347
348                 bool is_addr = (nh->nlmsg_type == RTM_NEWADDR
349                                 || nh->nlmsg_type == RTM_DELADDR);
350                 bool is_route = (nh->nlmsg_type == RTM_NEWROUTE
351                                 || nh->nlmsg_type == RTM_DELROUTE);
352                 bool is_neigh = (nh->nlmsg_type == RTM_NEWNEIGH
353                                 || nh->nlmsg_type == RTM_DELNEIGH);
354
355                 // Family and ifindex are on the same offset for NEIGH and ADDR
356                 if ((!is_addr && !is_route && !is_neigh)
357                                 || NLMSG_PAYLOAD(nh, 0) < sizeof(*ndm)
358                                 || ndm->ndm_family != AF_INET6)
359                         continue;
360
361                 // Inform about a change in default route
362                 if (is_route && rtm->rtm_dst_len == 0)
363                         raise(SIGUSR1);
364                 else if (is_route)
365                         continue;
366
367                 // Data to retrieve
368                 size_t rta_offset = (is_addr) ? sizeof(struct ifaddrmsg) : sizeof(*ndm);
369                 uint16_t atype = (is_addr) ? IFA_ADDRESS : NDA_DST;
370                 ssize_t alen = NLMSG_PAYLOAD(nh, rta_offset);
371                 struct in6_addr *addr = NULL;
372
373                 for (struct rtattr *rta = (void*)(((uint8_t*)ndm) + rta_offset);
374                                 RTA_OK(rta, alen); rta = RTA_NEXT(rta, alen)) {
375                         if (rta->rta_type == atype &&
376                                         RTA_PAYLOAD(rta) >= sizeof(*addr)) {
377                                 addr = RTA_DATA(rta);
378                         }
379                 }
380
381                 // Lookup interface
382                 struct interface *iface = odhcpd_get_interface_by_index(ndm->ndm_ifindex);
383                 if (!iface)
384                         continue;
385
386                 // Address not specified or unrelated
387                 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
388                                 IN6_IS_ADDR_MULTICAST(addr))
389                         continue;
390
391                 // Check for states
392                 bool add;
393                 if (is_addr)
394                         add = (nh->nlmsg_type == RTM_NEWADDR);
395                 else
396                         add = (nh->nlmsg_type == RTM_NEWNEIGH && (ndm->ndm_state &
397                                 (NUD_REACHABLE | NUD_STALE | NUD_DELAY | NUD_PROBE
398                                                 | NUD_PERMANENT | NUD_NOARP)));
399
400                 if (iface->ndp == RELAYD_RELAY) {
401                         // Replay change to all neighbor cache
402                         struct {
403                                 struct nlmsghdr nh;
404                                 struct ndmsg ndm;
405                                 struct nlattr nla_dst;
406                                 struct in6_addr dst;
407                         } req = {
408                                 {sizeof(req), RTM_DELNEIGH, NLM_F_REQUEST,
409                                                 ++rtnl_seqid, 0},
410                                 {.ndm_family = AF_INET6, .ndm_flags = NTF_PROXY},
411                                 {sizeof(struct nlattr) + sizeof(struct in6_addr), NDA_DST},
412                                 *addr
413                         };
414
415                         if (ndm->ndm_flags & NTF_PROXY) {
416                                 // Dump & flush proxy entries
417                                 if (nh->nlmsg_type == RTM_NEWNEIGH) {
418                                         req.ndm.ndm_ifindex = iface->ifindex;
419                                         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
420                                         setup_route(addr, iface, false);
421                                         dump_neigh = true;
422                                 }
423                         } else if (add) {
424                                 struct interface *c;
425                                 list_for_each_entry(c, &interfaces, head) {
426                                         if (iface == c)
427                                                 continue;
428
429                                         if (c->ndp == RELAYD_RELAY) {
430                                                 req.nh.nlmsg_type = RTM_NEWNEIGH;
431                                                 req.nh.nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
432
433                                                 req.ndm.ndm_ifindex = c->ifindex;
434                                                 send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
435                                         } else { // Delete NDP cache from interfaces without relay
436                                                 req.nh.nlmsg_type = RTM_DELNEIGH;
437                                                 req.nh.nlmsg_flags &= ~(NLM_F_CREATE | NLM_F_REPLACE);
438
439                                                 req.ndm.ndm_ifindex = c->ifindex;
440                                                 send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
441                                         }
442                                 }
443
444                                 setup_route(addr, iface, true);
445                         } else {
446                                 if (nh->nlmsg_type == RTM_NEWNEIGH) {
447                                         // might be locally originating
448                                         if (!IN6_ARE_ADDR_EQUAL(&last_solicited, addr)) {
449                                                 last_solicited = *addr;
450
451                                                 struct interface *c;
452                                                 list_for_each_entry(c, &interfaces, head)
453                                                         if (iface->ndp == RELAYD_RELAY && iface != c &&
454                                                                         !c->external == false)
455                                                                 ping6(addr, c);
456                                         }
457                                 } else {
458                                         struct interface *c;
459                                         list_for_each_entry(c, &interfaces, head) {
460                                                 if (c->ndp == RELAYD_RELAY && iface != c) {
461                                                         req.ndm.ndm_ifindex = c->ifindex;
462                                                         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
463                                                 }
464                                         }
465                                         setup_route(addr, iface, false);
466
467                                         // also: dump to add proxies back in case it moved elsewhere
468                                         dump_neigh = true;
469                                 }
470                         }
471                 }
472
473                 if (is_addr) {
474                         check_updates(iface);
475
476                         if (iface->dhcpv6 == RELAYD_SERVER)
477                                 iface->ia_reconf = true;
478
479                         if (iface->ndp == RELAYD_RELAY && iface->master) {
480                                 // Replay address changes on all slave interfaces
481                                 nh->nlmsg_flags = NLM_F_REQUEST;
482
483                                 if (nh->nlmsg_type == RTM_NEWADDR)
484                                         nh->nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
485
486                                 struct interface *c;
487                                 list_for_each_entry(c, &interfaces, head) {
488                                         if (c->ndp == RELAYD_RELAY && !c->master) {
489                                                 ndm->ndm_ifindex = c->ifindex;
490                                                 send(rtnl_event.uloop.fd, nh, nh->nlmsg_len, MSG_DONTWAIT);
491                                         }
492                                 }
493                         }
494                 }
495         }
496
497         if (dump_neigh)
498                 dump_neigh_table(false);
499 }
500
501 static void catch_rtnetlink(int error)
502 {
503         if (error == ENOBUFS) {
504                 struct {
505                         struct nlmsghdr nh;
506                         struct ifaddrmsg ifa;
507                 } req2 = {
508                         {sizeof(req2), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
509                                         ++rtnl_seqid, 0},
510                         {.ifa_family = AF_INET6}
511                 };
512                 send(rtnl_event.uloop.fd, &req2, sizeof(req2), MSG_DONTWAIT);
513         }
514 }