Loop until ubus connection succeeds
[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 <arpa/inet.h>
21 #include <sys/socket.h>
22 #include <net/ethernet.h>
23 #include <netinet/ip6.h>
24 #include <netinet/icmp6.h>
25 #include <netpacket/packet.h>
26
27 #include <linux/rtnetlink.h>
28 #include <linux/filter.h>
29 #include "router.h"
30 #include "ndp.h"
31
32
33
34 static void handle_solicit(void *addr, void *data, size_t len,
35                 struct interface *iface);
36 static void handle_rtnetlink(void *addr, void *data, size_t len,
37                 struct interface *iface);
38 static struct ndp_neighbor* find_neighbor(struct in6_addr *addr, bool strict);
39 static void modify_neighbor(struct in6_addr *addr, struct interface *iface,
40                 bool add);
41 static ssize_t ping6(struct in6_addr *addr,
42                 const struct interface *iface);
43
44 static struct list_head neighbors = LIST_HEAD_INIT(neighbors);
45 static size_t neighbor_count = 0;
46 static uint32_t rtnl_seqid = 0;
47
48 static int ping_socket = -1;
49 static struct odhcpd_event ndp_event = {{.fd = -1}, handle_solicit};
50 static struct odhcpd_event rtnl_event = {{.fd = -1}, handle_rtnetlink};
51
52
53 // Filter ICMPv6 messages of type neighbor soliciation
54 static struct sock_filter bpf[] = {
55         BPF_STMT(BPF_LD | BPF_B | BPF_ABS, offsetof(struct ip6_hdr, ip6_nxt)),
56         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMPV6, 0, 3),
57         BPF_STMT(BPF_LD | BPF_B | BPF_ABS, sizeof(struct ip6_hdr) +
58                         offsetof(struct icmp6_hdr, icmp6_type)),
59         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_SOLICIT, 0, 1),
60         BPF_STMT(BPF_RET | BPF_K, 0xffffffff),
61         BPF_STMT(BPF_RET | BPF_K, 0),
62 };
63 static const struct sock_fprog bpf_prog = {sizeof(bpf) / sizeof(*bpf), bpf};
64
65
66 // Initialize NDP-proxy
67 int init_ndp(void)
68 {
69         // Setup netlink socket
70         if ((rtnl_event.uloop.fd = odhcpd_open_rtnl()) < 0)
71                 return -1;
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         // Synthesize initial address events
82         struct {
83                 struct nlmsghdr nh;
84                 struct ifaddrmsg ifa;
85         } req2 = {
86                 {sizeof(req2), RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP,
87                                 ++rtnl_seqid, 0},
88                 {.ifa_family = AF_INET6}
89         };
90         send(rtnl_event.uloop.fd, &req2, sizeof(req2), MSG_DONTWAIT);
91         odhcpd_register(&rtnl_event);
92
93
94         // Create socket for intercepting NDP
95         int sock = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
96                         htons(ETH_P_ALL)); // ETH_P_ALL for ingress + egress
97         if (sock < 0) {
98                 syslog(LOG_ERR, "Unable to open packet socket: %s",
99                                 strerror(errno));
100                 return -1;
101         }
102
103         if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER,
104                         &bpf_prog, sizeof(bpf_prog))) {
105                 syslog(LOG_ERR, "Failed to set BPF: %s", strerror(errno));
106                 return -1;
107         }
108
109         ndp_event.uloop.fd = sock;
110         odhcpd_register(&ndp_event);
111
112         // Open ICMPv6 socket
113         ping_socket = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
114
115         int val = 2;
116         setsockopt(ping_socket, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
117
118         // This is required by RFC 4861
119         val = 255;
120         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
121         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
122
123         // Filter all packages, we only want to send
124         struct icmp6_filter filt;
125         ICMP6_FILTER_SETBLOCKALL(&filt);
126         setsockopt(ping_socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
127
128
129         // Netlink socket, continued...
130         group = RTNLGRP_NEIGH;
131         setsockopt(rtnl_event.uloop.fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
132
133         // Synthesize initial neighbor events
134         struct {
135                 struct nlmsghdr nh;
136                 struct ndmsg ndm;
137         } req = {
138                 {sizeof(req), RTM_GETNEIGH, NLM_F_REQUEST | NLM_F_DUMP,
139                                 ++rtnl_seqid, 0},
140                 {.ndm_family = AF_INET6}
141         };
142         send(rtnl_event.uloop.fd, &req, sizeof(req), MSG_DONTWAIT);
143
144         return 0;
145 }
146
147
148 int setup_ndp_interface(struct interface *iface, bool enable)
149 {
150         struct packet_mreq mreq = {iface->ifindex, PACKET_MR_ALLMULTI, ETH_ALEN, {0}};
151         setsockopt(ndp_event.uloop.fd, SOL_PACKET, PACKET_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
152
153         struct ndp_neighbor *c, *n;
154         list_for_each_entry_safe(c, n, &neighbors, head)
155                 if (c->iface == iface && (c->timeout == 0 || iface->ndp != RELAYD_RELAY || !enable))
156                         modify_neighbor(&c->addr, c->iface, false);
157
158         if (enable && iface->ndp == RELAYD_RELAY) {
159                 setsockopt(ndp_event.uloop.fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
160
161                 if (iface->static_ndp_len) {
162                         char *entry = alloca(iface->static_ndp_len), *saveptr;
163                         memcpy(entry, iface->static_ndp, iface->static_ndp_len);
164
165                         for (entry = strtok_r(entry, " ", &saveptr); entry; entry = strtok_r(NULL, " ", &saveptr)) {
166                                 struct ndp_neighbor *n = malloc(sizeof(*n));
167                                 n->iface = iface;
168                                 n->timeout = 0;
169
170                                 char ipbuf[INET6_ADDRSTRLEN];
171                                 if (sscanf(entry, "%45s/%hhu", ipbuf, &n->len) < 2
172                                                 || n->len > 128 || inet_pton(AF_INET6, ipbuf, &n->addr) != 1) {
173                                         syslog(LOG_ERR, "Invalid static NDP-prefix %s", entry);
174                                         return -1;
175                                 }
176
177                                 list_add(&n->head, &neighbors);
178                         }
179                 }
180         }
181
182         return 0;
183 }
184
185
186 // Send an ICMP-ECHO. This is less for actually pinging but for the
187 // neighbor cache to be kept up-to-date.
188 static ssize_t ping6(struct in6_addr *addr,
189                 const struct interface *iface)
190 {
191         struct sockaddr_in6 dest = {AF_INET6, 0, 0, *addr, 0};
192         struct icmp6_hdr echo = {.icmp6_type = ICMP6_ECHO_REQUEST};
193         struct iovec iov = {&echo, sizeof(echo)};
194
195         // Linux seems to not honor IPV6_PKTINFO on raw-sockets, so work around
196         setsockopt(ping_socket, SOL_SOCKET, SO_BINDTODEVICE,
197                         iface->ifname, sizeof(iface->ifname));
198         return odhcpd_send(ping_socket, &dest, &iov, 1, iface);
199 }
200
201
202 // Handle solicitations
203 static void handle_solicit(void *addr, void *data, size_t len,
204                 struct interface *iface)
205 {
206         struct ip6_hdr *ip6 = data;
207         struct nd_neighbor_solicit *req = (struct nd_neighbor_solicit*)&ip6[1];
208         struct sockaddr_ll *ll = addr;
209
210         // Solicitation is for duplicate address detection
211         bool ns_is_dad = IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src);
212
213         // Don't forward any non-DAD solicitation for external ifaces
214         // TODO: check if we should even forward DADs for them
215         if (iface->external && !ns_is_dad)
216                 return;
217
218         if (len < sizeof(*ip6) + sizeof(*req))
219                 return; // Invalid reqicitation
220
221         if (IN6_IS_ADDR_LINKLOCAL(&req->nd_ns_target) ||
222                         IN6_IS_ADDR_LOOPBACK(&req->nd_ns_target) ||
223                         IN6_IS_ADDR_MULTICAST(&req->nd_ns_target))
224                 return; // Invalid target
225
226         char ipbuf[INET6_ADDRSTRLEN];
227         inet_ntop(AF_INET6, &req->nd_ns_target, ipbuf, sizeof(ipbuf));
228         syslog(LOG_NOTICE, "Got a NS for %s", ipbuf);
229
230         uint8_t mac[6];
231         odhcpd_get_mac(iface, mac);
232         if (!memcmp(ll->sll_addr, mac, sizeof(mac)) &&
233                         ll->sll_pkttype != PACKET_OUTGOING)
234                 return; // Looped back
235
236         time_t now = time(NULL);
237
238         struct ndp_neighbor *n = find_neighbor(&req->nd_ns_target, false);
239         if (n && (n->iface || abs(n->timeout - now) < 5)) {
240                 syslog(LOG_NOTICE, "%s is on %s", ipbuf,
241                                 (n->iface) ? n->iface->ifname : "<pending>");
242                 if (!n->iface || n->iface == iface)
243                         return;
244
245                 // Found on other interface, answer with advertisement
246                 struct {
247                         struct nd_neighbor_advert body;
248                         struct nd_opt_hdr opt_ll_hdr;
249                         uint8_t mac[6];
250                 } advert = {
251                         .body = {
252                                 .nd_na_hdr = {ND_NEIGHBOR_ADVERT,
253                                         0, 0, {{0}}},
254                                 .nd_na_target = req->nd_ns_target,
255                         },
256                         .opt_ll_hdr = {ND_OPT_TARGET_LINKADDR, 1},
257                 };
258
259                 memcpy(advert.mac, mac, sizeof(advert.mac));
260                 advert.body.nd_na_flags_reserved = ND_NA_FLAG_ROUTER |
261                                 ND_NA_FLAG_SOLICITED;
262
263                 struct sockaddr_in6 dest = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
264                 if (!ns_is_dad) // If not DAD, then unicast to source
265                         dest.sin6_addr = ip6->ip6_src;
266
267                 // Linux seems to not honor IPV6_PKTINFO on raw-sockets, so work around
268                 setsockopt(ping_socket, SOL_SOCKET, SO_BINDTODEVICE,
269                                         iface->ifname, sizeof(iface->ifname));
270                 struct iovec iov = {&advert, sizeof(advert)};
271                 odhcpd_send(ping_socket, &dest, &iov, 1, iface);
272         } else {
273                 // Send echo to all other interfaces to see where target is on
274                 // This will trigger neighbor discovery which is what we want.
275                 // We will observe the neighbor cache to see results.
276
277                 ssize_t sent = 0;
278                 struct interface *c;
279                 list_for_each_entry(c, &interfaces, head)
280                         if (iface->ndp == RELAYD_RELAY && iface != c &&
281                                         (!ns_is_dad || !c->external == false))
282                                 sent += ping6(&req->nd_ns_target, c);
283
284                 if (sent > 0) // Sent a ping, add pending neighbor entry
285                         modify_neighbor(&req->nd_ns_target, NULL, true);
286         }
287 }
288
289
290 void odhcpd_setup_route(const struct in6_addr *addr, int prefixlen,
291                 const struct interface *iface, const struct in6_addr *gw, bool add)
292 {
293         struct req {
294                 struct nlmsghdr nh;
295                 struct rtmsg rtm;
296                 struct rtattr rta_dst;
297                 struct in6_addr dst_addr;
298                 struct rtattr rta_oif;
299                 uint32_t ifindex;
300                 struct rtattr rta_table;
301                 uint32_t table;
302                 struct rtattr rta_gw;
303                 struct in6_addr gw;
304         } req = {
305                 {sizeof(req), 0, NLM_F_REQUEST, ++rtnl_seqid, 0},
306                 {AF_INET6, prefixlen, 0, 0, 0, 0, 0, 0, 0},
307                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_DST},
308                 *addr,
309                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_OIF},
310                 iface->ifindex,
311                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_TABLE},
312                 RT_TABLE_MAIN,
313                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_GATEWAY},
314                 IN6ADDR_ANY_INIT,
315         };
316
317         if (gw)
318                 req.gw = *gw;
319
320         if (add) {
321                 req.nh.nlmsg_type = RTM_NEWROUTE;
322                 req.nh.nlmsg_flags |= (NLM_F_CREATE | NLM_F_REPLACE);
323                 req.rtm.rtm_protocol = RTPROT_BOOT;
324                 req.rtm.rtm_scope = (gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
325                 req.rtm.rtm_type = RTN_UNICAST;
326         } else {
327                 req.nh.nlmsg_type = RTM_DELROUTE;
328                 req.rtm.rtm_scope = RT_SCOPE_NOWHERE;
329         }
330
331         size_t reqlen = (gw) ? sizeof(req) : offsetof(struct req, rta_gw);
332         send(rtnl_event.uloop.fd, &req, reqlen, MSG_DONTWAIT);
333 }
334
335 // Use rtnetlink to modify kernel routes
336 static void setup_route(struct in6_addr *addr, struct interface *iface,
337                 bool add)
338 {
339         char namebuf[INET6_ADDRSTRLEN];
340         inet_ntop(AF_INET6, addr, namebuf, sizeof(namebuf));
341         syslog(LOG_NOTICE, "%s about %s on %s", (add) ? "Learned" : "Forgot",
342                         namebuf, (iface) ? iface->ifname : "<pending>");
343
344         if (!iface || !iface->learn_routes)
345                 return;
346
347         odhcpd_setup_route(addr, 128, iface, NULL, add);
348 }
349
350 static void free_neighbor(struct ndp_neighbor *n)
351 {
352         setup_route(&n->addr, n->iface, false);
353         list_del(&n->head);
354         free(n);
355         --neighbor_count;
356 }
357
358
359 static bool match_neighbor(struct ndp_neighbor *n, struct in6_addr *addr)
360 {
361         if (n->len <= 32)
362                 return ntohl(n->addr.s6_addr32[0]) >> (32 - n->len) ==
363                                 ntohl(addr->s6_addr32[0]) >> (32 - n->len);
364
365         if (n->addr.s6_addr32[0] != addr->s6_addr32[0])
366                 return false;
367
368         if (n->len <= 64)
369                 return ntohl(n->addr.s6_addr32[1]) >> (64 - n->len) ==
370                                 ntohl(addr->s6_addr32[1]) >> (64 - n->len);
371
372         if (n->addr.s6_addr32[1] != addr->s6_addr32[1])
373                 return false;
374
375         if (n->len <= 96)
376                 return ntohl(n->addr.s6_addr32[2]) >> (96 - n->len) ==
377                                 ntohl(addr->s6_addr32[2]) >> (96 - n->len);
378
379         if (n->addr.s6_addr32[2] != addr->s6_addr32[2])
380                 return false;
381
382         return ntohl(n->addr.s6_addr32[3]) >> (128 - n->len) ==
383                         ntohl(addr->s6_addr32[3]) >> (128 - n->len);
384 }
385
386
387 static struct ndp_neighbor* find_neighbor(struct in6_addr *addr, bool strict)
388 {
389         time_t now = time(NULL);
390         struct ndp_neighbor *n, *e;
391         list_for_each_entry_safe(n, e, &neighbors, head) {
392                 if ((!strict && match_neighbor(n, addr)) ||
393                                 (n->len == 128 && IN6_ARE_ADDR_EQUAL(&n->addr, addr)))
394                         return n;
395
396                 if (!n->iface && abs(n->timeout - now) >= 5)
397                         free_neighbor(n);
398         }
399         return NULL;
400 }
401
402
403 // Modified our own neighbor-entries
404 static void modify_neighbor(struct in6_addr *addr,
405                 struct interface *iface, bool add)
406 {
407         if (!addr || (void*)addr == (void*)iface)
408                 return;
409
410         struct ndp_neighbor *n = find_neighbor(addr, true);
411         if (!add) { // Delete action
412                 if (n && (!n->iface || n->iface == iface))
413                         free_neighbor(n);
414         } else if (!n) { // No entry yet, add one if possible
415                 if (neighbor_count >= NDP_MAX_NEIGHBORS ||
416                                 !(n = malloc(sizeof(*n))))
417                         return;
418
419                 n->len = 128;
420                 n->addr = *addr;
421                 n->iface = iface;
422                 if (!n->iface)
423                         time(&n->timeout);
424                 list_add(&n->head, &neighbors);
425                 ++neighbor_count;
426                 setup_route(addr, n->iface, add);
427         } else if (n->iface == iface) {
428                 if (!n->iface)
429                         time(&n->timeout);
430         } else if (iface && (!n->iface ||
431                         (!iface->external && n->iface->external))) {
432                 setup_route(addr, n->iface, false);
433                 n->iface = iface;
434                 setup_route(addr, n->iface, add);
435         }
436         // TODO: In case a host switches interfaces we might want
437         // to set its old neighbor entry to NUD_STALE and ping it
438         // on the old interface to confirm if the MACs match.
439 }
440
441
442 // Handler for neighbor cache entries from the kernel. This is our source
443 // to learn and unlearn hosts on interfaces.
444 static void handle_rtnetlink(_unused void *addr, void *data, size_t len,
445                 _unused struct interface *iface)
446 {
447         for (struct nlmsghdr *nh = data; NLMSG_OK(nh, len);
448                         nh = NLMSG_NEXT(nh, len)) {
449                 struct rtmsg *rtm = NLMSG_DATA(nh);
450                 if ((nh->nlmsg_type == RTM_NEWROUTE ||
451                                 nh->nlmsg_type == RTM_DELROUTE) &&
452                                 rtm->rtm_dst_len == 0)
453                         raise(SIGUSR1); // Inform about a change in default route
454
455                 struct ndmsg *ndm = NLMSG_DATA(nh);
456                 struct ifaddrmsg *ifa = NLMSG_DATA(nh);
457                 if (nh->nlmsg_type != RTM_NEWNEIGH
458                                 && nh->nlmsg_type != RTM_DELNEIGH
459                                 && nh->nlmsg_type != RTM_NEWADDR
460                                 && nh->nlmsg_type != RTM_DELADDR)
461                         continue; // Unrelated message type
462                 bool is_addr = (nh->nlmsg_type == RTM_NEWADDR
463                                 || nh->nlmsg_type == RTM_DELADDR);
464
465                 // Family and ifindex are on the same offset for NEIGH and ADDR
466                 if (NLMSG_PAYLOAD(nh, 0) < sizeof(*ndm)
467                                 || ndm->ndm_family != AF_INET6)
468                         continue; //
469
470                 // Lookup interface
471                 struct interface *iface;
472                 if (!(iface = odhcpd_get_interface_by_index(ndm->ndm_ifindex)))
473                         continue;
474
475                 // Data to retrieve
476                 size_t rta_offset = (is_addr) ? sizeof(*ifa) : sizeof(*ndm);
477                 uint16_t atype = (is_addr) ? IFA_ADDRESS : NDA_DST;
478                 ssize_t alen = NLMSG_PAYLOAD(nh, rta_offset);
479                 struct in6_addr *addr = NULL;
480
481                 for (struct rtattr *rta = (void*)(((uint8_t*)ndm) + rta_offset);
482                                 RTA_OK(rta, alen); rta = RTA_NEXT(rta, alen))
483                         if (rta->rta_type == atype &&
484                                         RTA_PAYLOAD(rta) >= sizeof(*addr))
485                                 addr = RTA_DATA(rta);
486
487                 // Address not specified or unrelated
488                 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
489                                 IN6_IS_ADDR_MULTICAST(addr))
490                         continue;
491
492                 // Check for states
493                 bool add;
494                 if (is_addr)
495                         add = (nh->nlmsg_type == RTM_NEWADDR);
496                 else
497                         add = (nh->nlmsg_type == RTM_NEWNEIGH && (ndm->ndm_state &
498                                 (NUD_REACHABLE | NUD_STALE | NUD_DELAY | NUD_PROBE
499                                                 | NUD_PERMANENT | NUD_NOARP)));
500
501                 if (iface->ndp == RELAYD_RELAY)
502                         modify_neighbor(addr, iface, add);
503
504                 if (is_addr && iface->ra == RELAYD_SERVER)
505                         raise(SIGUSR1); // Inform about a change in addresses
506
507                 if (is_addr && iface->dhcpv6 == RELAYD_SERVER)
508                         iface->ia_reconf = true;
509
510                 if (iface->ndp == RELAYD_RELAY && is_addr && iface->master) {
511                         // Replay address changes on all slave interfaces
512                         nh->nlmsg_flags = NLM_F_REQUEST;
513
514                         if (nh->nlmsg_type == RTM_NEWADDR)
515                                 nh->nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
516
517                         struct interface *c;
518                         list_for_each_entry(c, &interfaces, head) {
519                                 if (c->ndp == RELAYD_RELAY && !c->master) {
520                                         ifa->ifa_index = c->ifindex;
521                                         send(rtnl_event.uloop.fd, nh, nh->nlmsg_len, MSG_DONTWAIT);
522                                 }
523                         }
524                 }
525
526                 /* TODO: See if this is required for optimal operation
527                 // Keep neighbor entries alive so we don't loose routes
528                 if (add && (ndm->ndm_state & NUD_STALE))
529                         ping6(addr, iface);
530                 */
531         }
532 }