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