WindowsEthernetTap.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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 as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <WinSock2.h>
  32. #include <Windows.h>
  33. #include <tchar.h>
  34. #include <winreg.h>
  35. #include <wchar.h>
  36. #include <ws2ipdef.h>
  37. #include <WS2tcpip.h>
  38. #include <IPHlpApi.h>
  39. #include <nldef.h>
  40. #include <netioapi.h>
  41. #include <atlbase.h>
  42. #include <netlistmgr.h>
  43. #include <nldef.h>
  44. #include <iostream>
  45. #include "../node/Constants.hpp"
  46. #include "WindowsEthernetTap.hpp"
  47. #include "WindowsEthernetTapFactory.hpp"
  48. #include "../node/Utils.hpp"
  49. #include "../node/Mutex.hpp"
  50. #include "..\windows\TapDriver\tap-windows.h"
  51. // ff:ff:ff:ff:ff:ff with no ADI
  52. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  53. #define ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  54. namespace ZeroTier {
  55. // Only create or delete devices one at a time
  56. static Mutex _systemTapInitLock;
  57. WindowsEthernetTap::WindowsEthernetTap(
  58. const char *pathToHelpers,
  59. const MAC &mac,
  60. unsigned int mtu,
  61. unsigned int metric,
  62. uint64_t nwid,
  63. const char *desiredDevice,
  64. const char *friendlyName,
  65. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  66. void *arg) :
  67. EthernetTap("WindowsEthernetTap",mac,mtu,metric),
  68. _handler(handler),
  69. _arg(arg),
  70. _nwid(nwid),
  71. _tap(INVALID_HANDLE_VALUE),
  72. _injectSemaphore(INVALID_HANDLE_VALUE),
  73. _pathToHelpers(pathToHelpers),
  74. _run(true),
  75. _initialized(false),
  76. _enabled(true)
  77. {
  78. char subkeyName[4096];
  79. char subkeyClass[4096];
  80. char data[4096];
  81. char tag[24];
  82. if (mtu > 2800)
  83. throw std::runtime_error("MTU too large for Windows tap");
  84. Mutex::Lock _l(_systemTapInitLock);
  85. HKEY nwAdapters;
  86. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  87. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  88. std::set<std::string> existingDeviceInstances;
  89. std::string mySubkeyName;
  90. // We "tag" registry entries with the network ID to identify persistent devices
  91. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)nwid);
  92. // Look for the tap instance that corresponds with this network
  93. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  94. DWORD type;
  95. DWORD dataLen;
  96. DWORD subkeyNameLen = sizeof(subkeyName);
  97. DWORD subkeyClassLen = sizeof(subkeyClass);
  98. FILETIME lastWriteTime;
  99. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  100. type = 0;
  101. dataLen = sizeof(data);
  102. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  103. data[dataLen] = '\0';
  104. if (!strnicmp(data,"zttap",5)) {
  105. std::string instanceId;
  106. type = 0;
  107. dataLen = sizeof(data);
  108. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  109. instanceId.assign(data,dataLen);
  110. existingDeviceInstances.insert(instanceId);
  111. }
  112. std::string instanceIdPath;
  113. type = 0;
  114. dataLen = sizeof(data);
  115. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  116. instanceIdPath.assign(data,dataLen);
  117. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  118. type = 0;
  119. dataLen = sizeof(data);
  120. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  121. data[dataLen] = '\0';
  122. if (!strcmp(data,tag)) {
  123. _netCfgInstanceId = instanceId;
  124. _deviceInstanceId = instanceIdPath;
  125. mySubkeyName = subkeyName;
  126. break; // found it!
  127. }
  128. }
  129. }
  130. }
  131. }
  132. } else break; // no more subkeys or error occurred enumerating them
  133. }
  134. // If there is no device, try to create one
  135. bool creatingNewDevice = (_netCfgInstanceId.length() == 0);
  136. if (creatingNewDevice) {
  137. // Log devcon output to a file
  138. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  139. if (devconLog != INVALID_HANDLE_VALUE)
  140. SetFilePointer(devconLog,0,0,FILE_END);
  141. // Execute devcon to install an instance of the Microsoft Loopback Adapter
  142. STARTUPINFOA startupInfo;
  143. startupInfo.cb = sizeof(startupInfo);
  144. if (devconLog != INVALID_HANDLE_VALUE) {
  145. SetFilePointer(devconLog,0,0,FILE_END);
  146. startupInfo.hStdOutput = devconLog;
  147. startupInfo.hStdError = devconLog;
  148. }
  149. PROCESS_INFORMATION processInfo;
  150. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  151. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  152. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" install \"" + _pathToHelpers + WindowsEthernetTapFactory::WINENV.tapDriver + "\" zttap200").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  153. RegCloseKey(nwAdapters);
  154. if (devconLog != INVALID_HANDLE_VALUE)
  155. CloseHandle(devconLog);
  156. throw std::runtime_error(std::string("unable to find or execute devcon at ") + WindowsEthernetTapFactory::WINENV.devcon);
  157. }
  158. WaitForSingleObject(processInfo.hProcess,INFINITE);
  159. CloseHandle(processInfo.hProcess);
  160. CloseHandle(processInfo.hThread);
  161. if (devconLog != INVALID_HANDLE_VALUE)
  162. CloseHandle(devconLog);
  163. // Scan for the new instance by simply looking for taps that weren't originally there...
  164. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  165. DWORD type;
  166. DWORD dataLen;
  167. DWORD subkeyNameLen = sizeof(subkeyName);
  168. DWORD subkeyClassLen = sizeof(subkeyClass);
  169. FILETIME lastWriteTime;
  170. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  171. type = 0;
  172. dataLen = sizeof(data);
  173. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  174. data[dataLen] = '\0';
  175. if (!strnicmp(data,"zttap",5)) {
  176. type = 0;
  177. dataLen = sizeof(data);
  178. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  179. if (existingDeviceInstances.count(std::string(data,dataLen)) == 0) {
  180. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  181. _netCfgInstanceId.assign(data,dataLen);
  182. type = 0;
  183. dataLen = sizeof(data);
  184. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  185. _deviceInstanceId.assign(data,dataLen);
  186. mySubkeyName = subkeyName;
  187. // Disable DHCP by default on newly created devices
  188. HKEY tcpIpInterfaces;
  189. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  190. DWORD enable = 0;
  191. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  192. RegCloseKey(tcpIpInterfaces);
  193. }
  194. break; // found it!
  195. }
  196. }
  197. }
  198. }
  199. } else break; // no more keys or error occurred
  200. }
  201. }
  202. if (_netCfgInstanceId.length() > 0) {
  203. char tmps[64];
  204. unsigned int tmpsl = Utils::snprintf(tmps,sizeof(tmps),"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X",(unsigned int)mac[0],(unsigned int)mac[1],(unsigned int)mac[2],(unsigned int)mac[3],(unsigned int)mac[4],(unsigned int)mac[5]) + 1;
  205. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  206. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  207. DWORD tmp = mtu;
  208. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MTU",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  209. tmp = 0;
  210. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"*NdisDeviceType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  211. tmp = IF_TYPE_ETHERNET_CSMACD;
  212. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"*IfType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  213. if (creatingNewDevice) {
  214. tmp = 0;
  215. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  216. }
  217. RegCloseKey(nwAdapters);
  218. } else {
  219. RegCloseKey(nwAdapters);
  220. throw std::runtime_error("unable to find or create tap adapter");
  221. }
  222. // Convert device GUID junk... blech... is there an easier way to do this?
  223. {
  224. char nobraces[128];
  225. const char *nbtmp1 = _netCfgInstanceId.c_str();
  226. char *nbtmp2 = nobraces;
  227. while (*nbtmp1) {
  228. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  229. *nbtmp2++ = *nbtmp1;
  230. ++nbtmp1;
  231. }
  232. *nbtmp2 = (char)0;
  233. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  234. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  235. }
  236. // Look up interface LUID... why are there (at least) four fucking ways to refer to a network device in Windows?
  237. if (ConvertInterfaceGuidToLuid(&_deviceGuid,&_deviceLuid) != NO_ERROR)
  238. throw std::runtime_error("unable to convert device interface GUID to LUID");
  239. if (friendlyName)
  240. setFriendlyName(friendlyName);
  241. // Start background thread that actually performs I/O
  242. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  243. _thread = Thread::start(this);
  244. // Certain functions can now work (e.g. ips())
  245. _initialized = true;
  246. }
  247. WindowsEthernetTap::~WindowsEthernetTap()
  248. {
  249. _run = false;
  250. ReleaseSemaphore(_injectSemaphore,1,NULL);
  251. Thread::join(_thread);
  252. CloseHandle(_injectSemaphore);
  253. _disableTapDevice();
  254. }
  255. void WindowsEthernetTap::setEnabled(bool en)
  256. {
  257. _enabled = en;
  258. }
  259. bool WindowsEthernetTap::enabled() const
  260. {
  261. return _enabled;
  262. }
  263. bool WindowsEthernetTap::addIP(const InetAddress &ip)
  264. {
  265. if (!_initialized)
  266. return false;
  267. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  268. return false;
  269. std::set<InetAddress> haveIps(ips());
  270. try {
  271. // Add IP to interface at the netlink level if not already assigned.
  272. if (!haveIps.count(ip)) {
  273. MIB_UNICASTIPADDRESS_ROW ipr;
  274. InitializeUnicastIpAddressEntry(&ipr);
  275. if (ip.isV4()) {
  276. ipr.Address.Ipv4.sin_family = AF_INET;
  277. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)ip.rawIpData());
  278. ipr.OnLinkPrefixLength = ip.port();
  279. if (ipr.OnLinkPrefixLength >= 32)
  280. return false;
  281. } else if (ip.isV6()) {
  282. ipr.Address.Ipv6.sin6_family = AF_INET6;
  283. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,ip.rawIpData(),16);
  284. ipr.OnLinkPrefixLength = ip.port();
  285. if (ipr.OnLinkPrefixLength >= 128)
  286. return false;
  287. } else return false;
  288. ipr.PrefixOrigin = IpPrefixOriginManual;
  289. ipr.SuffixOrigin = IpSuffixOriginManual;
  290. ipr.ValidLifetime = 0xffffffff;
  291. ipr.PreferredLifetime = 0xffffffff;
  292. ipr.InterfaceLuid = _deviceLuid;
  293. ipr.InterfaceIndex = _getDeviceIndex();
  294. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  295. haveIps.insert(ip);
  296. } else {
  297. return false;
  298. }
  299. }
  300. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  301. if (std::find(regIps.begin(),regIps.end(),ip.toIpString()) == regIps.end()) {
  302. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  303. regIps.push_back(ip.toIpString());
  304. regSubnetMasks.push_back(ip.netmask().toIpString());
  305. _setRegistryIPv4Value("IPAddress",regIps);
  306. _setRegistryIPv4Value("SubnetMask",regSubnetMasks);
  307. }
  308. //_syncIpsWithRegistry(haveIps,_netCfgInstanceId);
  309. } catch ( ... ) {
  310. return false;
  311. }
  312. return true;
  313. }
  314. bool WindowsEthernetTap::removeIP(const InetAddress &ip)
  315. {
  316. if (!_initialized)
  317. return false;
  318. try {
  319. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  320. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  321. for(DWORD i=0;i<ipt->NumEntries;++i) {
  322. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  323. InetAddress addr;
  324. switch(ipt->Table[i].Address.si_family) {
  325. case AF_INET:
  326. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  327. break;
  328. case AF_INET6:
  329. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  330. if (addr.isLinkLocal())
  331. continue; // can't remove link-local IPv6 addresses
  332. break;
  333. }
  334. if (addr == ip) {
  335. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  336. FreeMibTable(ipt);
  337. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  338. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  339. std::string ipstr(ip.toIpString());
  340. for(std::vector<std::string>::iterator rip(regIps.begin()),rm(regSubnetMasks.begin());((rip!=regIps.end())&&(rm!=regSubnetMasks.end()));++rip,++rm) {
  341. if (*rip == ipstr) {
  342. regIps.erase(rip);
  343. regSubnetMasks.erase(rm);
  344. _setRegistryIPv4Value("IPAddress",regIps);
  345. _setRegistryIPv4Value("SubnetMask",regSubnetMasks);
  346. break;
  347. }
  348. }
  349. return true;
  350. }
  351. }
  352. }
  353. FreeMibTable((PVOID)ipt);
  354. }
  355. } catch ( ... ) {}
  356. return false;
  357. }
  358. std::set<InetAddress> WindowsEthernetTap::ips() const
  359. {
  360. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  361. std::set<InetAddress> addrs;
  362. if (!_initialized)
  363. return addrs;
  364. try {
  365. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  366. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  367. for(DWORD i=0;i<ipt->NumEntries;++i) {
  368. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  369. switch(ipt->Table[i].Address.si_family) {
  370. case AF_INET: {
  371. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  372. if (ip != InetAddress::LO4)
  373. addrs.insert(ip);
  374. } break;
  375. case AF_INET6: {
  376. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  377. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  378. addrs.insert(ip);
  379. } break;
  380. }
  381. }
  382. }
  383. FreeMibTable(ipt);
  384. }
  385. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  386. return addrs;
  387. }
  388. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  389. {
  390. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > (ZT_IF_MTU)))
  391. return;
  392. Mutex::Lock _l(_injectPending_m);
  393. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  394. char *d = _injectPending.back().first.data;
  395. to.copyTo(d,6);
  396. from.copyTo(d + 6,6);
  397. d[12] = (char)((etherType >> 8) & 0xff);
  398. d[13] = (char)(etherType & 0xff);
  399. memcpy(d + 14,data,len);
  400. ReleaseSemaphore(_injectSemaphore,1,NULL);
  401. }
  402. std::string WindowsEthernetTap::deviceName() const
  403. {
  404. char tmp[1024];
  405. if (ConvertInterfaceLuidToNameA(&_deviceLuid,tmp,sizeof(tmp)) != NO_ERROR)
  406. return std::string("[ConvertInterfaceLuidToName() failed]");
  407. return std::string(tmp);
  408. }
  409. void WindowsEthernetTap::setFriendlyName(const char *dn)
  410. {
  411. if (!_initialized)
  412. return;
  413. HKEY ifp;
  414. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,(std::string("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\") + _netCfgInstanceId).c_str(),0,KEY_READ|KEY_WRITE,&ifp) == ERROR_SUCCESS) {
  415. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  416. RegCloseKey(ifp);
  417. }
  418. }
  419. bool WindowsEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  420. {
  421. if (!_initialized)
  422. return false;
  423. HANDLE t = _tap;
  424. if (t == INVALID_HANDLE_VALUE)
  425. return false;
  426. std::set<MulticastGroup> newGroups;
  427. // Ensure that groups are added for each IP... this handles the MAC:ADI
  428. // groups that are created from IPv4 addresses. Some of these may end
  429. // up being duplicates of what the IOCTL returns but that's okay since
  430. // the set<> will filter that.
  431. std::set<InetAddress> ipaddrs(ips());
  432. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  433. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  434. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  435. // level... something Windows does not seem to expose ordinarily. This lets
  436. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  437. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  438. DWORD bytesReturned = 0;
  439. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  440. MAC mac;
  441. DWORD i = 0;
  442. while ((i + 6) <= bytesReturned) {
  443. mac.setTo(mcastbuf + i,6);
  444. i += 6;
  445. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  446. // exclude the nulls that may be returned or any other junk Windows puts in there
  447. newGroups.insert(MulticastGroup(mac,0));
  448. }
  449. }
  450. }
  451. bool changed = false;
  452. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  453. if (!groups.count(*mg)) {
  454. groups.insert(*mg);
  455. changed = true;
  456. }
  457. }
  458. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  459. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  460. groups.erase(mg++);
  461. changed = true;
  462. } else ++mg;
  463. }
  464. return changed;
  465. }
  466. void WindowsEthernetTap::threadMain()
  467. throw()
  468. {
  469. char tapPath[256];
  470. OVERLAPPED tapOvlRead,tapOvlWrite;
  471. HANDLE wait4[3];
  472. char *tapReadBuf = (char *)0;
  473. // Shouldn't be needed, but Windows does not overcommit. This Windows
  474. // tap code is defensive to schizoid paranoia degrees.
  475. while (!tapReadBuf) {
  476. tapReadBuf = (char *)::malloc(ZT_IF_MTU + 32);
  477. if (!tapReadBuf)
  478. Sleep(1000);
  479. }
  480. // Tap is in this weird Windows global pseudo file space
  481. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  482. /* More insanity: repetatively try to enable/disable tap device. The first
  483. * time we succeed, close it and do it again. This is to fix a driver init
  484. * bug that seems to be extremely non-deterministic and to only occur after
  485. * headless MSI upgrade. It cannot be reproduced in any other circumstance.
  486. *
  487. * Eventually when ZeroTier has actual money we will have someone create an
  488. * NDIS6 tap driver. Yes, we'll likely be cool and open source it. */
  489. bool throwOneAway = true;
  490. while (_run) {
  491. _disableTapDevice();
  492. Sleep(250);
  493. if (!_enableTapDevice()) {
  494. ::free(tapReadBuf);
  495. _enabled = false;
  496. return; // only happens if devcon is missing or totally fails
  497. }
  498. Sleep(250);
  499. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  500. if (_tap == INVALID_HANDLE_VALUE) {
  501. Sleep(500);
  502. continue;
  503. }
  504. {
  505. uint32_t tmpi = 1;
  506. DWORD bytesReturned = 0;
  507. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  508. bytesReturned = 0;
  509. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  510. }
  511. {
  512. #ifdef ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  513. /* This inserts a fake default route and a fake ARP entry, forcing
  514. * Windows to detect this as a "real" network and apply proper
  515. * firewall rules.
  516. *
  517. * This hack is completely stupid, but Windows made me do it
  518. * by being broken and insane.
  519. *
  520. * Background: Windows tries to detect its network location by
  521. * matching it to the ARP address of the default route. Networks
  522. * without default routes are "unidentified networks" and cannot
  523. * have their firewall classification changed by the user (easily).
  524. *
  525. * Yes, you read that right.
  526. *
  527. * The common workaround is to set *NdisDeviceType to 1, which
  528. * totally disables all Windows firewall functionality. This is
  529. * the answer you'll find on most forums for things like OpenVPN.
  530. *
  531. * Yes, you read that right.
  532. *
  533. * The default route workaround is also known, but for this to
  534. * work there must be a known default IP that resolves to a known
  535. * ARP address. This works for an OpenVPN tunnel, but not here
  536. * because this isn't a tunnel. It's a mesh. There is no "other
  537. * end," or any other known always on IP.
  538. *
  539. * So let's make a fake one and shove it in there along with its
  540. * fake static ARP entry. Also makes it instant-on and static.
  541. *
  542. * We'll have to see what DHCP does with this. In the future we
  543. * probably will not want to do this on DHCP-enabled networks, so
  544. * when we enable DHCP we will go in and yank this wacko hacko from
  545. * the routing table before doing so.
  546. *
  547. * Like Jesse Pinkman would say: "YEEEEAAH BITCH!" */
  548. const uint32_t fakeIp = htonl(0x19fffffe); // 25.255.255.254 -- unrouted IPv4 block
  549. for(int i=0;i<8;++i) {
  550. MIB_IPNET_ROW2 ipnr;
  551. memset(&ipnr,0,sizeof(ipnr));
  552. ipnr.Address.si_family = AF_INET;
  553. ipnr.Address.Ipv4.sin_addr.s_addr = fakeIp;
  554. ipnr.InterfaceLuid.Value = _deviceLuid.Value;
  555. ipnr.PhysicalAddress[0] = _mac[0] ^ 0x10; // just make something up that's consistent and not part of this net
  556. ipnr.PhysicalAddress[1] = 0x00;
  557. ipnr.PhysicalAddress[2] = (UCHAR)((_deviceGuid.Data1 >> 24) & 0xff);
  558. ipnr.PhysicalAddress[3] = (UCHAR)((_deviceGuid.Data1 >> 16) & 0xff);
  559. ipnr.PhysicalAddress[4] = (UCHAR)((_deviceGuid.Data1 >> 8) & 0xff);
  560. ipnr.PhysicalAddress[5] = (UCHAR)(_deviceGuid.Data1 & 0xff);
  561. ipnr.PhysicalAddressLength = 6;
  562. ipnr.State = NlnsPermanent;
  563. ipnr.IsRouter = 1;
  564. ipnr.IsUnreachable = 0;
  565. ipnr.ReachabilityTime.LastReachable = 0x0fffffff;
  566. ipnr.ReachabilityTime.LastUnreachable = 1;
  567. DWORD result = CreateIpNetEntry2(&ipnr);
  568. if (result != NO_ERROR)
  569. Sleep(500);
  570. else break;
  571. }
  572. for(int i=0;i<8;++i) {
  573. MIB_IPFORWARD_ROW2 nr;
  574. memset(&nr,0,sizeof(nr));
  575. InitializeIpForwardEntry(&nr);
  576. nr.InterfaceLuid.Value = _deviceLuid.Value;
  577. nr.DestinationPrefix.Prefix.si_family = AF_INET; // rest is left as 0.0.0.0/0
  578. nr.NextHop.si_family = AF_INET;
  579. nr.NextHop.Ipv4.sin_addr.s_addr = fakeIp;
  580. nr.Metric = 9999; // do not use as real default route
  581. nr.Protocol = MIB_IPPROTO_NETMGMT;
  582. DWORD result = CreateIpForwardEntry2(&nr);
  583. if (result != NO_ERROR)
  584. Sleep(500);
  585. else break;
  586. }
  587. #endif
  588. }
  589. if (throwOneAway) {
  590. throwOneAway = false;
  591. CloseHandle(_tap);
  592. _tap = INVALID_HANDLE_VALUE;
  593. Sleep(1000);
  594. continue;
  595. } else break;
  596. }
  597. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  598. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  599. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  600. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  601. wait4[0] = _injectSemaphore;
  602. wait4[1] = tapOvlRead.hEvent;
  603. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  604. // Start overlapped read, which is always active
  605. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  606. bool writeInProgress = false;
  607. for(;;) {
  608. if (!_run) break;
  609. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,5000,TRUE);
  610. if (!_run) break;
  611. if ((r == WAIT_TIMEOUT)||(r == WAIT_FAILED))
  612. continue;
  613. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  614. DWORD bytesRead = 0;
  615. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  616. if ((bytesRead > 14)&&(_enabled)) {
  617. MAC to(tapReadBuf,6);
  618. MAC from(tapReadBuf + 6,6);
  619. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  620. try {
  621. Buffer<4096> tmp(tapReadBuf + 14,bytesRead - 14);
  622. _handler(_arg,from,to,etherType,tmp);
  623. } catch ( ... ) {} // handlers should not throw
  624. }
  625. }
  626. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  627. }
  628. if (writeInProgress) {
  629. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  630. writeInProgress = false;
  631. _injectPending_m.lock();
  632. _injectPending.pop();
  633. } else continue; // still writing, so skip code below and wait
  634. } else _injectPending_m.lock();
  635. if (!_injectPending.empty()) {
  636. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  637. writeInProgress = true;
  638. }
  639. _injectPending_m.unlock();
  640. }
  641. CancelIo(_tap);
  642. CloseHandle(tapOvlRead.hEvent);
  643. CloseHandle(tapOvlWrite.hEvent);
  644. CloseHandle(_tap);
  645. _tap = INVALID_HANDLE_VALUE;
  646. ::free(tapReadBuf);
  647. }
  648. bool WindowsEthernetTap::_disableTapDevice()
  649. {
  650. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  651. if (devconLog != INVALID_HANDLE_VALUE)
  652. SetFilePointer(devconLog,0,0,FILE_END);
  653. STARTUPINFOA startupInfo;
  654. startupInfo.cb = sizeof(startupInfo);
  655. if (devconLog != INVALID_HANDLE_VALUE) {
  656. startupInfo.hStdOutput = devconLog;
  657. startupInfo.hStdError = devconLog;
  658. }
  659. PROCESS_INFORMATION processInfo;
  660. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  661. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  662. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" disable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  663. if (devconLog != INVALID_HANDLE_VALUE)
  664. CloseHandle(devconLog);
  665. return false;
  666. }
  667. WaitForSingleObject(processInfo.hProcess,INFINITE);
  668. CloseHandle(processInfo.hProcess);
  669. CloseHandle(processInfo.hThread);
  670. if (devconLog != INVALID_HANDLE_VALUE)
  671. CloseHandle(devconLog);
  672. return true;
  673. }
  674. bool WindowsEthernetTap::_enableTapDevice()
  675. {
  676. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  677. if (devconLog != INVALID_HANDLE_VALUE)
  678. SetFilePointer(devconLog,0,0,FILE_END);
  679. STARTUPINFOA startupInfo;
  680. startupInfo.cb = sizeof(startupInfo);
  681. if (devconLog != INVALID_HANDLE_VALUE) {
  682. startupInfo.hStdOutput = devconLog;
  683. startupInfo.hStdError = devconLog;
  684. }
  685. PROCESS_INFORMATION processInfo;
  686. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  687. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  688. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" enable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  689. if (devconLog != INVALID_HANDLE_VALUE)
  690. CloseHandle(devconLog);
  691. return false;
  692. }
  693. WaitForSingleObject(processInfo.hProcess,INFINITE);
  694. CloseHandle(processInfo.hProcess);
  695. CloseHandle(processInfo.hThread);
  696. if (devconLog != INVALID_HANDLE_VALUE)
  697. CloseHandle(devconLog);
  698. return true;
  699. }
  700. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  701. {
  702. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  703. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  704. throw std::runtime_error("GetIfTable2Ex() failed");
  705. for(ULONG i=0;i<ift->NumEntries;++i) {
  706. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  707. NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
  708. FreeMibTable(ift);
  709. return idx;
  710. }
  711. }
  712. FreeMibTable(&ift);
  713. throw std::runtime_error("interface not found");
  714. }
  715. std::vector<std::string> WindowsEthernetTap::_getRegistryIPv4Value(const char *regKey)
  716. {
  717. std::vector<std::string> value;
  718. HKEY tcpIpInterfaces;
  719. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  720. char buf[16384];
  721. DWORD len = sizeof(buf);
  722. DWORD kt = REG_MULTI_SZ;
  723. if (RegGetValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,0,&kt,&buf,&len) == ERROR_SUCCESS) {
  724. switch(kt) {
  725. case REG_SZ:
  726. if (len > 0)
  727. value.push_back(std::string(buf));
  728. break;
  729. case REG_MULTI_SZ: {
  730. for(DWORD k=0,s=0;k<len;++k) {
  731. if (!buf[k]) {
  732. if (s < k) {
  733. value.push_back(std::string(buf + s));
  734. s = k + 1;
  735. } else break;
  736. }
  737. }
  738. } break;
  739. }
  740. }
  741. RegCloseKey(tcpIpInterfaces);
  742. }
  743. return value;
  744. }
  745. void WindowsEthernetTap::_setRegistryIPv4Value(const char *regKey,const std::vector<std::string> &value)
  746. {
  747. std::string regMulti;
  748. for(std::vector<std::string>::const_iterator s(value.begin());s!=value.end();++s) {
  749. regMulti.append(*s);
  750. regMulti.push_back((char)0);
  751. }
  752. HKEY tcpIpInterfaces;
  753. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  754. if (regMulti.length() > 0) {
  755. regMulti.push_back((char)0);
  756. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,REG_MULTI_SZ,regMulti.data(),(DWORD)regMulti.length());
  757. } else {
  758. RegDeleteKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey);
  759. }
  760. RegCloseKey(tcpIpInterfaces);
  761. }
  762. }
  763. } // namespace ZeroTier