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