c1f3d0373cf47ca311e297d8ed48e2d25bb853fd
[oweals/odhcp6c.git] / src / ra.c
1 /**
2  * Copyright (C) 2012-2014 Steven Barth <steven@midlink.org>
3  * Copyright (C) 2017-2018 Hans Dedecker <dedeckeh@gmail.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License v2 as published by
7  * the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  */
15
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdio.h>
19 #include <signal.h>
20 #include <string.h>
21 #include <stddef.h>
22 #include <stdbool.h>
23 #include <syslog.h>
24 #include <unistd.h>
25 #include <resolv.h>
26 #include <alloca.h>
27
28 #include <net/if.h>
29 #include <arpa/inet.h>
30 #include <sys/socket.h>
31 #include <sys/types.h>
32 #include <netinet/in.h>
33 #include <netinet/icmp6.h>
34
35 #include <linux/rtnetlink.h>
36
37 #ifndef SOL_NETLINK
38 #define SOL_NETLINK 270
39 #endif
40
41 #ifndef NETLINK_ADD_MEMBERSHIP
42 #define NETLINK_ADD_MEMBERSHIP 1
43 #endif
44
45 #ifndef IFF_LOWER_UP
46 #define IFF_LOWER_UP 0x10000
47 #endif
48
49 #include "odhcp6c.h"
50 #include "ra.h"
51
52 static bool nocarrier = false;
53
54 static int sock = -1, rtnl = -1;
55 static int if_index = 0;
56 static char if_name[IF_NAMESIZE] = {0};
57 static volatile int rs_attempt = 0;
58 static struct in6_addr lladdr = IN6ADDR_ANY_INIT;
59 static unsigned int ra_options = 0;
60 static unsigned int ra_holdoff_interval = 0;
61
62 struct {
63         struct icmp6_hdr hdr;
64         struct icmpv6_opt lladdr;
65 } rs = {
66         .hdr = {ND_ROUTER_SOLICIT, 0, 0, {{0}}},
67         .lladdr = {ND_OPT_SOURCE_LINKADDR, 1, {0}},
68 };
69
70 static void ra_send_rs(int signal __attribute__((unused)));
71
72 int ra_init(const char *ifname, const struct in6_addr *ifid,
73                 unsigned int options, unsigned int holdoff_interval)
74 {
75         ra_options = options;
76         ra_holdoff_interval = holdoff_interval;
77
78         const pid_t ourpid = getpid();
79         sock = socket(AF_INET6, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_ICMPV6);
80         if (sock < 0)
81                 goto failure;
82
83         if_index = if_nametoindex(ifname);
84         if (!if_index)
85                 goto failure;
86
87         strncpy(if_name, ifname, sizeof(if_name) - 1);
88         lladdr = *ifid;
89
90         rtnl = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_ROUTE);
91         if (rtnl < 0)
92                 goto failure;
93
94         struct sockaddr_nl rtnl_kernel = { .nl_family = AF_NETLINK };
95         if (connect(rtnl, (const struct sockaddr*)&rtnl_kernel, sizeof(rtnl_kernel)) < 0)
96                 goto failure;
97
98         int val = RTNLGRP_LINK;
99         if (setsockopt(rtnl, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &val, sizeof(val)) < 0)
100                 goto failure;
101
102         if (fcntl(rtnl, F_SETOWN, ourpid) < 0)
103                 goto failure;
104
105         if (fcntl(rtnl, F_SETFL, fcntl(sock, F_GETFL) | O_ASYNC) < 0)
106                 goto failure;
107
108         struct {
109                 struct nlmsghdr hdr;
110                 struct ifinfomsg ifi;
111         } req = {
112                 .hdr = {sizeof(req), RTM_GETLINK, NLM_F_REQUEST, 1, 0},
113                 .ifi = {.ifi_index = if_index}
114         };
115         if (send(rtnl, &req, sizeof(req), 0) < 0)
116                 goto failure;
117
118         ra_link_up();
119
120         // Filter ICMPv6 package types
121         struct icmp6_filter filt;
122         ICMP6_FILTER_SETBLOCKALL(&filt);
123         ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filt);
124         if (setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, sizeof(filt)) < 0)
125                 goto failure;
126
127         // Bind to all-nodes
128         struct ipv6_mreq an = {ALL_IPV6_NODES, if_index};
129         if (setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &an, sizeof(an)) < 0)
130                 goto failure;
131
132         // Let the kernel compute our checksums
133         val = 2;
134         if (setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val)) < 0)
135                 goto failure;
136
137         // This is required by RFC 4861
138         val = 255;
139         if (setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)) < 0)
140                 goto failure;
141
142         // Receive multicast hops
143         val = 1;
144         if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val)) < 0)
145                 goto failure;
146
147         // Bind to one device
148         if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname)) < 0)
149                 goto failure;
150
151         // Add async-mode
152         if (fcntl(sock, F_SETOWN, ourpid) < 0)
153                 goto failure;
154
155         val = fcntl(sock, F_GETFL);
156         if (val < 0)
157                 goto failure;
158
159         if (fcntl(sock, F_SETFL, val | O_ASYNC) < 0)
160                 goto failure;
161
162         // Send RS
163         signal(SIGALRM, ra_send_rs);
164         ra_send_rs(SIGALRM);
165
166         return 0;
167
168 failure:
169         if (sock >= 0)
170                 close(sock);
171
172         if (rtnl >= 0)
173                 close(rtnl);
174
175         return -1;
176 }
177
178 static void ra_send_rs(int signal __attribute__((unused)))
179 {
180         const struct sockaddr_in6 dest = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, if_index};
181         const struct icmpv6_opt llnull = {ND_OPT_SOURCE_LINKADDR, 1, {0}};
182         size_t len;
183
184         if ((rs_attempt % 2 == 0) && memcmp(&rs.lladdr, &llnull, sizeof(llnull)))
185                 len = sizeof(rs);
186         else
187                 len = sizeof(struct icmp6_hdr);
188
189         if (sendto(sock, &rs, len, MSG_DONTWAIT, (struct sockaddr*)&dest, sizeof(dest)) < 0)
190                 syslog(LOG_ERR, "Failed to send RS (%s)",  strerror(errno));
191
192         if (++rs_attempt <= 3)
193                 alarm(4);
194 }
195
196 static int16_t pref_to_priority(uint8_t flags)
197 {
198         flags = (flags >> 3) & 0x03;
199
200         return (flags == 0x0) ? 512 : (flags == 0x1) ? 384 :
201                         (flags == 0x3) ? 640 : -1;
202 }
203
204 bool ra_link_up(void)
205 {
206         static bool firstcall = true;
207         struct {
208                 struct nlmsghdr hdr;
209                 struct ifinfomsg msg;
210                 uint8_t pad[4000];
211         } resp;
212         bool ret = false;
213         ssize_t read;
214
215         do {
216                 read = recv(rtnl, &resp, sizeof(resp), MSG_DONTWAIT);
217
218                 if (read < 0 || !NLMSG_OK(&resp.hdr, (size_t)read) ||
219                                 resp.hdr.nlmsg_type != RTM_NEWLINK ||
220                                 resp.msg.ifi_index != if_index)
221                         continue;
222
223                 ssize_t alen = NLMSG_PAYLOAD(&resp.hdr, sizeof(resp.msg));
224                 for (struct rtattr *rta = (struct rtattr*)(resp.pad);
225                                 RTA_OK(rta, alen); rta = RTA_NEXT(rta, alen)) {
226                         if (rta->rta_type == IFLA_ADDRESS &&
227                                         RTA_PAYLOAD(rta) >= sizeof(rs.lladdr.data))
228                                 memcpy(rs.lladdr.data, RTA_DATA(rta), sizeof(rs.lladdr.data));
229                 }
230
231                 bool hascarrier = resp.msg.ifi_flags & IFF_LOWER_UP;
232                 if (!firstcall && nocarrier != !hascarrier)
233                         ret = true;
234
235                 nocarrier = !hascarrier;
236                 firstcall = false;
237         } while (read > 0);
238
239         if (ret) {
240                 syslog(LOG_NOTICE, "carrier => %i event on %s", (int)!nocarrier, if_name);
241
242                 rs_attempt = 0;
243                 ra_send_rs(SIGALRM);
244         }
245
246         return ret;
247 }
248
249 static bool ra_icmpv6_valid(struct sockaddr_in6 *source, int hlim, uint8_t *data, size_t len)
250 {
251         struct icmp6_hdr *hdr = (struct icmp6_hdr*)data;
252         struct icmpv6_opt *opt, *end = (struct icmpv6_opt*)&data[len];
253
254         if (hlim != 255 || len < sizeof(*hdr) || hdr->icmp6_code)
255                 return false;
256
257         switch (hdr->icmp6_type) {
258         case ND_ROUTER_ADVERT:
259                 if (!IN6_IS_ADDR_LINKLOCAL(&source->sin6_addr))
260                         return false;
261
262                 opt = (struct icmpv6_opt*)((struct nd_router_advert*)data + 1);
263                 break;
264
265         default:
266                 return false;
267         }
268
269         icmpv6_for_each_option(opt, opt, end)
270                 ;
271
272         return opt == end;
273 }
274
275 int ra_conf_hoplimit(int newvalue)
276 {
277         static int value = 0;
278
279         if (newvalue > 0)
280                 value = newvalue;
281
282         return value;
283 }
284
285 int ra_conf_mtu(int newvalue)
286 {
287         static int value = 0;
288
289         if (newvalue >= 1280 && newvalue <= 65535)
290                 value = newvalue;
291
292         return value;
293 }
294
295 int ra_conf_reachable(int newvalue)
296 {
297         static int value = 0;
298
299         if (newvalue > 0 && newvalue <= 3600000)
300                 value = newvalue;
301
302         return value;
303 }
304
305 int ra_conf_retransmit(int newvalue)
306 {
307         static int value = 0;
308
309         if (newvalue > 0 && newvalue <= 60000)
310                 value = newvalue;
311
312         return value;
313 }
314
315 bool ra_process(void)
316 {
317         bool found = false;
318         bool changed = false;
319         uint8_t buf[1500] _aligned(4);
320         union {
321                 struct cmsghdr hdr;
322                 uint8_t buf[CMSG_SPACE(sizeof(int))];
323         } cmsg_buf;
324         struct nd_router_advert *adv = (struct nd_router_advert*)buf;
325         struct odhcp6c_entry *entry = alloca(sizeof(*entry) + 256);
326         const struct in6_addr any = IN6ADDR_ANY_INIT;
327
328         memset(entry, 0, sizeof(*entry));
329
330         if (IN6_IS_ADDR_UNSPECIFIED(&lladdr)) {
331                 struct sockaddr_in6 addr = {AF_INET6, 0, 0, ALL_IPV6_ROUTERS, if_index};
332                 socklen_t alen = sizeof(addr);
333                 int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
334
335                 if (sock >= 0) {
336                         if (!connect(sock, (struct sockaddr*)&addr, sizeof(addr)) &&
337                                         !getsockname(sock, (struct sockaddr*)&addr, &alen))
338                                 lladdr = addr.sin6_addr;
339
340                         close(sock);
341                 }
342         }
343
344         while (true) {
345                 struct sockaddr_in6 from;
346                 struct iovec iov = {buf, sizeof(buf)};
347                 struct msghdr msg = {
348                         .msg_name = (void *) &from,
349                         .msg_namelen = sizeof(from),
350                         .msg_iov = &iov,
351                         .msg_iovlen = 1,
352                         .msg_control = cmsg_buf.buf,
353                         .msg_controllen = sizeof(cmsg_buf),
354                         .msg_flags = 0
355                 };
356
357                 ssize_t len = recvmsg(sock, &msg, MSG_DONTWAIT);
358                 if (len <= 0)
359                         break;
360
361                 if (IN6_IS_ADDR_UNSPECIFIED(&lladdr))
362                         continue;
363
364                 int hlim = 0;
365                 for (struct cmsghdr *ch = CMSG_FIRSTHDR(&msg); ch != NULL;
366                                 ch = CMSG_NXTHDR(&msg, ch))
367                         if (ch->cmsg_level == IPPROTO_IPV6 &&
368                                         ch->cmsg_type == IPV6_HOPLIMIT)
369                                 memcpy(&hlim, CMSG_DATA(ch), sizeof(hlim));
370
371                 if (!ra_icmpv6_valid(&from, hlim, buf, len))
372                         continue;
373
374                 // Stop sending solicits
375                 if (rs_attempt > 0) {
376                         alarm(0);
377                         rs_attempt = 0;
378                 }
379
380                 if (!found) {
381                         odhcp6c_expire();
382                         found = true;
383                 }
384                 uint32_t router_valid = ntohs(adv->nd_ra_router_lifetime);
385
386                 // Parse default route
387                 entry->target = any;
388                 entry->length = 0;
389                 entry->router = from.sin6_addr;
390                 entry->priority = pref_to_priority(adv->nd_ra_flags_reserved);
391                 if (entry->priority < 0)
392                         entry->priority = pref_to_priority(0);
393
394                 entry->valid = router_valid;
395                 entry->preferred = entry->valid;
396                 changed |= odhcp6c_update_entry(STATE_RA_ROUTE, entry,
397                                                 0, ra_holdoff_interval);
398
399                 // Parse hoplimit
400                 ra_conf_hoplimit(adv->nd_ra_curhoplimit);
401
402                 // Parse ND parameters
403                 ra_conf_reachable(ntohl(adv->nd_ra_reachable));
404                 ra_conf_retransmit(ntohl(adv->nd_ra_retransmit));
405
406                 // Evaluate options
407                 struct icmpv6_opt *opt;
408                 icmpv6_for_each_option(opt, &adv[1], &buf[len]) {
409                         if (opt->type == ND_OPT_MTU) {
410                                 uint32_t *mtu = (uint32_t*)&opt->data[2];
411                                 ra_conf_mtu(ntohl(*mtu));
412                         } else if (opt->type == ND_OPT_ROUTE_INFORMATION && opt->len <= 3) {
413                                 struct icmpv6_opt_route_info *ri = (struct icmpv6_opt_route_info *)opt;
414
415                                 if (ri->prefix_len > 128) {
416                                         continue;
417                                 } else if (ri->prefix_len > 64) {
418                                         if (ri->len < 2)
419                                                 continue;
420                                 } else if (ri->prefix_len > 0) {
421                                         if (ri->len < 1)
422                                                 continue;
423                                 }
424
425                                 entry->router = from.sin6_addr;
426                                 entry->target = any;
427                                 entry->priority = pref_to_priority(ri->flags);
428                                 entry->length = ri->prefix_len;
429                                 entry->valid = ntohl(ri->lifetime);
430                                 memcpy(&entry->target, ri->prefix, (ri->len - 1) * 8);
431
432                                 if (IN6_IS_ADDR_LINKLOCAL(&entry->target)
433                                                 || IN6_IS_ADDR_LOOPBACK(&entry->target)
434                                                 || IN6_IS_ADDR_MULTICAST(&entry->target))
435                                         continue;
436
437                                 if (entry->priority > 0)
438                                         changed |= odhcp6c_update_entry(STATE_RA_ROUTE, entry,
439                                                                         0, ra_holdoff_interval);
440                         } else if (opt->type == ND_OPT_PREFIX_INFORMATION && opt->len == 4) {
441                                 struct nd_opt_prefix_info *pinfo = (struct nd_opt_prefix_info*)opt;
442                                 entry->router = any;
443                                 entry->target = pinfo->nd_opt_pi_prefix;
444                                 entry->priority = 256;
445                                 entry->length = pinfo->nd_opt_pi_prefix_len;
446                                 entry->valid = ntohl(pinfo->nd_opt_pi_valid_time);
447                                 entry->preferred = ntohl(pinfo->nd_opt_pi_preferred_time);
448
449                                 if (entry->length > 128 || IN6_IS_ADDR_LINKLOCAL(&entry->target)
450                                                 || IN6_IS_ADDR_LOOPBACK(&entry->target)
451                                                 || IN6_IS_ADDR_MULTICAST(&entry->target)
452                                                 || entry->valid < entry->preferred)
453                                         continue;
454
455                                 if (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_ONLINK)
456                                         changed |= odhcp6c_update_entry(STATE_RA_ROUTE, entry,
457                                                                         7200, ra_holdoff_interval);
458
459                                 if (!(pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_AUTO) ||
460                                                 pinfo->nd_opt_pi_prefix_len != 64)
461                                         continue;
462
463                                 entry->target.s6_addr32[2] = lladdr.s6_addr32[2];
464                                 entry->target.s6_addr32[3] = lladdr.s6_addr32[3];
465
466                                 changed |= odhcp6c_update_entry(STATE_RA_PREFIX, entry,
467                                                                 7200, ra_holdoff_interval);
468                         } else if (opt->type == ND_OPT_RECURSIVE_DNS && opt->len > 2) {
469                                 entry->router = from.sin6_addr;
470                                 entry->priority = 0;
471                                 entry->length = 128;
472                                 uint32_t *valid = (uint32_t*)&opt->data[2];
473                                 entry->valid = ntohl(*valid);
474                                 entry->preferred = 0;
475
476                                 for (ssize_t i = 0; i < (opt->len - 1) / 2; ++i) {
477                                         memcpy(&entry->target, &opt->data[6 + i * sizeof(entry->target)],
478                                                         sizeof(entry->target));
479                                         changed |= odhcp6c_update_entry(STATE_RA_DNS, entry,
480                                                                         0, ra_holdoff_interval);
481                                 }
482                         } else if (opt->type == ND_OPT_DNSSL && opt->len > 1) {
483                                 uint32_t *valid = (uint32_t*)&opt->data[2];
484                                 uint8_t *buf = &opt->data[6];
485                                 uint8_t *end = &buf[(opt->len - 1) * 8];
486
487                                 entry->router = from.sin6_addr;
488                                 entry->valid = ntohl(*valid);
489
490                                 while (buf < end) {
491                                         int len = dn_expand(buf, end, buf, (char*)entry->auxtarget, 256);
492                                         if (len < 1)
493                                                 break;
494
495                                         buf = &buf[len];
496                                         entry->auxlen = strlen((char*)entry->auxtarget);
497
498                                         if (entry->auxlen == 0)
499                                                 continue;
500
501                                         changed |= odhcp6c_update_entry(STATE_RA_SEARCH, entry,
502                                                                         0, ra_holdoff_interval);
503                                         entry->auxlen = 0;
504                                 }
505                         }
506                 }
507
508                 if (ra_options & RA_RDNSS_DEFAULT_LIFETIME) {
509                         int states[2] = {STATE_RA_DNS, STATE_RA_SEARCH};
510
511                         for (size_t i = 0; i < 2; ++i) {
512                                 size_t ra_dns_len;
513                                 uint8_t *start = odhcp6c_get_state(states[i], &ra_dns_len);
514
515                                 for (struct odhcp6c_entry *c = (struct odhcp6c_entry*)start;
516                                                         (uint8_t*)c < &start[ra_dns_len] &&
517                                                         (uint8_t*)odhcp6c_next_entry(c) <= &start[ra_dns_len];
518                                                         c = odhcp6c_next_entry(c)) {
519                                         if (IN6_ARE_ADDR_EQUAL(&c->router, &from.sin6_addr) &&
520                                                         c->valid > router_valid)
521                                                 c->valid = router_valid;
522                                 }
523                         }
524                 }
525         }
526
527         if (found)
528                 odhcp6c_expire();
529
530         return found && changed;
531 }