1 /*
2  * Copyright (c)2019 ZeroTier, Inc.
3  *
4  * Use of this software is governed by the Business Source License included
5  * in the LICENSE.TXT file in the project's root directory.
6  *
7  * Change Date: 2025-01-01
8  *
9  * On the date above, in accordance with the Business Source License, use
10  * of this software will be governed by version 2.0 of the Apache License.
11  */
12 /****/
13 
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 
20 #include <unistd.h>
21 #include <signal.h>
22 
23 #include <fcntl.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/ioctl.h>
27 #include <sys/wait.h>
28 #include <sys/select.h>
29 #include <sys/cdefs.h>
30 #include <sys/uio.h>
31 #include <sys/param.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36 #include <net/if.h>
37 #include <ifaddrs.h>
38 #include <net/if_arp.h>
39 #include <net/if_dl.h>
40 #include <net/if_media.h>
41 #include <net/route.h>
42 
43 #include <sys/sysctl.h>
44 
45 #include "freebsd_getifmaddrs.h"
46 
47 #include <string>
48 #include <map>
49 #include <set>
50 #include <algorithm>
51 #include <utility>
52 
53 #include "../node/Constants.hpp"
54 #include "../node/Utils.hpp"
55 #include "../node/Mutex.hpp"
56 #include "OSUtils.hpp"
57 #include "NetBSDEthernetTap.hpp"
58 
59 #include <iostream>
60 using namespace std;
61 #define ZT_BASE32_CHARS "0123456789abcdefghijklmnopqrstuv"
62 
63 // ff:ff:ff:ff:ff:ff with no ADI
64 static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
65 
66 namespace ZeroTier {
67 
NetBSDEthernetTap(const char * homePath,const MAC & mac,unsigned int mtu,unsigned int metric,uint64_t nwid,const char * friendlyName,void (* handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),void * arg)68 NetBSDEthernetTap::NetBSDEthernetTap(
69 	const char *homePath,
70 	const MAC &mac,
71 	unsigned int mtu,
72 	unsigned int metric,
73 	uint64_t nwid,
74 	const char *friendlyName,
75 	void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
76 	void *arg) :
77 	_handler(handler),
78 	_arg(arg),
79 	_nwid(nwid),
80 	_mtu(mtu),
81 	_metric(metric),
82 	_fd(0),
83 	_enabled(true)
84 {
85 	static Mutex globalTapCreateLock;
86 	char devpath[64],ethaddr[64],mtustr[32],metstr[32],tmpdevname[32];
87 	struct stat stattmp;
88 
89 	Mutex::Lock _gl(globalTapCreateLock);
90 
91 	if (mtu > 2800)
92 		throw std::runtime_error("max tap MTU is 2800");
93 
94 	// we can create /dev/tap*
95 	std::vector<std::string> devFiles(OSUtils::listDirectory("/dev"));
96 	for(int i=9993;i<(9993+128);++i) {
97 		Utils::snprintf(tmpdevname,sizeof(tmpdevname),"tap%d",i);
98 		Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",tmpdevname);
99 		if (std::find(devFiles.begin(),devFiles.end(),std::string(tmpdevname)) == devFiles.end()) {
100 			long cpid = (long)vfork();
101 			if (cpid == 0) {
102 				::execl("/sbin/ifconfig","/sbin/ifconfig",tmpdevname,"create",(const char *)0);
103 				::_exit(-1);
104 			} else if (cpid > 0) {
105 				int exitcode = -1;
106 				::waitpid(cpid,&exitcode,0);
107 			} else throw std::runtime_error("fork() failed");
108 
109 			cpid = (long)vfork();
110 			if (cpid == 0) {
111 				string tmp;
112 				sprintf((char*)tmp.c_str(), "%d", i);
113 				string minor = tmp.c_str();
114 				::execl("/sbin/mknod","/sbin/mknod",devpath,"c","169",minor.c_str(),(const char *)0);
115 				// http://ftp.netbsd.org/pub/NetBSD/NetBSD-current/src/sys/conf/majors
116 				// major 169 => tap
117 				::_exit(-1);
118 			} else if (cpid > 0) {
119 				int exitcode = -1;
120 				::waitpid(cpid,&exitcode,0);
121 			} else throw std::runtime_error("fork() failed");
122 
123 			cerr<<"created device "<<devpath<<endl;
124 
125 			_dev = tmpdevname;
126 			_fd = ::open(  devpath,O_RDWR);
127 			if (!stat(devpath,&stattmp)) {
128 				if (_fd > 0)
129 					break;
130 				else
131 					throw std::runtime_error("unable to open created tap device ");
132 			} else {
133 				throw std::runtime_error("cannot find /dev node for newly created tap device");
134 			}
135 		}
136 	}
137 
138 	if (_fd <= 0)
139 		throw std::runtime_error("unable to open TAP device or no more devices available");
140 
141 	if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
142 		::close(_fd);
143 		throw std::runtime_error("unable to set flags on file descriptor for TAP device");
144 	}
145 
146 	// Configure MAC address and MTU, bring interface up
147 	Utils::snprintf(ethaddr,sizeof(ethaddr),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(int)mac[0],(int)mac[1],(int)mac[2],(int)mac[3],(int)mac[4],(int)mac[5]);
148 	Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
149 	Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
150 	long cpid = (long)vfork();
151 	if (cpid == 0) {
152 		::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"link",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
153 		::_exit(-1);
154 	} else if (cpid > 0) {
155 		int exitcode = -1;
156 		::waitpid(cpid,&exitcode,0);
157 		if (exitcode) {
158 			::close(_fd);
159 			throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
160 		}
161 	}
162 
163 	// ifconfig link seems to be different from address
164 	// https://wiki.netbsd.org/tutorials/faking_a_mac_address/
165 	cpid = (long)vfork();
166 	if (cpid == 0) {
167 		string cmdline = "net.link.tap."+string(_dev);
168 		cmdline += "="+string(ethaddr);
169 		::execl("/sbin/sysctl","/sbin/sysctl","-w",cmdline.c_str(),(const char *)0);
170 		::_exit(-1);
171 	} else if (cpid > 0) {
172 		int exitcode = -1;
173 		::waitpid(cpid,&exitcode,0);
174 		if (exitcode) {
175 			::close(_fd);
176 			throw std::runtime_error("sysctl failure setting link-layer address and activating tap interface");
177 		}
178 	}
179 
180 	// Set close-on-exec so that devices cannot persist if we fork/exec for update
181 	fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
182 
183 	::pipe(_shutdownSignalPipe);
184 
185 	_thread = Thread::start(this);
186 
187 }
188 
~NetBSDEthernetTap()189 NetBSDEthernetTap::~NetBSDEthernetTap()
190 {
191 	::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
192 	Thread::join(_thread);
193 	::close(_fd);
194 	::close(_shutdownSignalPipe[0]);
195 	::close(_shutdownSignalPipe[1]);
196 
197 	long cpid = (long)vfork();
198 	if (cpid == 0) {
199 		::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
200 		::_exit(-1);
201 	} else if (cpid > 0) {
202 		int exitcode = -1;
203 		::waitpid(cpid,&exitcode,0);
204 	}
205 
206 	cpid = (long)vfork();
207 	if (cpid == 0) {
208 		string tmp="/dev/";
209 		tmp+=_dev.c_str();
210 		::execl("/bin/rm","/bin/rm",tmp.c_str(),(const char *)0);
211 		::_exit(-1);
212 	} else if (cpid > 0) {
213 		int exitcode = -1;
214 		::waitpid(cpid,&exitcode,0);
215 	} else throw std::runtime_error("fork() failed");
216 }
217 
setEnabled(bool en)218 void NetBSDEthernetTap::setEnabled(bool en)
219 {
220 	_enabled = en;
221 }
222 
enabled() const223 bool NetBSDEthernetTap::enabled() const
224 {
225 	return _enabled;
226 }
227 
___removeIp(const std::string & _dev,const InetAddress & ip)228 static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
229 {
230 	long cpid = (long)vfork();
231 	if (cpid == 0) {
232 		execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
233 		_exit(-1);
234 	} else if (cpid > 0) {
235 		int exitcode = -1;
236 		waitpid(cpid,&exitcode,0);
237 		return (exitcode == 0);
238 	}
239 	return false; // never reached, make compiler shut up about return value
240 }
241 
addIp(const InetAddress & ip)242 bool NetBSDEthernetTap::addIp(const InetAddress &ip)
243 {
244 	if (!ip)
245 		return false;
246 
247 	std::vector<InetAddress> allIps(ips());
248 	if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end())
249 		return true; // IP/netmask already assigned
250 
251 	// Remove and reconfigure if address is the same but netmask is different
252 	for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
253 		if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
254 			if (___removeIp(_dev,*i))
255 				break;
256 		}
257 	}
258 
259 	long cpid = (long)vfork();
260 	if (cpid == 0) {
261 		::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
262 		::_exit(-1);
263 	} else if (cpid > 0) {
264 		int exitcode = -1;
265 		::waitpid(cpid,&exitcode,0);
266 		return (exitcode == 0);
267 	}
268 	return false;
269 }
270 
removeIp(const InetAddress & ip)271 bool NetBSDEthernetTap::removeIp(const InetAddress &ip)
272 {
273 	if (!ip)
274 		return false;
275 	std::vector<InetAddress> allIps(ips());
276 	if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
277 		if (___removeIp(_dev,ip))
278 			return true;
279 	}
280 	return false;
281 }
282 
ips() const283 std::vector<InetAddress> NetBSDEthernetTap::ips() const
284 {
285 	struct ifaddrs *ifa = (struct ifaddrs *)0;
286 	if (getifaddrs(&ifa))
287 		return std::vector<InetAddress>();
288 
289 	std::vector<InetAddress> r;
290 
291 	struct ifaddrs *p = ifa;
292 	while (p) {
293 		if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
294 			switch(p->ifa_addr->sa_family) {
295 				case AF_INET: {
296 					struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
297 					struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
298 					r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
299 				}	break;
300 				case AF_INET6: {
301 					struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
302 					struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
303 					uint32_t b[4];
304 					memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
305 					r.push_back(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
306 				}	break;
307 			}
308 		}
309 		p = p->ifa_next;
310 	}
311 
312 	if (ifa)
313 		freeifaddrs(ifa);
314 
315 	std::sort(r.begin(),r.end());
316 	std::unique(r.begin(),r.end());
317 
318 	return r;
319 }
320 
put(const MAC & from,const MAC & to,unsigned int etherType,const void * data,unsigned int len)321 void NetBSDEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
322 {
323 	char putBuf[4096];
324 	if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
325 		to.copyTo(putBuf,6);
326 		from.copyTo(putBuf + 6,6);
327 		*((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
328 		memcpy(putBuf + 14,data,len);
329 		len += 14;
330 		::write(_fd,putBuf,len);
331 	}
332 }
333 
deviceName() const334 std::string NetBSDEthernetTap::deviceName() const
335 {
336 	return _dev;
337 }
338 
setFriendlyName(const char * friendlyName)339 void NetBSDEthernetTap::setFriendlyName(const char *friendlyName)
340 {
341 }
342 
scanMulticastGroups(std::vector<MulticastGroup> & added,std::vector<MulticastGroup> & removed)343 void NetBSDEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
344 {
345 	std::vector<MulticastGroup> newGroups;
346 
347 	struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
348 	if (!getifmaddrs(&ifmap)) {
349 		struct ifmaddrs *p = ifmap;
350 		while (p) {
351 			if (p->ifma_addr->sa_family == AF_LINK) {
352 				struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
353 				struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
354 				if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
355 					newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
356 			}
357 			p = p->ifma_next;
358 		}
359 		freeifmaddrs(ifmap);
360 	}
361 
362 	std::vector<InetAddress> allIps(ips());
363 	for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
364 		newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
365 
366 	std::sort(newGroups.begin(),newGroups.end());
367 	std::unique(newGroups.begin(),newGroups.end());
368 
369 	for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
370 		if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
371 			added.push_back(*m);
372 	}
373 	for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
374 		if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
375 			removed.push_back(*m);
376 	}
377 
378 	_multicastGroups.swap(newGroups);
379 }
380 
381 /*
382 bool NetBSDEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
383 {
384 	std::set<MulticastGroup> newGroups;
385 	struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
386 	if (!getifmaddrs(&ifmap)) {
387 		struct ifmaddrs *p = ifmap;
388 		while (p) {
389 			if (p->ifma_addr->sa_family == AF_LINK) {
390 				struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
391 				struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
392 				if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
393 					newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
394 			}
395 			p = p->ifma_next;
396 		}
397 		freeifmaddrs(ifmap);
398 	}
399 
400 	{
401 		std::set<InetAddress> allIps(ips());
402 		for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
403 			newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
404 	}
405 
406 	bool changed = false;
407 
408 	for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
409 		if (!groups.count(*mg)) {
410 			groups.insert(*mg);
411 			changed = true;
412 		}
413 	}
414 	for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
415 		if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
416 			groups.erase(mg++);
417 			changed = true;
418 		} else ++mg;
419 	}
420 
421 	return changed;
422 }
423 */
424 
threadMain()425 void NetBSDEthernetTap::threadMain()
426 	throw()
427 {
428 	fd_set readfds,nullfds;
429 	MAC to,from;
430 	int n,nfds,r;
431 	char getBuf[8194];
432 
433 	// Wait for a moment after startup -- wait for Network to finish
434 	// constructing itself.
435 	Thread::sleep(500);
436 
437 	FD_ZERO(&readfds);
438 	FD_ZERO(&nullfds);
439 	nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
440 
441 	r = 0;
442 	for(;;) {
443 		FD_SET(_shutdownSignalPipe[0],&readfds);
444 		FD_SET(_fd,&readfds);
445 		select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
446 
447 		if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
448 			break;
449 
450 		if (FD_ISSET(_fd,&readfds)) {
451 			n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
452 			if (n < 0) {
453 				if ((errno != EINTR)&&(errno != ETIMEDOUT))
454 					break;
455 			} else {
456 				// Some tap drivers like to send the ethernet frame and the
457 				// payload in two chunks, so handle that by accumulating
458 				// data until we have at least a frame.
459 				r += n;
460 				if (r > 14) {
461 					if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
462 						r = _mtu + 14;
463 
464 					if (_enabled) {
465 						to.setTo(getBuf,6);
466 						from.setTo(getBuf + 6,6);
467 						unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
468 						// TODO: VLAN support
469 						_handler(_arg,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
470 					}
471 
472 					r = 0;
473 				}
474 			}
475 		}
476 	}
477 }
478 
479 } // namespace ZeroTier
480