npd: rework IPv6 relay logic (FS#396)
[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
32 #include <netlink/msg.h>
33 #include <netlink/socket.h>
34 #include <netlink/attr.h>
35
36 #include "router.h"
37 #include "dhcpv6.h"
38 #include "ndp.h"
39
40 struct event_socket {
41         struct odhcpd_event ev;
42         struct nl_sock *sock;
43 };
44
45 static void handle_solicit(void *addr, void *data, size_t len,
46                 struct interface *iface, void *dest);
47 static void handle_rtnl_event(struct odhcpd_event *ev);
48 static int cb_rtnl_valid(struct nl_msg *msg, void *arg);
49 static void catch_rtnetlink(int error);
50
51 static int ping_socket = -1;
52 static struct event_socket rtnl_event = {
53         .ev = {
54                 .uloop = {.fd = - 1, },
55                 .handle_dgram = NULL,
56                 .handle_error = catch_rtnetlink,
57                 .recv_msgs = handle_rtnl_event,
58         },
59         .sock = NULL,
60 };
61
62 // Filter ICMPv6 messages of type neighbor soliciation
63 static struct sock_filter bpf[] = {
64         BPF_STMT(BPF_LD | BPF_B | BPF_ABS, offsetof(struct ip6_hdr, ip6_nxt)),
65         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMPV6, 0, 3),
66         BPF_STMT(BPF_LD | BPF_B | BPF_ABS, sizeof(struct ip6_hdr) +
67                         offsetof(struct icmp6_hdr, icmp6_type)),
68         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ND_NEIGHBOR_SOLICIT, 0, 1),
69         BPF_STMT(BPF_RET | BPF_K, 0xffffffff),
70         BPF_STMT(BPF_RET | BPF_K, 0),
71 };
72 static const struct sock_fprog bpf_prog = {sizeof(bpf) / sizeof(*bpf), bpf};
73
74
75 // Initialize NDP-proxy
76 int init_ndp(void)
77 {
78         int val = 256 * 1024;
79
80         rtnl_event.sock = odhcpd_create_nl_socket(NETLINK_ROUTE);
81         if (!rtnl_event.sock)
82                 goto err;
83
84         rtnl_event.ev.uloop.fd = nl_socket_get_fd(rtnl_event.sock);
85
86         if (nl_socket_set_buffer_size(rtnl_event.sock, val, 0))
87                 goto err;
88
89         nl_socket_disable_seq_check(rtnl_event.sock);
90
91         nl_socket_modify_cb(rtnl_event.sock, NL_CB_VALID, NL_CB_CUSTOM,
92                         cb_rtnl_valid, NULL);
93
94         // Receive IPv6 address, IPv6 routes and neighbor events
95         if (nl_socket_add_memberships(rtnl_event.sock, RTNLGRP_IPV6_IFADDR,
96                                 RTNLGRP_IPV6_ROUTE, RTNLGRP_NEIGH, 0))
97                 goto err;
98
99         odhcpd_register(&rtnl_event.ev);
100
101         // Open ICMPv6 socket
102         ping_socket = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
103         if (ping_socket < 0) {
104                 syslog(LOG_ERR, "Unable to open raw socket: %s", strerror(errno));
105                         return -1;
106         }
107
108         val = 2;
109         setsockopt(ping_socket, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
110
111         // This is required by RFC 4861
112         val = 255;
113         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
114         setsockopt(ping_socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
115
116         // Filter all packages, we only want to send
117         struct icmp6_filter filt;
118         ICMP6_FILTER_SETBLOCKALL(&filt);
119         setsockopt(ping_socket, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
120
121         return 0;
122
123 err:
124         if (rtnl_event.sock) {
125                 nl_socket_free(rtnl_event.sock);
126                 rtnl_event.sock = NULL;
127                 rtnl_event.ev.uloop.fd = -1;
128         }
129
130         return -1;
131 }
132
133 static void dump_neigh_table(const bool proxy)
134 {
135         struct nl_msg *msg;
136         struct ndmsg ndm = {
137                 .ndm_family = AF_INET6,
138                 .ndm_flags = proxy ? NTF_PROXY : 0,
139         };
140
141         msg = nlmsg_alloc_simple(RTM_GETNEIGH, NLM_F_REQUEST | NLM_F_DUMP);
142         if (!msg)
143                 return;
144
145         nlmsg_append(msg, &ndm, sizeof(ndm), 0);
146
147         nl_send_auto_complete(rtnl_event.sock, msg);
148
149         nlmsg_free(msg);
150 }
151
152 static void dump_addr_table(void)
153 {
154         struct nl_msg *msg;
155         struct ifaddrmsg ifa = {
156                 .ifa_family = AF_INET6,
157         };
158
159         msg = nlmsg_alloc_simple(RTM_GETADDR, NLM_F_REQUEST | NLM_F_DUMP);
160         if (!msg)
161                 return;
162
163         nlmsg_append(msg, &ifa, sizeof(ifa), 0);
164
165         nl_send_auto_complete(rtnl_event.sock, msg);
166
167         nlmsg_free(msg);
168 }
169
170 int setup_ndp_interface(struct interface *iface, bool enable)
171 {
172         char procbuf[64];
173         snprintf(procbuf, sizeof(procbuf), "/proc/sys/net/ipv6/conf/%s/proxy_ndp", iface->ifname);
174         int procfd = open(procbuf, O_WRONLY);
175         bool dump_neigh = false;
176
177         if (iface->ndp_event.uloop.fd > 0) {
178                 uloop_fd_delete(&iface->ndp_event.uloop);
179                 close(iface->ndp_event.uloop.fd);
180                 iface->ndp_event.uloop.fd = -1;
181
182                 if (!enable || iface->ndp != RELAYD_RELAY)
183                         if (write(procfd, "0\n", 2) < 0) {}
184
185                 dump_neigh = true;
186         }
187
188         if (enable && (iface->ra == RELAYD_SERVER ||
189                         iface->dhcpv6 == RELAYD_SERVER || iface->ndp == RELAYD_RELAY))
190                 dump_addr_table();
191
192         if (enable && iface->ndp == RELAYD_RELAY) {
193                 if (write(procfd, "1\n", 2) < 0) {}
194                 close(procfd);
195
196                 int sock = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC, htons(ETH_P_IPV6));
197                 if (sock < 0) {
198                         syslog(LOG_ERR, "Unable to open packet socket: %s",
199                                         strerror(errno));
200                         return -1;
201                 }
202
203 #ifdef PACKET_RECV_TYPE
204                 int pktt = 1 << PACKET_MULTICAST;
205                 setsockopt(sock, SOL_PACKET, PACKET_RECV_TYPE, &pktt, sizeof(pktt));
206 #endif
207
208                 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER,
209                                 &bpf_prog, sizeof(bpf_prog))) {
210                         syslog(LOG_ERR, "Failed to set BPF: %s", strerror(errno));
211                         return -1;
212                 }
213
214                 struct sockaddr_ll ll = {
215                         .sll_family = AF_PACKET,
216                         .sll_ifindex = iface->ifindex,
217                         .sll_protocol = htons(ETH_P_IPV6),
218                         .sll_hatype = 0,
219                         .sll_pkttype = 0,
220                         .sll_halen = 0,
221                         .sll_addr = {0},
222                 };
223                 bind(sock, (struct sockaddr*)&ll, sizeof(ll));
224
225                 struct packet_mreq mreq = {iface->ifindex, PACKET_MR_ALLMULTI, ETH_ALEN, {0}};
226                 setsockopt(sock, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
227
228                 iface->ndp_event.uloop.fd = sock;
229                 iface->ndp_event.handle_dgram = handle_solicit;
230                 odhcpd_register(&iface->ndp_event);
231
232                 // If we already were enabled dump is unnecessary, if not do dump
233                 if (!dump_neigh)
234                         dump_neigh_table(false);
235                 else
236                         dump_neigh = false;
237         } else
238                 close(procfd);
239
240         if (dump_neigh)
241                 dump_neigh_table(true);
242
243         return 0;
244 }
245
246
247 // Send an ICMP-ECHO. This is less for actually pinging but for the
248 // neighbor cache to be kept up-to-date.
249 static void ping6(struct in6_addr *addr,
250                 const struct interface *iface)
251 {
252         struct sockaddr_in6 dest = { .sin6_family = AF_INET6, .sin6_addr = *addr, .sin6_scope_id = iface->ifindex, };
253         struct icmp6_hdr echo = { .icmp6_type = ICMP6_ECHO_REQUEST };
254         struct iovec iov = { .iov_base = &echo, .iov_len = sizeof(echo) };
255
256         odhcpd_setup_route(addr, 128, iface, NULL, 128, true);
257         odhcpd_send(ping_socket, &dest, &iov, 1, iface);
258         odhcpd_setup_route(addr, 128, iface, NULL, 128, false);
259 }
260
261
262 // Handle solicitations
263 static void handle_solicit(void *addr, void *data, size_t len,
264                 struct interface *iface, _unused void *dest)
265 {
266         struct ip6_hdr *ip6 = data;
267         struct nd_neighbor_solicit *req = (struct nd_neighbor_solicit*)&ip6[1];
268         struct sockaddr_ll *ll = addr;
269
270         // Solicitation is for duplicate address detection
271         bool ns_is_dad = IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src);
272
273         // Don't process solicit messages on non relay interfaces
274         // Don't forward any non-DAD solicitation for external ifaces
275         // TODO: check if we should even forward DADs for them
276         if (iface->ndp != RELAYD_RELAY || (iface->external && !ns_is_dad))
277                 return;
278
279         if (len < sizeof(*ip6) + sizeof(*req))
280                 return; // Invalid reqicitation
281
282         if (IN6_IS_ADDR_LINKLOCAL(&req->nd_ns_target) ||
283                         IN6_IS_ADDR_LOOPBACK(&req->nd_ns_target) ||
284                         IN6_IS_ADDR_MULTICAST(&req->nd_ns_target))
285                 return; // Invalid target
286
287         char ipbuf[INET6_ADDRSTRLEN];
288         inet_ntop(AF_INET6, &req->nd_ns_target, ipbuf, sizeof(ipbuf));
289         syslog(LOG_DEBUG, "Got a NS for %s", ipbuf);
290
291         uint8_t mac[6];
292         odhcpd_get_mac(iface, mac);
293         if (!memcmp(ll->sll_addr, mac, sizeof(mac)))
294                 return; // Looped back
295
296         struct interface *c;
297         list_for_each_entry(c, &interfaces, head)
298                 if (iface != c && c->ndp == RELAYD_RELAY &&
299                                 (ns_is_dad || !c->external))
300                         ping6(&req->nd_ns_target, c);
301 }
302
303 // Use rtnetlink to modify kernel routes
304 static void setup_route(struct in6_addr *addr, struct interface *iface, bool add)
305 {
306         char namebuf[INET6_ADDRSTRLEN];
307         inet_ntop(AF_INET6, addr, namebuf, sizeof(namebuf));
308         syslog(LOG_NOTICE, "%s about %s on %s",
309                         (add) ? "Learned" : "Forgot", namebuf, iface->ifname);
310
311         if (iface->learn_routes)
312                 odhcpd_setup_route(addr, 128, iface, NULL, 1024, add);
313 }
314
315 // compare prefixes
316 static int prefixcmp(const void *va, const void *vb)
317 {
318         const struct odhcpd_ipaddr *a = va, *b = vb;
319         uint32_t a_pref = ((a->addr.s6_addr[0] & 0xfe) != 0xfc) ? a->preferred : 1;
320         uint32_t b_pref = ((b->addr.s6_addr[0] & 0xfe) != 0xfc) ? b->preferred : 1;
321         return (a_pref < b_pref) ? 1 : (a_pref > b_pref) ? -1 : 0;
322 }
323
324 // Check address update
325 static void check_addr_updates(struct interface *iface)
326 {
327         struct odhcpd_ipaddr addr[RELAYD_MAX_ADDRS] = {{IN6ADDR_ANY_INIT, 0, 0, 0, 0}};
328         time_t now = odhcpd_time();
329         ssize_t len = odhcpd_get_interface_addresses(iface->ifindex, addr, ARRAY_SIZE(addr));
330
331         if (len < 0)
332                 return;
333
334         qsort(addr, len, sizeof(*addr), prefixcmp);
335
336         for (int i = 0; i < len; ++i) {
337                 addr[i].addr.s6_addr32[3] = 0;
338
339                 if (addr[i].preferred < UINT32_MAX - now)
340                         addr[i].preferred += now;
341
342                 if (addr[i].valid < UINT32_MAX - now)
343                         addr[i].valid += now;
344         }
345
346         bool change = len != (ssize_t)iface->ia_addr_len;
347         for (ssize_t i = 0; !change && i < len; ++i)
348                 if (!IN6_ARE_ADDR_EQUAL(&addr[i].addr, &iface->ia_addr[i].addr) ||
349                                 (addr[i].preferred > 0) != (iface->ia_addr[i].preferred > 0) ||
350                                 addr[i].valid < iface->ia_addr[i].valid ||
351                                 addr[i].preferred < iface->ia_addr[i].preferred)
352                         change = true;
353
354         if (change)
355                 dhcpv6_ia_preupdate(iface);
356
357         memcpy(iface->ia_addr, addr, len * sizeof(*addr));
358         iface->ia_addr_len = len;
359
360         if (change)
361                 dhcpv6_ia_postupdate(iface, now);
362
363         if (change) {
364                 syslog(LOG_INFO, "Raising SIGUSR1 due to address change on %s", iface->ifname);
365                 raise(SIGUSR1);
366         }
367 }
368
369 void setup_addr_for_relaying(struct in6_addr *addr, struct interface *iface, bool add)
370 {
371         struct interface *c;
372
373         list_for_each_entry(c, &interfaces, head) {
374                 if (iface == c || (c->ndp != RELAYD_RELAY && !add))
375                         continue;
376
377                 odhcpd_setup_proxy_neigh(addr, c, c->ndp == RELAYD_RELAY ? add : false);
378         }
379 }
380
381 void setup_ping6(struct in6_addr *addr, struct interface *iface)
382 {
383         struct interface *c;
384
385         list_for_each_entry(c, &interfaces, head) {
386                 if (iface == c || c->ndp != RELAYD_RELAY ||
387                                 c->external == true)
388                         continue;
389
390                 ping6(addr, c);
391         }
392 }
393
394 static struct in6_addr last_solicited;
395
396 static void handle_rtnl_event(struct odhcpd_event *e)
397 {
398         struct event_socket *ev_sock = container_of(e, struct event_socket, ev);
399
400         nl_recvmsgs_default(ev_sock->sock);
401 }
402
403
404 // Handler for neighbor cache entries from the kernel. This is our source
405 // to learn and unlearn hosts on interfaces.
406 static int cb_rtnl_valid(struct nl_msg *msg, _unused void *arg)
407 {
408         struct nlmsghdr *hdr = nlmsg_hdr(msg);
409         struct in6_addr *addr = NULL;
410         struct interface *iface = NULL;
411         bool add = false;
412
413         switch (hdr->nlmsg_type) {
414         case RTM_NEWROUTE:
415         case RTM_DELROUTE: {
416                 struct rtmsg *rtm = nlmsg_data(hdr);
417
418                 if (!nlmsg_valid_hdr(hdr, sizeof(*rtm)) ||
419                                 rtm->rtm_family != AF_INET6)
420                         return NL_SKIP;
421
422                 if (rtm->rtm_dst_len == 0) {
423                         syslog(LOG_INFO, "Raising SIGUSR1 due to default route change");
424                         raise(SIGUSR1);
425                 }
426                 return NL_OK;
427         }
428
429         case RTM_NEWADDR:
430                 add = true;
431         case RTM_DELADDR: {
432                 struct ifaddrmsg *ifa = nlmsg_data(hdr);
433                 struct nlattr *nla[__IFA_MAX];
434
435                 if (!nlmsg_valid_hdr(hdr, sizeof(*ifa)) ||
436                                 ifa->ifa_family != AF_INET6)
437                         return NL_SKIP;
438
439                 iface = odhcpd_get_interface_by_index(ifa->ifa_index);
440                 if (!iface)
441                         return NL_SKIP;
442
443                 nlmsg_parse(hdr, sizeof(*ifa), nla, __IFA_MAX - 1, NULL);
444                 if (!nla[IFA_ADDRESS])
445                         return NL_SKIP;
446
447                 addr = nla_data(nla[IFA_ADDRESS]);
448                 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
449                                 IN6_IS_ADDR_MULTICAST(addr))
450                         return NL_SKIP;
451
452                 check_addr_updates(iface);
453
454                 if (iface->ndp != RELAYD_RELAY)
455                         break;
456
457                 /* handle the relay logic below */
458                 setup_addr_for_relaying(addr, iface, add);
459
460                 if (!add)
461                         dump_neigh_table(false);
462                 break;
463         }
464
465         case RTM_NEWNEIGH:
466                 add = true;
467         case RTM_DELNEIGH: {
468                 struct ndmsg *ndm = nlmsg_data(hdr);
469                 struct nlattr *nla[__NDA_MAX];
470
471                 if (!nlmsg_valid_hdr(hdr, sizeof(*ndm)) ||
472                                 ndm->ndm_family != AF_INET6)
473                         return NL_SKIP;
474
475                 iface = odhcpd_get_interface_by_index(ndm->ndm_ifindex);
476                 if (!iface || iface->ndp != RELAYD_RELAY)
477                         return (iface ? NL_OK : NL_SKIP);
478
479                 nlmsg_parse(hdr, sizeof(*ndm), nla, __NDA_MAX - 1, NULL);
480                 if (!nla[NDA_DST])
481                         return NL_SKIP;
482
483                 addr = nla_data(nla[NDA_DST]);
484                 if (!addr || IN6_IS_ADDR_LINKLOCAL(addr) ||
485                                 IN6_IS_ADDR_MULTICAST(addr))
486                         return NL_SKIP;
487
488                 if (ndm->ndm_flags & NTF_PROXY) {
489                         /* Dump and flush proxy entries */
490                         if (hdr->nlmsg_type == RTM_NEWNEIGH) {
491                                 odhcpd_setup_proxy_neigh(addr, iface, false);
492                                 setup_route(addr, iface, false);
493                                 dump_neigh_table(false);
494                         }
495
496                         return NL_OK;
497                 }
498
499                 if (add && !(ndm->ndm_state &
500                                 (NUD_REACHABLE | NUD_STALE | NUD_DELAY | NUD_PROBE |
501                                  NUD_PERMANENT | NUD_NOARP))) {
502                         if (!IN6_ARE_ADDR_EQUAL(&last_solicited, addr)) {
503                                 last_solicited = *addr;
504                                 setup_ping6(addr, iface);
505                         }
506
507                         return NL_OK;
508                 }
509
510                 setup_addr_for_relaying(addr, iface, add);
511                 setup_route(addr, iface, add);
512
513                 if (!add)
514                         dump_neigh_table(false);
515                 break;
516         }
517
518         default:
519                 return NL_SKIP;
520         }
521
522         return NL_OK;
523 }
524
525 static void catch_rtnetlink(int error)
526 {
527         if (error == ENOBUFS)
528                 dump_addr_table();
529 }