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