WindowsEthernetTap.cpp 29 KB

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