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