3ba552daffa6246154abdcfe5e91bdf0a94cf835
[project/odhcpd.git] / src / router.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 <errno.h>
16 #include <fcntl.h>
17 #include <signal.h>
18 #include <resolv.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdbool.h>
23 #include <net/route.h>
24
25 #include "router.h"
26 #include "odhcpd.h"
27
28
29 static void forward_router_solicitation(const struct interface *iface);
30 static void forward_router_advertisement(uint8_t *data, size_t len);
31
32 static void handle_icmpv6(void *addr, void *data, size_t len,
33                 struct interface *iface);
34 static void send_router_advert(struct uloop_timeout *event);
35 static void sigusr1_refresh(int signal);
36
37 static struct odhcpd_event router_event = {{.fd = -1}, handle_icmpv6};
38
39 static FILE *fp_route = NULL;
40
41
42 int init_router(void)
43 {
44         // Open ICMPv6 socket
45         int sock = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
46         if (sock < 0 && errno != EAFNOSUPPORT) {
47                 syslog(LOG_ERR, "Failed to open RAW-socket: %s", strerror(errno));
48                 return -1;
49         }
50
51         // Let the kernel compute our checksums
52         int val = 2;
53         setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
54
55         // This is required by RFC 4861
56         val = 255;
57         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
58         setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
59
60         // We need to know the source interface
61         val = 1;
62         setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
63         setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val));
64
65         // Don't loop back
66         val = 0;
67         setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, sizeof(val));
68
69         // Filter ICMPv6 package types
70         struct icmp6_filter filt;
71         ICMP6_FILTER_SETBLOCKALL(&filt);
72         ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
73         ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &filt);
74         setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt));
75
76         // Register socket
77         router_event.uloop.fd = sock;
78         odhcpd_register(&router_event);
79
80         if (!(fp_route = fopen("/proc/net/ipv6_route", "r")))
81                 syslog(LOG_ERR, "Failed to open routing table: %s",
82                                 strerror(errno));
83
84         signal(SIGUSR1, sigusr1_refresh);
85         return 0;
86 }
87
88
89 int setup_router_interface(struct interface *iface, bool enable)
90 {
91         struct ipv6_mreq all_nodes = {ALL_IPV6_NODES, iface->ifindex};
92         struct ipv6_mreq all_routers = {ALL_IPV6_ROUTERS, iface->ifindex};
93
94         uloop_timeout_cancel(&iface->timer_rs);
95         iface->timer_rs.cb = NULL;
96
97         setsockopt(router_event.uloop.fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP,
98                         &all_nodes, sizeof(all_nodes));
99         setsockopt(router_event.uloop.fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP,
100                         &all_routers, sizeof(all_routers));
101
102         if (!enable) {
103                 if (iface->ra)
104                         send_router_advert(&iface->timer_rs);
105         } else {
106                 void *mreq = &all_routers;
107
108                 if (iface->ra == RELAYD_RELAY && iface->master) {
109                         mreq = &all_nodes;
110                         forward_router_solicitation(iface);
111                 } else if (iface->ra == RELAYD_SERVER && !iface->master) {
112                         iface->timer_rs.cb = send_router_advert;
113                         send_router_advert(&iface->timer_rs);
114                 }
115
116                 if (iface->ra == RELAYD_RELAY || (iface->ra == RELAYD_SERVER && !iface->master))
117                         setsockopt(router_event.uloop.fd, IPPROTO_IPV6,
118                                         IPV6_ADD_MEMBERSHIP, mreq, sizeof(all_nodes));
119         }
120         return 0;
121 }
122
123
124 // Signal handler to resend all RDs
125 static void sigusr1_refresh(_unused int signal)
126 {
127         struct interface *iface;
128         list_for_each_entry(iface, &interfaces, head)
129                 if (iface->ra == RELAYD_SERVER && !iface->master)
130                         uloop_timeout_set(&iface->timer_rs, 1000);
131 }
132
133 static bool router_icmpv6_valid(struct sockaddr_in6 *source, uint8_t *data, size_t len)
134 {
135         struct icmp6_hdr *hdr = (struct icmp6_hdr *)data;
136         struct icmpv6_opt *opt, *end = (struct icmpv6_opt*)&data[len];
137
138         /* Hoplimit is already checked in odhcpd_receive_packets */
139         if (len < sizeof(*hdr) || hdr->icmp6_code)
140                 return false;
141
142         switch (hdr->icmp6_type) {
143         case ND_ROUTER_ADVERT:
144                 if (!IN6_IS_ADDR_LINKLOCAL(&source->sin6_addr))
145                         return false;
146
147                 opt = (struct icmpv6_opt *)((struct nd_router_advert *)data + 1);
148                 break;
149
150         case ND_ROUTER_SOLICIT:
151                 opt = (struct icmpv6_opt *)((struct nd_router_solicit *)data + 1);
152                 break;
153
154         default:
155                 return false;
156         }
157
158         icmpv6_for_each_option(opt, opt, end)
159                 if (opt->type == ND_OPT_SOURCE_LINKADDR &&
160                                 IN6_IS_ADDR_UNSPECIFIED(&source->sin6_addr) &&
161                                 hdr->icmp6_type == ND_ROUTER_SOLICIT)
162                         return false;
163
164         // Check all options parsed successfully
165         return opt == end;
166 }
167
168 // Event handler for incoming ICMPv6 packets
169 static void handle_icmpv6(void *addr, void *data, size_t len,
170                 struct interface *iface)
171 {
172         struct icmp6_hdr *hdr = data;
173
174         if (!router_icmpv6_valid(addr, data, len))
175                 return;
176
177         if ((iface->ra == RELAYD_SERVER && !iface->master)) { // Server mode
178                 if (hdr->icmp6_type == ND_ROUTER_SOLICIT)
179                         send_router_advert(&iface->timer_rs);
180         } else if (iface->ra == RELAYD_RELAY) { // Relay mode
181                 if (hdr->icmp6_type == ND_ROUTER_ADVERT && iface->master)
182                         forward_router_advertisement(data, len);
183                 else if (hdr->icmp6_type == ND_ROUTER_SOLICIT && !iface->master)
184                         forward_router_solicitation(odhcpd_get_master_interface());
185         }
186 }
187
188
189 // Detect whether a default route exists, also find the source prefixes
190 static bool parse_routes(struct odhcpd_ipaddr *n, ssize_t len)
191 {
192         rewind(fp_route);
193
194         char line[512], ifname[16];
195         bool found_default = false;
196         struct odhcpd_ipaddr p = {IN6ADDR_ANY_INIT, 0, 0, false, 0, 0, 0};
197         while (fgets(line, sizeof(line), fp_route)) {
198                 uint32_t rflags;
199                 if (sscanf(line, "00000000000000000000000000000000 00 "
200                                 "%*s %*s %*s %*s %*s %*s %*s %15s", ifname) &&
201                                 strcmp(ifname, "lo")) {
202                         found_default = true;
203                 } else if (sscanf(line, "%8" SCNx32 "%8" SCNx32 "%*8" SCNx32 "%*8" SCNx32 " %hhx %*s "
204                                 "%*s 00000000000000000000000000000000 %*s %*s %*s %" SCNx32 " lo",
205                                 &p.addr.s6_addr32[0], &p.addr.s6_addr32[1], &p.prefix, &rflags) &&
206                                 p.prefix > 0 && (rflags & RTF_NONEXTHOP) && (rflags & RTF_REJECT)) {
207                         // Find source prefixes by scanning through unreachable-routes
208                         p.addr.s6_addr32[0] = htonl(p.addr.s6_addr32[0]);
209                         p.addr.s6_addr32[1] = htonl(p.addr.s6_addr32[1]);
210
211                         for (ssize_t i = 0; i < len; ++i) {
212                                 if (n[i].prefix <= 64 && n[i].prefix >= p.prefix &&
213                                                 !odhcpd_bmemcmp(&p.addr, &n[i].addr, p.prefix)) {
214                                         n[i].dprefix = p.prefix;
215                                         break;
216                                 }
217                         }
218
219                 }
220         }
221
222         return found_default;
223 }
224
225
226 // Router Advert server mode
227 static void send_router_advert(struct uloop_timeout *event)
228 {
229         struct interface *iface =
230                         container_of(event, struct interface, timer_rs);
231
232         int mtu = odhcpd_get_interface_mtu(iface->ifname);
233         if (mtu < 0)
234                 mtu = 1500;
235
236         struct {
237                 struct nd_router_advert h;
238                 struct icmpv6_opt lladdr;
239                 struct nd_opt_mtu mtu;
240                 struct nd_opt_prefix_info prefix[RELAYD_MAX_PREFIXES];
241         } adv = {
242                 .h = {{.icmp6_type = ND_ROUTER_ADVERT, .icmp6_code = 0}, 0, 0},
243                 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
244                 .mtu = {ND_OPT_MTU, 1, 0, htonl(mtu)},
245         };
246
247         if (iface->dhcpv6)
248                 adv.h.nd_ra_flags_reserved = ND_RA_FLAG_OTHER;
249
250         if (iface->managed >= RELAYD_MANAGED_MFLAG)
251                 adv.h.nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
252
253         if (iface->route_preference < 0)
254                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_LOW;
255         else if (iface->route_preference > 0)
256                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_HIGH;
257         odhcpd_get_mac(iface, adv.lladdr.data);
258
259         // If not currently shutting down
260         struct odhcpd_ipaddr addrs[RELAYD_MAX_PREFIXES];
261         ssize_t ipcnt = 0;
262         uint64_t maxpreferred = 0;
263
264         // If not shutdown
265         if (event->cb) {
266                 ipcnt = odhcpd_get_interface_addresses(iface->ifindex,
267                                 addrs, ARRAY_SIZE(addrs));
268
269                 // Check default route
270                 if (parse_routes(addrs, ipcnt) || iface->default_router > 1)
271                         adv.h.nd_ra_router_lifetime =
272                                         htons(3 * MaxRtrAdvInterval);
273         }
274
275         // Construct Prefix Information options
276         bool have_public = false;
277         size_t cnt = 0;
278
279         struct in6_addr dns_pref = IN6ADDR_ANY_INIT, *dns_addr = &dns_pref;
280         uint32_t dns_time = 0;
281         size_t dns_cnt = 1;
282
283         for (ssize_t i = 0; i < ipcnt; ++i) {
284                 struct odhcpd_ipaddr *addr = &addrs[i];
285                 if (addr->prefix > 96 || addr->has_class)
286                         continue; // Address not suitable
287
288                 if (addr->preferred > MaxPreferredTime)
289                         addr->preferred = MaxPreferredTime;
290
291                 if (addr->valid > MaxValidTime)
292                         addr->valid = MaxValidTime;
293
294                 struct nd_opt_prefix_info *p = NULL;
295                 for (size_t i = 0; i < cnt; ++i) {
296                         if (addr->prefix == adv.prefix[i].nd_opt_pi_prefix_len &&
297                                         !odhcpd_bmemcmp(&adv.prefix[i].nd_opt_pi_prefix,
298                                         &addr->addr, addr->prefix))
299                                 p = &adv.prefix[i];
300                 }
301
302                 if (!p) {
303                         if (cnt >= ARRAY_SIZE(adv.prefix))
304                                 break;
305
306                         p = &adv.prefix[cnt++];
307                 }
308
309                 if ((addr->addr.s6_addr[0] & 0xfe) != 0xfc && addr->preferred > 0) {
310                         have_public = true;
311
312                         if (maxpreferred < 1000 * addr->preferred)
313                                 maxpreferred = 1000 * addr->preferred;
314                 }
315
316                 odhcpd_bmemcpy(&p->nd_opt_pi_prefix, &addr->addr, addr->prefix);
317                 p->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
318                 p->nd_opt_pi_len = 4;
319                 p->nd_opt_pi_prefix_len = (addr->prefix < 64) ? 64 : addr->prefix;
320                 p->nd_opt_pi_flags_reserved = 0;
321                 if (!iface->ra_not_onlink)
322                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
323                 if (iface->managed < RELAYD_MANAGED_NO_AFLAG && addr->prefix <= 64)
324                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
325                 p->nd_opt_pi_valid_time = htonl(addr->valid);
326                 p->nd_opt_pi_preferred_time = htonl(addr->preferred);
327
328                 if (addr->preferred > dns_time) {
329                         dns_time = addr->preferred;
330                         dns_pref = addr->addr;
331                 }
332         }
333
334         if (!have_public && !iface->default_router && adv.h.nd_ra_router_lifetime) {
335                 syslog(LOG_WARNING, "A default route is present but there is no public prefix "
336                                 "on %s thus we don't announce a default route!", iface->ifname);
337                 adv.h.nd_ra_router_lifetime = 0;
338         }
339
340         // DNS Recursive DNS
341         if (iface->dns_cnt > 0) {
342                 dns_addr = iface->dns;
343                 dns_cnt = iface->dns_cnt;
344                 dns_time = 2 * MaxRtrAdvInterval;
345         }
346
347         if (!dns_addr || IN6_IS_ADDR_UNSPECIFIED(dns_addr))
348                 dns_cnt = 0;
349
350         struct {
351                 uint8_t type;
352                 uint8_t len;
353                 uint8_t pad;
354                 uint8_t pad2;
355                 uint32_t lifetime;
356         } dns = {ND_OPT_RECURSIVE_DNS, (1 + (2 * dns_cnt)), 0, 0, htonl(dns_time)};
357
358
359
360         // DNS Search options
361         uint8_t search_buf[256], *search_domain = iface->search;
362         size_t search_len = iface->search_len, search_padded = 0;
363
364         if (!search_domain && !res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
365                 int len = dn_comp(_res.dnsrch[0], search_buf,
366                                 sizeof(search_buf), NULL, NULL);
367                 if (len > 0) {
368                         search_domain = search_buf;
369                         search_len = len;
370                 }
371         }
372
373         if (search_len > 0)
374                 search_padded = ((search_len + 7) & (~7)) + 8;
375
376         struct {
377                 uint8_t type;
378                 uint8_t len;
379                 uint8_t pad;
380                 uint8_t pad2;
381                 uint32_t lifetime;
382                 uint8_t name[];
383         } *search = alloca(sizeof(*search) + search_padded);
384
385         if (!search) {
386                 syslog(LOG_ERR, "Alloca failed for dns search on interface %s", iface->ifname);
387                 return;
388         }
389         search->type = ND_OPT_DNS_SEARCH;
390         search->len = search_len ? ((sizeof(*search) + search_padded) / 8) : 0;
391         search->pad = 0;
392         search->pad2 = 0;
393         search->lifetime = htonl(2 * MaxRtrAdvInterval);;
394         memcpy(search->name, search_domain, search_len);
395         memset(&search->name[search_len], 0, search_padded - search_len);
396
397
398         size_t routes_cnt = 0;
399         struct {
400                 uint8_t type;
401                 uint8_t len;
402                 uint8_t prefix;
403                 uint8_t flags;
404                 uint32_t lifetime;
405                 uint32_t addr[4];
406         } routes[RELAYD_MAX_PREFIXES];
407
408         for (ssize_t i = 0; i < ipcnt; ++i) {
409                 struct odhcpd_ipaddr *addr = &addrs[i];
410                 if (addr->dprefix > 64 || addr->dprefix == 0) {
411                         continue; // Address not suitable
412                 } else if (addr->dprefix > 32) {
413                         addr->addr.s6_addr32[1] &= htonl(~((1U << (64 - addr->dprefix)) - 1));
414                 } else if (addr->dprefix <= 32) {
415                         addr->addr.s6_addr32[0] &= htonl(~((1U << (32 - addr->dprefix)) - 1));
416                         addr->addr.s6_addr32[1] = 0;
417                 }
418
419                 routes[routes_cnt].type = ND_OPT_ROUTE_INFO;
420                 routes[routes_cnt].len = sizeof(*routes) / 8;
421                 routes[routes_cnt].prefix = addr->dprefix;
422                 routes[routes_cnt].flags = 0;
423                 if (iface->route_preference < 0)
424                         routes[routes_cnt].flags |= ND_RA_PREF_LOW;
425                 else if (iface->route_preference > 0)
426                         routes[routes_cnt].flags |= ND_RA_PREF_HIGH;
427                 routes[routes_cnt].lifetime = htonl(addr->valid);
428                 routes[routes_cnt].addr[0] = addr->addr.s6_addr32[0];
429                 routes[routes_cnt].addr[1] = addr->addr.s6_addr32[1];
430                 routes[routes_cnt].addr[2] = 0;
431                 routes[routes_cnt].addr[3] = 0;
432
433                 ++routes_cnt;
434         }
435
436
437         struct iovec iov[] = {{&adv, (uint8_t*)&adv.prefix[cnt] - (uint8_t*)&adv},
438                         {&routes, routes_cnt * sizeof(*routes)},
439                         {&dns, (dns_cnt) ? sizeof(dns) : 0},
440                         {dns_addr, dns_cnt * sizeof(*dns_addr)},
441                         {search, search->len * 8}};
442         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
443         odhcpd_send(router_event.uloop.fd,
444                         &all_nodes, iov, ARRAY_SIZE(iov), iface);
445
446         // Rearm timer if not shut down
447         if (event->cb) {
448                 uint32_t maxinterval = MaxRtrAdvInterval * 1000;
449                 uint32_t mininterval = MinRtrAdvInterval * 1000;
450
451                 if (maxpreferred > 0 && maxinterval > maxpreferred / 2) {
452                         maxinterval = maxpreferred / 2;
453                         if (maxinterval < 4000)
454                                 maxinterval = 4000;
455
456                         if (maxinterval >= 9000)
457                                 mininterval = maxinterval / 3;
458                         else
459                                 mininterval = (maxinterval * 3) / 4;
460                 }
461
462                 int msecs;
463                 odhcpd_urandom(&msecs, sizeof(msecs));
464                 msecs = (labs(msecs) % (maxinterval - mininterval)) + mininterval;
465                 uloop_timeout_set(&iface->timer_rs, msecs);
466         }
467 }
468
469
470 // Forward router solicitation
471 static void forward_router_solicitation(const struct interface *iface)
472 {
473         if (!iface)
474                 return;
475
476         struct icmp6_hdr rs = {ND_ROUTER_SOLICIT, 0, 0, {{0}}};
477         struct iovec iov = {&rs, sizeof(rs)};
478         struct sockaddr_in6 all_routers =
479                 {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, iface->ifindex};
480
481         syslog(LOG_NOTICE, "Sending RS to %s", iface->ifname);
482         odhcpd_send(router_event.uloop.fd, &all_routers, &iov, 1, iface);
483 }
484
485
486 // Handler for incoming router solicitations on slave interfaces
487 static void forward_router_advertisement(uint8_t *data, size_t len)
488 {
489         struct nd_router_advert *adv = (struct nd_router_advert *)data;
490
491         // Rewrite options
492         uint8_t *end = data + len;
493         uint8_t *mac_ptr = NULL;
494         struct in6_addr *dns_ptr = NULL;
495         size_t dns_count = 0;
496
497         struct icmpv6_opt *opt;
498         icmpv6_for_each_option(opt, &adv[1], end) {
499                 if (opt->type == ND_OPT_SOURCE_LINKADDR) {
500                         // Store address of source MAC-address
501                         mac_ptr = opt->data;
502                 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 1) {
503                         // Check if we have to rewrite DNS
504                         dns_ptr = (struct in6_addr*)&opt->data[6];
505                         dns_count = (opt->len - 1) / 2;
506                 }
507         }
508
509         syslog(LOG_NOTICE, "Got a RA");
510
511         // Indicate a proxy, however we don't follow the rest of RFC 4389 yet
512         adv->nd_ra_flags_reserved |= ND_RA_FLAG_PROXY;
513
514         // Forward advertisement to all slave interfaces
515         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
516         struct iovec iov = {data, len};
517
518         struct odhcpd_ipaddr addr;
519         struct interface *iface;
520         list_for_each_entry(iface, &interfaces, head) {
521                 if (iface->ra != RELAYD_RELAY || iface->master)
522                         continue;
523
524                 // Fixup source hardware address option
525                 if (mac_ptr)
526                         odhcpd_get_mac(iface, mac_ptr);
527
528                 // If we have to rewrite DNS entries
529                 if (iface->always_rewrite_dns && dns_ptr && dns_count > 0) {
530                         const struct in6_addr *rewrite = iface->dns;
531                         size_t rewrite_cnt = iface->dns_cnt;
532
533                         if (rewrite_cnt == 0) {
534                                 if (odhcpd_get_interface_addresses(iface->ifindex, &addr, 1) < 1)
535                                         continue; // Unable to comply
536
537                                 rewrite = &addr.addr;
538                                 rewrite_cnt = 1;
539                         }
540
541                         // Copy over any other addresses
542                         for (size_t i = 0; i < dns_count; ++i) {
543                                 size_t j = (i < rewrite_cnt) ? i : rewrite_cnt - 1;
544                                 dns_ptr[i] = rewrite[j];
545                         }
546                 }
547
548                 odhcpd_send(router_event.uloop.fd, &all_nodes, &iov, 1, iface);
549         }
550 }