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