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