WindowsEthernetTap.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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 "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. bool WindowsEthernetTap::injectPacketFromHost(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  467. {
  468. return false;
  469. }
  470. void WindowsEthernetTap::threadMain()
  471. throw()
  472. {
  473. char tapPath[256];
  474. OVERLAPPED tapOvlRead,tapOvlWrite;
  475. HANDLE wait4[3];
  476. char *tapReadBuf = (char *)0;
  477. // Shouldn't be needed, but Windows does not overcommit. This Windows
  478. // tap code is defensive to schizoid paranoia degrees.
  479. while (!tapReadBuf) {
  480. tapReadBuf = (char *)::malloc(ZT_IF_MTU + 32);
  481. if (!tapReadBuf)
  482. Sleep(1000);
  483. }
  484. // Tap is in this weird Windows global pseudo file space
  485. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  486. /* More insanity: repetatively try to enable/disable tap device. The first
  487. * time we succeed, close it and do it again. This is to fix a driver init
  488. * bug that seems to be extremely non-deterministic and to only occur after
  489. * headless MSI upgrade. It cannot be reproduced in any other circumstance.
  490. *
  491. * Eventually when ZeroTier has actual money we will have someone create an
  492. * NDIS6 tap driver. Yes, we'll likely be cool and open source it. */
  493. bool throwOneAway = true;
  494. while (_run) {
  495. _disableTapDevice();
  496. Sleep(250);
  497. if (!_enableTapDevice()) {
  498. ::free(tapReadBuf);
  499. _enabled = false;
  500. return; // only happens if devcon is missing or totally fails
  501. }
  502. Sleep(250);
  503. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  504. if (_tap == INVALID_HANDLE_VALUE) {
  505. Sleep(500);
  506. continue;
  507. }
  508. {
  509. uint32_t tmpi = 1;
  510. DWORD bytesReturned = 0;
  511. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  512. bytesReturned = 0;
  513. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  514. }
  515. {
  516. #ifdef ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  517. /* This inserts a fake default route and a fake ARP entry, forcing
  518. * Windows to detect this as a "real" network and apply proper
  519. * firewall rules.
  520. *
  521. * This hack is completely stupid, but Windows made me do it
  522. * by being broken and insane.
  523. *
  524. * Background: Windows tries to detect its network location by
  525. * matching it to the ARP address of the default route. Networks
  526. * without default routes are "unidentified networks" and cannot
  527. * have their firewall classification changed by the user (easily).
  528. *
  529. * Yes, you read that right.
  530. *
  531. * The common workaround is to set *NdisDeviceType to 1, which
  532. * totally disables all Windows firewall functionality. This is
  533. * the answer you'll find on most forums for things like OpenVPN.
  534. *
  535. * Yes, you read that right.
  536. *
  537. * The default route workaround is also known, but for this to
  538. * work there must be a known default IP that resolves to a known
  539. * ARP address. This works for an OpenVPN tunnel, but not here
  540. * because this isn't a tunnel. It's a mesh. There is no "other
  541. * end," or any other known always on IP.
  542. *
  543. * So let's make a fake one and shove it in there along with its
  544. * fake static ARP entry. Also makes it instant-on and static.
  545. *
  546. * We'll have to see what DHCP does with this. In the future we
  547. * probably will not want to do this on DHCP-enabled networks, so
  548. * when we enable DHCP we will go in and yank this wacko hacko from
  549. * the routing table before doing so.
  550. *
  551. * Like Jesse Pinkman would say: "YEEEEAAH BITCH!" */
  552. const uint32_t fakeIp = htonl(0x19fffffe); // 25.255.255.254 -- unrouted IPv4 block
  553. for(int i=0;i<8;++i) {
  554. MIB_IPNET_ROW2 ipnr;
  555. memset(&ipnr,0,sizeof(ipnr));
  556. ipnr.Address.si_family = AF_INET;
  557. ipnr.Address.Ipv4.sin_addr.s_addr = fakeIp;
  558. ipnr.InterfaceLuid.Value = _deviceLuid.Value;
  559. ipnr.PhysicalAddress[0] = _mac[0] ^ 0x10; // just make something up that's consistent and not part of this net
  560. ipnr.PhysicalAddress[1] = 0x00;
  561. ipnr.PhysicalAddress[2] = (UCHAR)((_deviceGuid.Data1 >> 24) & 0xff);
  562. ipnr.PhysicalAddress[3] = (UCHAR)((_deviceGuid.Data1 >> 16) & 0xff);
  563. ipnr.PhysicalAddress[4] = (UCHAR)((_deviceGuid.Data1 >> 8) & 0xff);
  564. ipnr.PhysicalAddress[5] = (UCHAR)(_deviceGuid.Data1 & 0xff);
  565. ipnr.PhysicalAddressLength = 6;
  566. ipnr.State = NlnsPermanent;
  567. ipnr.IsRouter = 1;
  568. ipnr.IsUnreachable = 0;
  569. ipnr.ReachabilityTime.LastReachable = 0x0fffffff;
  570. ipnr.ReachabilityTime.LastUnreachable = 1;
  571. DWORD result = CreateIpNetEntry2(&ipnr);
  572. if (result != NO_ERROR)
  573. Sleep(500);
  574. else break;
  575. }
  576. for(int i=0;i<8;++i) {
  577. MIB_IPFORWARD_ROW2 nr;
  578. memset(&nr,0,sizeof(nr));
  579. InitializeIpForwardEntry(&nr);
  580. nr.InterfaceLuid.Value = _deviceLuid.Value;
  581. nr.DestinationPrefix.Prefix.si_family = AF_INET; // rest is left as 0.0.0.0/0
  582. nr.NextHop.si_family = AF_INET;
  583. nr.NextHop.Ipv4.sin_addr.s_addr = fakeIp;
  584. nr.Metric = 9999; // do not use as real default route
  585. nr.Protocol = MIB_IPPROTO_NETMGMT;
  586. DWORD result = CreateIpForwardEntry2(&nr);
  587. if (result != NO_ERROR)
  588. Sleep(500);
  589. else break;
  590. }
  591. #endif
  592. }
  593. if (throwOneAway) {
  594. throwOneAway = false;
  595. CloseHandle(_tap);
  596. _tap = INVALID_HANDLE_VALUE;
  597. Sleep(1000);
  598. continue;
  599. } else break;
  600. }
  601. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  602. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  603. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  604. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  605. wait4[0] = _injectSemaphore;
  606. wait4[1] = tapOvlRead.hEvent;
  607. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  608. // Start overlapped read, which is always active
  609. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  610. bool writeInProgress = false;
  611. for(;;) {
  612. if (!_run) break;
  613. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,5000,TRUE);
  614. if (!_run) break;
  615. if ((r == WAIT_TIMEOUT)||(r == WAIT_FAILED))
  616. continue;
  617. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  618. DWORD bytesRead = 0;
  619. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  620. if ((bytesRead > 14)&&(_enabled)) {
  621. MAC to(tapReadBuf,6);
  622. MAC from(tapReadBuf + 6,6);
  623. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  624. try {
  625. Buffer<4096> tmp(tapReadBuf + 14,bytesRead - 14);
  626. _handler(_arg,from,to,etherType,tmp);
  627. } catch ( ... ) {} // handlers should not throw
  628. }
  629. }
  630. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  631. }
  632. if (writeInProgress) {
  633. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  634. writeInProgress = false;
  635. _injectPending_m.lock();
  636. _injectPending.pop();
  637. } else continue; // still writing, so skip code below and wait
  638. } else _injectPending_m.lock();
  639. if (!_injectPending.empty()) {
  640. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  641. writeInProgress = true;
  642. }
  643. _injectPending_m.unlock();
  644. }
  645. CancelIo(_tap);
  646. CloseHandle(tapOvlRead.hEvent);
  647. CloseHandle(tapOvlWrite.hEvent);
  648. CloseHandle(_tap);
  649. _tap = INVALID_HANDLE_VALUE;
  650. ::free(tapReadBuf);
  651. }
  652. bool WindowsEthernetTap::_disableTapDevice()
  653. {
  654. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  655. if (devconLog != INVALID_HANDLE_VALUE)
  656. SetFilePointer(devconLog,0,0,FILE_END);
  657. STARTUPINFOA startupInfo;
  658. startupInfo.cb = sizeof(startupInfo);
  659. if (devconLog != INVALID_HANDLE_VALUE) {
  660. startupInfo.hStdOutput = devconLog;
  661. startupInfo.hStdError = devconLog;
  662. }
  663. PROCESS_INFORMATION processInfo;
  664. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  665. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  666. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" disable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  667. if (devconLog != INVALID_HANDLE_VALUE)
  668. CloseHandle(devconLog);
  669. return false;
  670. }
  671. WaitForSingleObject(processInfo.hProcess,INFINITE);
  672. CloseHandle(processInfo.hProcess);
  673. CloseHandle(processInfo.hThread);
  674. if (devconLog != INVALID_HANDLE_VALUE)
  675. CloseHandle(devconLog);
  676. return true;
  677. }
  678. bool WindowsEthernetTap::_enableTapDevice()
  679. {
  680. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  681. if (devconLog != INVALID_HANDLE_VALUE)
  682. SetFilePointer(devconLog,0,0,FILE_END);
  683. STARTUPINFOA startupInfo;
  684. startupInfo.cb = sizeof(startupInfo);
  685. if (devconLog != INVALID_HANDLE_VALUE) {
  686. startupInfo.hStdOutput = devconLog;
  687. startupInfo.hStdError = devconLog;
  688. }
  689. PROCESS_INFORMATION processInfo;
  690. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  691. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  692. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" enable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  693. if (devconLog != INVALID_HANDLE_VALUE)
  694. CloseHandle(devconLog);
  695. return false;
  696. }
  697. WaitForSingleObject(processInfo.hProcess,INFINITE);
  698. CloseHandle(processInfo.hProcess);
  699. CloseHandle(processInfo.hThread);
  700. if (devconLog != INVALID_HANDLE_VALUE)
  701. CloseHandle(devconLog);
  702. return true;
  703. }
  704. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  705. {
  706. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  707. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  708. throw std::runtime_error("GetIfTable2Ex() failed");
  709. for(ULONG i=0;i<ift->NumEntries;++i) {
  710. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  711. NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
  712. FreeMibTable(ift);
  713. return idx;
  714. }
  715. }
  716. FreeMibTable(&ift);
  717. throw std::runtime_error("interface not found");
  718. }
  719. std::vector<std::string> WindowsEthernetTap::_getRegistryIPv4Value(const char *regKey)
  720. {
  721. std::vector<std::string> value;
  722. HKEY tcpIpInterfaces;
  723. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  724. char buf[16384];
  725. DWORD len = sizeof(buf);
  726. DWORD kt = REG_MULTI_SZ;
  727. if (RegGetValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,0,&kt,&buf,&len) == ERROR_SUCCESS) {
  728. switch(kt) {
  729. case REG_SZ:
  730. if (len > 0)
  731. value.push_back(std::string(buf));
  732. break;
  733. case REG_MULTI_SZ: {
  734. for(DWORD k=0,s=0;k<len;++k) {
  735. if (!buf[k]) {
  736. if (s < k) {
  737. value.push_back(std::string(buf + s));
  738. s = k + 1;
  739. } else break;
  740. }
  741. }
  742. } break;
  743. }
  744. }
  745. RegCloseKey(tcpIpInterfaces);
  746. }
  747. return value;
  748. }
  749. void WindowsEthernetTap::_setRegistryIPv4Value(const char *regKey,const std::vector<std::string> &value)
  750. {
  751. std::string regMulti;
  752. for(std::vector<std::string>::const_iterator s(value.begin());s!=value.end();++s) {
  753. regMulti.append(*s);
  754. regMulti.push_back((char)0);
  755. }
  756. HKEY tcpIpInterfaces;
  757. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  758. if (regMulti.length() > 0) {
  759. regMulti.push_back((char)0);
  760. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,REG_MULTI_SZ,regMulti.data(),(DWORD)regMulti.length());
  761. } else {
  762. RegDeleteKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey);
  763. }
  764. RegCloseKey(tcpIpInterfaces);
  765. }
  766. }
  767. } // namespace ZeroTier