a213c84739778e43db0dd670937ff49cc5d17189
[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 int 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;
137         size_t optlen = len - sizeof(*hdr);
138
139         /* Hoplimit is already checked in odhcpd_receive_packets */
140         if (len < sizeof(*hdr))
141                 return 0;
142
143         if (hdr->icmp6_code)
144                 return 0;
145
146         switch (hdr->icmp6_type) {
147         case ND_ROUTER_ADVERT:
148                 if (!IN6_IS_ADDR_LINKLOCAL(&source->sin6_addr))
149                         return 0;
150
151                 opt = (struct icmpv6_opt *)((struct nd_router_advert *)data + 1);
152                 break;
153
154         case ND_ROUTER_SOLICIT:
155                 opt = (struct icmpv6_opt *)((struct nd_router_solicit *)data + 1);
156                 break;
157
158         default:
159                 return 0;
160         }
161
162         while (optlen > 0) {
163                 size_t l = opt->len << 3;
164
165                 if (optlen < sizeof(*opt))
166                         return 0;
167
168                 if (l > optlen || l == 0)
169                         return 0;
170
171                 if (opt->type == ND_OPT_SOURCE_LINKADDR && IN6_IS_ADDR_UNSPECIFIED(&source->sin6_addr) &&
172                         hdr->icmp6_type == ND_ROUTER_SOLICIT) {
173                         return 0;
174                 }
175
176                 opt = (struct icmpv6_opt *)(((uint8_t *)opt) + l);
177
178                 optlen -= l;
179         }
180
181         return 1;
182 }
183
184 // Event handler for incoming ICMPv6 packets
185 static void handle_icmpv6(void *addr, void *data, size_t len,
186                 struct interface *iface)
187 {
188         struct icmp6_hdr *hdr = data;
189         
190         if (!router_icmpv6_valid(addr, data, len))
191                 return;
192
193         if ((iface->ra == RELAYD_SERVER && !iface->master)) { // Server mode
194                 if (hdr->icmp6_type == ND_ROUTER_SOLICIT)
195                         send_router_advert(&iface->timer_rs);
196         } else if (iface->ra == RELAYD_RELAY) { // Relay mode
197                 if (hdr->icmp6_type == ND_ROUTER_ADVERT && iface->master)
198                         forward_router_advertisement(data, len);
199                 else if (hdr->icmp6_type == ND_ROUTER_SOLICIT && !iface->master)
200                         forward_router_solicitation(odhcpd_get_master_interface());
201         }
202 }
203
204
205 static bool match_route(const struct odhcpd_ipaddr *n, const struct in6_addr *addr)
206 {
207         if (n->prefix <= 32)
208                 return ntohl(n->addr.s6_addr32[0]) >> (32 - n->prefix) ==
209                                 ntohl(addr->s6_addr32[0]) >> (32 - n->prefix);
210
211         if (n->addr.s6_addr32[0] != addr->s6_addr32[0])
212                 return false;
213
214         return ntohl(n->addr.s6_addr32[1]) >> (64 - n->prefix) ==
215                         ntohl(addr->s6_addr32[1]) >> (64 - n->prefix);
216 }
217
218
219 // Detect whether a default route exists, also find the source prefixes
220 static bool parse_routes(struct odhcpd_ipaddr *n, ssize_t len)
221 {
222         rewind(fp_route);
223
224         char line[512], ifname[16];
225         bool found_default = false;
226         struct odhcpd_ipaddr p = {IN6ADDR_ANY_INIT, 0, false, 0, 0, 0};
227         while (fgets(line, sizeof(line), fp_route)) {
228                 uint32_t rflags;
229                 if (sscanf(line, "00000000000000000000000000000000 00 "
230                                 "%*s %*s %*s %*s %*s %*s %*s %15s", ifname) &&
231                                 strcmp(ifname, "lo")) {
232                         found_default = true;
233                 } else if (sscanf(line, "%8" SCNx32 "%8" SCNx32 "%*8" SCNx32 "%*8" SCNx32 " %hhx %*s "
234                                 "%*s 00000000000000000000000000000000 %*s %*s %*s %" SCNx32 " lo",
235                                 &p.addr.s6_addr32[0], &p.addr.s6_addr32[1], &p.prefix, &rflags) &&
236                                 p.prefix > 0 && (rflags & RTF_NONEXTHOP) && (rflags & RTF_REJECT)) {
237                         // Find source prefixes by scanning through unreachable-routes
238                         p.addr.s6_addr32[0] = htonl(p.addr.s6_addr32[0]);
239                         p.addr.s6_addr32[1] = htonl(p.addr.s6_addr32[1]);
240
241                         for (ssize_t i = 0; i < len; ++i) {
242                                 if (n[i].prefix <= 64 && n[i].prefix >= p.prefix &&
243                                                 match_route(&p, &n[i].addr)) {
244                                         n[i].prefix = p.prefix;
245                                         break;
246                                 }
247                         }
248
249                 }
250         }
251
252         return found_default;
253 }
254
255
256 // Router Advert server mode
257 static void send_router_advert(struct uloop_timeout *event)
258 {
259         struct interface *iface =
260                         container_of(event, struct interface, timer_rs);
261
262         int mtu = odhcpd_get_interface_mtu(iface->ifname);
263         if (mtu < 0)
264                 mtu = 1500;
265
266         struct {
267                 struct nd_router_advert h;
268                 struct nd_opt_slla lladdr;
269                 struct nd_opt_mtu mtu;
270                 struct nd_opt_prefix_info prefix[RELAYD_MAX_PREFIXES];
271         } adv = {
272                 .h = {{.icmp6_type = ND_ROUTER_ADVERT, .icmp6_code = 0}, 0, 0},
273                 .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
274                 .mtu = {ND_OPT_MTU, 1, 0, htonl(mtu)},
275         };
276         adv.h.nd_ra_flags_reserved = ND_RA_FLAG_OTHER;
277         if (iface->managed >= RELAYD_MANAGED_MFLAG)
278                 adv.h.nd_ra_flags_reserved |= ND_RA_FLAG_MANAGED;
279
280         if (iface->route_preference < 0)
281                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_LOW;
282         else if (iface->route_preference > 0)
283                 adv.h.nd_ra_flags_reserved |= ND_RA_PREF_HIGH;
284         odhcpd_get_mac(iface, adv.lladdr.addr);
285
286         // If not currently shutting down
287         struct odhcpd_ipaddr addrs[RELAYD_MAX_PREFIXES];
288         ssize_t ipcnt = 0;
289
290         // If not shutdown
291         if (event->cb) {
292                 ipcnt = odhcpd_get_interface_addresses(iface->ifindex,
293                                 addrs, ARRAY_SIZE(addrs));
294
295                 // Check default route
296                 if (parse_routes(addrs, ipcnt) || iface->default_router > 1)
297                         adv.h.nd_ra_router_lifetime =
298                                         htons(3 * MaxRtrAdvInterval);
299         }
300
301         // Construct Prefix Information options
302         bool have_public = false;
303         size_t cnt = 0;
304
305         struct in6_addr *dns_addr = NULL;
306         uint32_t dns_time = 0;
307         size_t dns_cnt = 1;
308
309         for (ssize_t i = 0; i < ipcnt; ++i) {
310                 struct odhcpd_ipaddr *addr = &addrs[i];
311                 if (addr->prefix > 64 || addr->has_class)
312                         continue; // Address not suitable
313
314                 if (addr->preferred > MaxPreferredTime)
315                         addr->preferred = MaxPreferredTime;
316
317                 if (addr->valid > MaxValidTime)
318                         addr->valid = MaxValidTime;
319
320                 struct nd_opt_prefix_info *p = NULL;
321                 for (size_t i = 0; i < cnt; ++i) {
322                         if (!memcmp(&adv.prefix[i].nd_opt_pi_prefix,
323                                         &addr->addr, 8))
324                                 p = &adv.prefix[i];
325                 }
326
327                 if (!p) {
328                         if (cnt >= ARRAY_SIZE(adv.prefix))
329                                 break;
330
331                         p = &adv.prefix[cnt++];
332                 }
333
334                 if ((addr->addr.s6_addr[0] & 0xfe) != 0xfc && addr->preferred > 0)
335                         have_public = true;
336
337                 memcpy(&p->nd_opt_pi_prefix, &addr->addr, 8);
338                 p->nd_opt_pi_type = ND_OPT_PREFIX_INFORMATION;
339                 p->nd_opt_pi_len = 4;
340                 p->nd_opt_pi_prefix_len = 64;
341                 p->nd_opt_pi_flags_reserved = 0;
342                 if (!iface->ra_not_onlink)
343                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_ONLINK;
344                 if (iface->managed < RELAYD_MANAGED_NO_AFLAG)
345                         p->nd_opt_pi_flags_reserved |= ND_OPT_PI_FLAG_AUTO;
346                 p->nd_opt_pi_valid_time = htonl(addr->valid);
347                 p->nd_opt_pi_preferred_time = htonl(addr->preferred);
348
349                 if (addr->preferred > dns_time) {
350                         dns_time = addr->preferred;
351                         dns_addr = &addr->addr;
352                 }
353         }
354
355         if (!have_public && !iface->default_router && adv.h.nd_ra_router_lifetime) {
356                 syslog(LOG_WARNING, "A default route is present but there is no public prefix "
357                                 "on %s thus we don't announce a default route!", iface->ifname);
358                 adv.h.nd_ra_router_lifetime = 0;
359         }
360
361         if (have_public && iface->deprecate_ula_if_public_avail)
362                 for (size_t i = 0; i < cnt; ++i)
363                         if ((adv.prefix[i].nd_opt_pi_prefix.s6_addr[0] & 0xfe) == 0xfc)
364                                 adv.prefix[i].nd_opt_pi_preferred_time = 0;
365
366         // DNS Recursive DNS
367         if (iface->dns_cnt > 0) {
368                 dns_addr = iface->dns;
369                 dns_cnt = iface->dns_cnt;
370                 dns_time = 2 * MaxRtrAdvInterval;
371         }
372
373         if (!dns_addr)
374                 dns_cnt = 0;
375
376         struct nd_opt_recursive_dns dns = {ND_OPT_RECURSIVE_DNS, (1 + (2 * dns_cnt)), 0, 0, htonl(dns_time)};
377
378
379         // DNS Search options
380         uint8_t search_buf[256], *search_domain = iface->search;
381         size_t search_len = iface->search_len, search_padded = 0;
382
383         if (!search_domain && !res_init() && _res.dnsrch[0] && _res.dnsrch[0][0]) {
384                 int len = dn_comp(_res.dnsrch[0], search_buf,
385                                 sizeof(search_buf), NULL, NULL);
386                 if (len > 0) {
387                         search_domain = search_buf;
388                         search_len = len;
389                 }
390         }
391
392         if (search_len > 0)
393                 search_padded = ((search_len + 7) & (~7)) + 8;
394
395         struct {
396                 uint8_t type;
397                 uint8_t len;
398                 uint8_t pad;
399                 uint8_t pad2;
400                 uint32_t lifetime;
401                 uint8_t name[];
402         } *search = alloca(sizeof(*search) + search_padded);
403
404         if (!search) {
405                 syslog(LOG_ERR, "Alloca failed for dns search on interface %s", iface->ifname);
406                 return;
407         }
408         search->type = ND_OPT_DNS_SEARCH;
409         search->len = search_len ? ((sizeof(*search) + search_padded) / 8) : 0;
410         search->pad = 0;
411         search->pad2 = 0;
412         search->lifetime = htonl(2 * MaxRtrAdvInterval);;
413         memcpy(search->name, search_domain, search_len);
414         memset(&search->name[search_len], 0, search_padded - search_len);
415
416
417         size_t routes_cnt = 0;
418         struct {
419                 uint8_t type;
420                 uint8_t len;
421                 uint8_t prefix;
422                 uint8_t flags;
423                 uint32_t lifetime;
424                 uint32_t addr[4];
425         } routes[RELAYD_MAX_PREFIXES];
426
427         for (ssize_t i = 0; i < ipcnt; ++i) {
428                 struct odhcpd_ipaddr *addr = &addrs[i];
429                 if (addr->prefix > 64 || addr->prefix == 0) {
430                         continue; // Address not suitable
431                 } else if (addr->prefix > 32) {
432                         addr->addr.s6_addr32[1] &= htonl(~((1U << (64 - addr->prefix)) - 1));
433                 } else if (addr->prefix <= 32) {
434                         addr->addr.s6_addr32[0] &= htonl(~((1U << (32 - addr->prefix)) - 1));
435                         addr->addr.s6_addr32[1] = 0;
436                 }
437
438                 routes[routes_cnt].type = ND_OPT_ROUTE_INFO;
439                 routes[routes_cnt].len = sizeof(*routes) / 8;
440                 routes[routes_cnt].prefix = addr->prefix;
441                 routes[routes_cnt].flags = 0;
442                 if (iface->route_preference < 0)
443                         routes[routes_cnt].flags |= ND_RA_PREF_LOW;
444                 else if (iface->route_preference > 0)
445                         routes[routes_cnt].flags |= ND_RA_PREF_HIGH;
446                 routes[routes_cnt].lifetime = htonl(addr->valid);
447                 routes[routes_cnt].addr[0] = addr->addr.s6_addr32[0];
448                 routes[routes_cnt].addr[1] = addr->addr.s6_addr32[1];
449                 routes[routes_cnt].addr[2] = addr->addr.s6_addr32[2];
450                 routes[routes_cnt].addr[3] = addr->addr.s6_addr32[3];
451
452                 ++routes_cnt;
453         }
454
455
456         struct iovec iov[] = {{&adv, (uint8_t*)&adv.prefix[cnt] - (uint8_t*)&adv},
457                         {&routes, routes_cnt * sizeof(*routes)},
458                         {&dns, (dns_cnt) ? sizeof(dns) : 0},
459                         {dns_addr, dns_cnt * sizeof(*dns_addr)},
460                         {search, search->len * 8}};
461         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
462         odhcpd_send(router_event.uloop.fd,
463                         &all_nodes, iov, ARRAY_SIZE(iov), iface);
464
465         // Rearm timer
466         int msecs;
467         odhcpd_urandom(&msecs, sizeof(msecs));
468         msecs = (labs(msecs) % (1000 * (MaxRtrAdvInterval
469                         - MinRtrAdvInterval))) + (MinRtrAdvInterval * 1000);
470         uloop_timeout_set(&iface->timer_rs, msecs);
471 }
472
473
474 // Forward router solicitation
475 static void forward_router_solicitation(const struct interface *iface)
476 {
477         if (!iface)
478                 return;
479
480         struct icmp6_hdr rs = {ND_ROUTER_SOLICIT, 0, 0, {{0}}};
481         struct iovec iov = {&rs, sizeof(rs)};
482         struct sockaddr_in6 all_routers =
483                 {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, iface->ifindex};
484
485         syslog(LOG_NOTICE, "Sending RS to %s", iface->ifname);
486         odhcpd_send(router_event.uloop.fd, &all_routers, &iov, 1, iface);
487 }
488
489
490 // Handler for incoming router solicitations on slave interfaces
491 static void forward_router_advertisement(uint8_t *data, size_t len)
492 {
493         struct nd_router_advert *adv = (struct nd_router_advert *)data;
494
495         // Rewrite options
496         uint8_t *end = data + len;
497         uint8_t *mac_ptr = NULL;
498         struct in6_addr *dns_ptr = NULL;
499         size_t dns_count = 0;
500
501         struct icmpv6_opt *opt;
502         icmpv6_for_each_option(opt, &adv[1], end) {
503                 if (opt->type == ND_OPT_SOURCE_LINKADDR) {
504                         // Store address of source MAC-address
505                         mac_ptr = ((struct nd_opt_slla *)opt)->addr;
506                 } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 1) {
507                         struct nd_opt_recursive_dns *dns = (struct nd_opt_recursive_dns *)opt;
508                         // Check if we have to rewrite DNS
509                         dns_ptr = (struct in6_addr *)&dns[1];
510                         dns_count = (dns->len - 1) / 2;
511                 }
512         }
513
514         syslog(LOG_NOTICE, "Got a RA");
515
516         // Indicate a proxy, however we don't follow the rest of RFC 4389 yet
517         adv->nd_ra_flags_reserved |= ND_RA_FLAG_PROXY;
518
519         // Forward advertisement to all slave interfaces
520         struct sockaddr_in6 all_nodes = {AF_INET6, 0, 0, ALL_IPV6_NODES, 0};
521         struct iovec iov = {data, len};
522
523         struct odhcpd_ipaddr addr;
524         struct interface *iface;
525         list_for_each_entry(iface, &interfaces, head) {
526                 if (iface->ra != RELAYD_RELAY || iface->master)
527                         continue;
528
529                 // Fixup source hardware address option
530                 if (mac_ptr)
531                         odhcpd_get_mac(iface, mac_ptr);
532
533                 // If we have to rewrite DNS entries
534                 if (iface->always_rewrite_dns && dns_ptr && dns_count > 0) {
535                         const struct in6_addr *rewrite = iface->dns;
536                         size_t rewrite_cnt = iface->dns_cnt;
537
538                         if (rewrite_cnt == 0) {
539                                 if (odhcpd_get_interface_addresses(iface->ifindex, &addr, 1) < 1)
540                                         continue; // Unable to comply
541
542                                 rewrite = &addr.addr;
543                                 rewrite_cnt = 1;
544                         }
545
546                         // Copy over any other addresses
547                         for (size_t i = 0; i < dns_count; ++i) {
548                                 size_t j = (i < rewrite_cnt) ? i : rewrite_cnt - 1;
549                                 dns_ptr[i] = rewrite[j];
550                         }
551                 }
552
553                 odhcpd_send(router_event.uloop.fd, &all_nodes, &iov, 1, iface);
554         }
555 }