Fix parsing of static ndp entries
[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                         if (!entry) {
164                                 syslog(LOG_ERR, "Alloca failed for static NDP list");
165                                 return -1;
166                         }
167                         memcpy(entry, iface->static_ndp, iface->static_ndp_len);
168
169                         for (entry = strtok_r(entry, " ", &saveptr); entry; entry = strtok_r(NULL, " ", &saveptr)) {
170                                 char *sep;
171                                 struct ndp_neighbor *n = malloc(sizeof(*n));
172                                 if (!n) {
173                                         syslog(LOG_ERR, "Malloc failed for static NDP-prefix %s", entry);
174                                         return -1;
175                                 }
176
177                                 n->iface = iface;
178                                 n->timeout = 0;
179
180                                 sep = strchr(entry, '/');
181                                 if (!sep) {
182                                         free(n);
183                                         syslog(LOG_ERR, "Invalid static NDP-prefix %s", entry);
184                                         return -1;
185                                 }
186                                 
187                                 *sep = 0;
188                                 n->len = atoi(sep + 1);
189                                 if (inet_pton(AF_INET6, entry, &n->addr) != 1 || n->len > 128) {
190                                         free(n);
191                                         syslog(LOG_ERR, "Invalid static NDP-prefix %s/%s", entry, sep + 1);
192                                         return -1;
193                                 }
194
195                                 list_add(&n->head, &neighbors);
196                         }
197                 }
198         }
199
200         return 0;
201 }
202
203
204 // Send an ICMP-ECHO. This is less for actually pinging but for the
205 // neighbor cache to be kept up-to-date.
206 static ssize_t ping6(struct in6_addr *addr,
207                 const struct interface *iface)
208 {
209         struct sockaddr_in6 dest = {AF_INET6, 0, 0, *addr, 0};
210         struct icmp6_hdr echo = {.icmp6_type = ICMP6_ECHO_REQUEST};
211         struct iovec iov = {&echo, sizeof(echo)};
212
213         // Linux seems to not honor IPV6_PKTINFO on raw-sockets, so work around
214         setsockopt(ping_socket, SOL_SOCKET, SO_BINDTODEVICE,
215                         iface->ifname, sizeof(iface->ifname));
216         return odhcpd_send(ping_socket, &dest, &iov, 1, iface);
217 }
218
219
220 // Handle solicitations
221 static void handle_solicit(void *addr, void *data, size_t len,
222                 struct interface *iface)
223 {
224         struct ip6_hdr *ip6 = data;
225         struct nd_neighbor_solicit *req = (struct nd_neighbor_solicit*)&ip6[1];
226         struct sockaddr_ll *ll = addr;
227
228         // Solicitation is for duplicate address detection
229         bool ns_is_dad = IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src);
230
231         // Don't forward any non-DAD solicitation for external ifaces
232         // TODO: check if we should even forward DADs for them
233         if (iface->external && !ns_is_dad)
234                 return;
235
236         if (len < sizeof(*ip6) + sizeof(*req))
237                 return; // Invalid reqicitation
238
239         if (IN6_IS_ADDR_LINKLOCAL(&req->nd_ns_target) ||
240                         IN6_IS_ADDR_LOOPBACK(&req->nd_ns_target) ||
241                         IN6_IS_ADDR_MULTICAST(&req->nd_ns_target))
242                 return; // Invalid target
243
244         char ipbuf[INET6_ADDRSTRLEN];
245         inet_ntop(AF_INET6, &req->nd_ns_target, ipbuf, sizeof(ipbuf));
246         syslog(LOG_DEBUG, "Got a NS for %s", ipbuf);
247
248         uint8_t mac[6];
249         odhcpd_get_mac(iface, mac);
250         if (!memcmp(ll->sll_addr, mac, sizeof(mac)) &&
251                         ll->sll_pkttype != PACKET_OUTGOING)
252                 return; // Looped back
253
254         time_t now = time(NULL);
255
256         struct ndp_neighbor *n = find_neighbor(&req->nd_ns_target, false);
257         if (n && (n->iface || abs(n->timeout - now) < 5)) {
258                 syslog(LOG_DEBUG, "%s is on %s", ipbuf,
259                                 (n->iface) ? n->iface->ifname : "<pending>");
260                 if (!n->iface || n->iface == iface)
261                         return;
262
263                 // Found on other interface, answer with advertisement
264                 struct {
265                         struct nd_neighbor_advert body;
266                         struct nd_opt_hdr opt_ll_hdr;
267                         uint8_t mac[6];
268                 } advert = {
269                         .body = {
270                                 .nd_na_hdr = {ND_NEIGHBOR_ADVERT,
271                                         0, 0, {{0}}},
272                                 .nd_na_target = req->nd_ns_target,
273                         },
274                         .opt_ll_hdr = {ND_OPT_TARGET_LINKADDR, 1},
275                 };
276
277                 memcpy(advert.mac, mac, sizeof(advert.mac));
278                 advert.body.nd_na_flags_reserved = ND_NA_FLAG_ROUTER |
279                                 ND_NA_FLAG_SOLICITED;
280
281                 struct sockaddr_in6 dest = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
282                 if (!ns_is_dad) // If not DAD, then unicast to source
283                         dest.sin6_addr = ip6->ip6_src;
284
285                 // Linux seems to not honor IPV6_PKTINFO on raw-sockets, so work around
286                 setsockopt(ping_socket, SOL_SOCKET, SO_BINDTODEVICE,
287                                         iface->ifname, sizeof(iface->ifname));
288                 struct iovec iov = {&advert, sizeof(advert)};
289                 odhcpd_send(ping_socket, &dest, &iov, 1, iface);
290         } else {
291                 // Send echo to all other interfaces to see where target is on
292                 // This will trigger neighbor discovery which is what we want.
293                 // We will observe the neighbor cache to see results.
294
295                 ssize_t sent = 0;
296                 struct interface *c;
297                 list_for_each_entry(c, &interfaces, head)
298                         if (iface->ndp == RELAYD_RELAY && iface != c &&
299                                         (!ns_is_dad || !c->external == false))
300                                 sent += ping6(&req->nd_ns_target, c);
301
302                 if (sent > 0) // Sent a ping, add pending neighbor entry
303                         modify_neighbor(&req->nd_ns_target, NULL, true);
304         }
305 }
306
307
308 void odhcpd_setup_route(const struct in6_addr *addr, int prefixlen,
309                 const struct interface *iface, const struct in6_addr *gw, bool add)
310 {
311         struct req {
312                 struct nlmsghdr nh;
313                 struct rtmsg rtm;
314                 struct rtattr rta_dst;
315                 struct in6_addr dst_addr;
316                 struct rtattr rta_oif;
317                 uint32_t ifindex;
318                 struct rtattr rta_table;
319                 uint32_t table;
320                 struct rtattr rta_gw;
321                 struct in6_addr gw;
322         } req = {
323                 {sizeof(req), 0, NLM_F_REQUEST, ++rtnl_seqid, 0},
324                 {AF_INET6, prefixlen, 0, 0, 0, 0, 0, 0, 0},
325                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_DST},
326                 *addr,
327                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_OIF},
328                 iface->ifindex,
329                 {sizeof(struct rtattr) + sizeof(uint32_t), RTA_TABLE},
330                 RT_TABLE_MAIN,
331                 {sizeof(struct rtattr) + sizeof(struct in6_addr), RTA_GATEWAY},
332                 IN6ADDR_ANY_INIT,
333         };
334
335         if (gw)
336                 req.gw = *gw;
337
338         if (add) {
339                 req.nh.nlmsg_type = RTM_NEWROUTE;
340                 req.nh.nlmsg_flags |= (NLM_F_CREATE | NLM_F_REPLACE);
341                 req.rtm.rtm_protocol = RTPROT_BOOT;
342                 req.rtm.rtm_scope = (gw) ? RT_SCOPE_UNIVERSE : RT_SCOPE_LINK;
343                 req.rtm.rtm_type = RTN_UNICAST;
344         } else {
345                 req.nh.nlmsg_type = RTM_DELROUTE;
346                 req.rtm.rtm_scope = RT_SCOPE_NOWHERE;
347         }
348
349         size_t reqlen = (gw) ? sizeof(req) : offsetof(struct req, rta_gw);
350         send(rtnl_event.uloop.fd, &req, reqlen, MSG_DONTWAIT);
351 }
352
353 // Use rtnetlink to modify kernel routes
354 static void setup_route(struct in6_addr *addr, struct interface *iface,
355                 bool add)
356 {
357         char namebuf[INET6_ADDRSTRLEN];
358         inet_ntop(AF_INET6, addr, namebuf, sizeof(namebuf));
359         syslog(LOG_NOTICE, "%s about %s on %s", (add) ? "Learned" : "Forgot",
360                         namebuf, (iface) ? iface->ifname : "<pending>");
361
362         if (!iface || !iface->learn_routes)
363                 return;
364
365         odhcpd_setup_route(addr, 128, iface, NULL, add);
366 }
367
368 static void free_neighbor(struct ndp_neighbor *n)
369 {
370         setup_route(&n->addr, n->iface, false);
371         list_del(&n->head);
372         free(n);
373         --neighbor_count;
374 }
375
376 static struct ndp_neighbor* find_neighbor(struct in6_addr *addr, bool strict)
377 {
378         time_t now = time(NULL);
379         struct ndp_neighbor *n, *e;
380         list_for_each_entry_safe(n, e, &neighbors, head) {
381                 if ((!strict && !odhcpd_bmemcmp(&n->addr, addr, n->len)) ||
382                                 (n->len == 128 && IN6_ARE_ADDR_EQUAL(&n->addr, addr)))
383                         return n;
384
385                 if (!n->iface && abs(n->timeout - now) >= 5)
386                         free_neighbor(n);
387         }
388         return NULL;
389 }
390
391
392 // Modified our own neighbor-entries
393 static void modify_neighbor(struct in6_addr *addr,
394                 struct interface *iface, bool add)
395 {
396         if (!addr || (void*)addr == (void*)iface)
397                 return;
398
399         struct ndp_neighbor *n = find_neighbor(addr, true);
400         if (!add) { // Delete action
401                 if (n && (!n->iface || n->iface == iface))
402                         free_neighbor(n);
403         } else if (!n) { // No entry yet, add one if possible
404                 if (neighbor_count >= NDP_MAX_NEIGHBORS ||
405                                 !(n = malloc(sizeof(*n))))
406                         return;
407
408                 n->len = 128;
409                 n->addr = *addr;
410                 n->iface = iface;
411                 if (!n->iface)
412                         time(&n->timeout);
413                 list_add(&n->head, &neighbors);
414                 ++neighbor_count;
415                 setup_route(addr, n->iface, add);
416         } else if (n->iface == iface) {
417                 if (!n->iface)
418                         time(&n->timeout);
419         } else if (iface && (!n->iface ||
420                         (!iface->external && n->iface->external))) {
421                 setup_route(addr, n->iface, false);
422                 n->iface = iface;
423                 setup_route(addr, n->iface, add);
424         }
425         // TODO: In case a host switches interfaces we might want
426         // to set its old neighbor entry to NUD_STALE and ping it
427         // on the old interface to confirm if the MACs match.
428 }
429
430
431 // Handler for neighbor cache entries from the kernel. This is our source
432 // to learn and unlearn hosts on interfaces.
433 static void handle_rtnetlink(_unused void *addr, void *data, size_t len,
434                 _unused struct interface *iface)
435 {
436         for (struct nlmsghdr *nh = data; NLMSG_OK(nh, len);
437                         nh = NLMSG_NEXT(nh, len)) {
438                 struct rtmsg *rtm = NLMSG_DATA(nh);
439                 if ((nh->nlmsg_type == RTM_NEWROUTE ||
440                                 nh->nlmsg_type == RTM_DELROUTE) &&
441                                 rtm->rtm_dst_len == 0)
442                         raise(SIGUSR1); // Inform about a change in default route
443
444                 struct ndmsg *ndm = NLMSG_DATA(nh);
445                 struct ifaddrmsg *ifa = NLMSG_DATA(nh);
446                 if (nh->nlmsg_type != RTM_NEWNEIGH
447                                 && nh->nlmsg_type != RTM_DELNEIGH
448                                 && nh->nlmsg_type != RTM_NEWADDR
449                                 && nh->nlmsg_type != RTM_DELADDR)
450                         continue; // Unrelated message type
451                 bool is_addr = (nh->nlmsg_type == RTM_NEWADDR
452                                 || nh->nlmsg_type == RTM_DELADDR);
453
454                 // Family and ifindex are on the same offset for NEIGH and ADDR
455                 if (NLMSG_PAYLOAD(nh, 0) < sizeof(*ndm)
456                                 || ndm->ndm_family != AF_INET6)
457                         continue; //
458
459                 // Lookup interface
460                 struct interface *iface;
461                 if (!(iface = odhcpd_get_interface_by_index(ndm->ndm_ifindex)))
462                         continue;
463
464                 // Data to retrieve
465                 size_t rta_offset = (is_addr) ? sizeof(*ifa) : sizeof(*ndm);
466                 uint16_t atype = (is_addr) ? IFA_ADDRESS : NDA_DST;
467                 ssize_t alen = NLMSG_PAYLOAD(nh, rta_offset);
468                 struct in6_addr *addr = NULL;
469
470                 for (struct rtattr *rta = (void*)(((uint8_t*)ndm) + rta_offset);
471                                 RTA_OK(rta, alen); rta = RTA_NEXT(rta, alen))
472                         if (rta->rta_type == atype &&
473                                         RTA_PAYLOAD(rta) >= sizeof(*addr))
474                                 addr = RTA_DATA(rta);
475
476                 // Address not specified or unrelated
477                 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
478                                 IN6_IS_ADDR_MULTICAST(addr))
479                         continue;
480
481                 // Check for states
482                 bool add;
483                 if (is_addr)
484                         add = (nh->nlmsg_type == RTM_NEWADDR);
485                 else
486                         add = (nh->nlmsg_type == RTM_NEWNEIGH && (ndm->ndm_state &
487                                 (NUD_REACHABLE | NUD_STALE | NUD_DELAY | NUD_PROBE
488                                                 | NUD_PERMANENT | NUD_NOARP)));
489
490                 if (iface->ndp == RELAYD_RELAY)
491                         modify_neighbor(addr, iface, add);
492
493                 if (is_addr && iface->ra == RELAYD_SERVER)
494                         raise(SIGUSR1); // Inform about a change in addresses
495
496                 if (is_addr && iface->dhcpv6 == RELAYD_SERVER)
497                         iface->ia_reconf = true;
498
499                 if (iface->ndp == RELAYD_RELAY && is_addr && iface->master) {
500                         // Replay address changes on all slave interfaces
501                         nh->nlmsg_flags = NLM_F_REQUEST;
502
503                         if (nh->nlmsg_type == RTM_NEWADDR)
504                                 nh->nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
505
506                         struct interface *c;
507                         list_for_each_entry(c, &interfaces, head) {
508                                 if (c->ndp == RELAYD_RELAY && !c->master) {
509                                         ifa->ifa_index = c->ifindex;
510                                         send(rtnl_event.uloop.fd, nh, nh->nlmsg_len, MSG_DONTWAIT);
511                                 }
512                         }
513                 }
514
515                 /* TODO: See if this is required for optimal operation
516                 // Keep neighbor entries alive so we don't loose routes
517                  */
518                 if (add && (ndm->ndm_state & NUD_STALE))
519                         ping6(addr, iface);
520         }
521 }