WindowsEthernetTap.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 = NDIS_DEVICE_TYPE_ENDPOINT;
  210. tmp = 0;
  211. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"*NdisDeviceType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  212. tmp = IF_TYPE_ETHERNET_CSMACD;
  213. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"*IfType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  214. if (creatingNewDevice) {
  215. tmp = 0;
  216. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  217. }
  218. RegCloseKey(nwAdapters);
  219. } else {
  220. RegCloseKey(nwAdapters);
  221. throw std::runtime_error("unable to find or create tap adapter");
  222. }
  223. // Convert device GUID junk... blech... is there an easier way to do this?
  224. {
  225. char nobraces[128];
  226. const char *nbtmp1 = _netCfgInstanceId.c_str();
  227. char *nbtmp2 = nobraces;
  228. while (*nbtmp1) {
  229. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  230. *nbtmp2++ = *nbtmp1;
  231. ++nbtmp1;
  232. }
  233. *nbtmp2 = (char)0;
  234. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  235. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  236. }
  237. // Look up interface LUID... why are there (at least) four fucking ways to refer to a network device in Windows?
  238. if (ConvertInterfaceGuidToLuid(&_deviceGuid,&_deviceLuid) != NO_ERROR)
  239. throw std::runtime_error("unable to convert device interface GUID to LUID");
  240. if (friendlyName)
  241. setFriendlyName(friendlyName);
  242. // Start background thread that actually performs I/O
  243. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  244. _thread = Thread::start(this);
  245. // Certain functions can now work (e.g. ips())
  246. _initialized = true;
  247. }
  248. WindowsEthernetTap::~WindowsEthernetTap()
  249. {
  250. _run = false;
  251. ReleaseSemaphore(_injectSemaphore,1,NULL);
  252. Thread::join(_thread);
  253. CloseHandle(_injectSemaphore);
  254. _disableTapDevice();
  255. }
  256. void WindowsEthernetTap::setEnabled(bool en)
  257. {
  258. _enabled = en;
  259. }
  260. bool WindowsEthernetTap::enabled() const
  261. {
  262. return _enabled;
  263. }
  264. bool WindowsEthernetTap::addIP(const InetAddress &ip)
  265. {
  266. if (!_initialized)
  267. return false;
  268. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  269. return false;
  270. std::set<InetAddress> haveIps(ips());
  271. try {
  272. // Add IP to interface at the netlink level if not already assigned.
  273. if (!haveIps.count(ip)) {
  274. MIB_UNICASTIPADDRESS_ROW ipr;
  275. InitializeUnicastIpAddressEntry(&ipr);
  276. if (ip.isV4()) {
  277. ipr.Address.Ipv4.sin_family = AF_INET;
  278. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)ip.rawIpData());
  279. ipr.OnLinkPrefixLength = ip.port();
  280. if (ipr.OnLinkPrefixLength >= 32)
  281. return false;
  282. } else if (ip.isV6()) {
  283. ipr.Address.Ipv6.sin6_family = AF_INET6;
  284. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,ip.rawIpData(),16);
  285. ipr.OnLinkPrefixLength = ip.port();
  286. if (ipr.OnLinkPrefixLength >= 128)
  287. return false;
  288. } else return false;
  289. ipr.PrefixOrigin = IpPrefixOriginManual;
  290. ipr.SuffixOrigin = IpSuffixOriginManual;
  291. ipr.ValidLifetime = 0xffffffff;
  292. ipr.PreferredLifetime = 0xffffffff;
  293. ipr.InterfaceLuid = _deviceLuid;
  294. ipr.InterfaceIndex = _getDeviceIndex();
  295. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  296. haveIps.insert(ip);
  297. } else {
  298. return false;
  299. }
  300. }
  301. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  302. if (std::find(regIps.begin(),regIps.end(),ip.toIpString()) == regIps.end()) {
  303. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  304. regIps.push_back(ip.toIpString());
  305. regSubnetMasks.push_back(ip.netmask().toIpString());
  306. _setRegistryIPv4Value("IPAddress",regIps);
  307. _setRegistryIPv4Value("SubnetMask",regSubnetMasks);
  308. }
  309. //_syncIpsWithRegistry(haveIps,_netCfgInstanceId);
  310. } catch ( ... ) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. bool WindowsEthernetTap::removeIP(const InetAddress &ip)
  316. {
  317. if (!_initialized)
  318. return false;
  319. try {
  320. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  321. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  322. for(DWORD i=0;i<ipt->NumEntries;++i) {
  323. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  324. InetAddress addr;
  325. switch(ipt->Table[i].Address.si_family) {
  326. case AF_INET:
  327. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  328. break;
  329. case AF_INET6:
  330. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  331. if (addr.isLinkLocal())
  332. continue; // can't remove link-local IPv6 addresses
  333. break;
  334. }
  335. if (addr == ip) {
  336. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  337. FreeMibTable(ipt);
  338. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  339. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  340. std::string ipstr(ip.toIpString());
  341. for(std::vector<std::string>::iterator rip(regIps.begin()),rm(regSubnetMasks.begin());((rip!=regIps.end())&&(rm!=regSubnetMasks.end()));++rip,++rm) {
  342. if (*rip == ipstr) {
  343. regIps.erase(rip);
  344. regSubnetMasks.erase(rm);
  345. _setRegistryIPv4Value("IPAddress",regIps);
  346. _setRegistryIPv4Value("SubnetMask",regSubnetMasks);
  347. break;
  348. }
  349. }
  350. return true;
  351. }
  352. }
  353. }
  354. FreeMibTable((PVOID)ipt);
  355. }
  356. } catch ( ... ) {}
  357. return false;
  358. }
  359. std::set<InetAddress> WindowsEthernetTap::ips() const
  360. {
  361. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  362. std::set<InetAddress> addrs;
  363. if (!_initialized)
  364. return addrs;
  365. try {
  366. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  367. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  368. for(DWORD i=0;i<ipt->NumEntries;++i) {
  369. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  370. switch(ipt->Table[i].Address.si_family) {
  371. case AF_INET: {
  372. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  373. if (ip != InetAddress::LO4)
  374. addrs.insert(ip);
  375. } break;
  376. case AF_INET6: {
  377. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  378. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  379. addrs.insert(ip);
  380. } break;
  381. }
  382. }
  383. }
  384. FreeMibTable(ipt);
  385. }
  386. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  387. return addrs;
  388. }
  389. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  390. {
  391. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > (ZT_IF_MTU)))
  392. return;
  393. Mutex::Lock _l(_injectPending_m);
  394. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  395. char *d = _injectPending.back().first.data;
  396. to.copyTo(d,6);
  397. from.copyTo(d + 6,6);
  398. d[12] = (char)((etherType >> 8) & 0xff);
  399. d[13] = (char)(etherType & 0xff);
  400. memcpy(d + 14,data,len);
  401. ReleaseSemaphore(_injectSemaphore,1,NULL);
  402. }
  403. std::string WindowsEthernetTap::deviceName() const
  404. {
  405. char tmp[1024];
  406. if (ConvertInterfaceLuidToNameA(&_deviceLuid,tmp,sizeof(tmp)) != NO_ERROR)
  407. return std::string("[ConvertInterfaceLuidToName() failed]");
  408. return std::string(tmp);
  409. }
  410. void WindowsEthernetTap::setFriendlyName(const char *dn)
  411. {
  412. if (!_initialized)
  413. return;
  414. HKEY ifp;
  415. 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) {
  416. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  417. RegCloseKey(ifp);
  418. }
  419. }
  420. bool WindowsEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  421. {
  422. if (!_initialized)
  423. return false;
  424. HANDLE t = _tap;
  425. if (t == INVALID_HANDLE_VALUE)
  426. return false;
  427. std::set<MulticastGroup> newGroups;
  428. // Ensure that groups are added for each IP... this handles the MAC:ADI
  429. // groups that are created from IPv4 addresses. Some of these may end
  430. // up being duplicates of what the IOCTL returns but that's okay since
  431. // the set<> will filter that.
  432. std::set<InetAddress> ipaddrs(ips());
  433. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  434. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  435. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  436. // level... something Windows does not seem to expose ordinarily. This lets
  437. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  438. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  439. DWORD bytesReturned = 0;
  440. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  441. MAC mac;
  442. DWORD i = 0;
  443. while ((i + 6) <= bytesReturned) {
  444. mac.setTo(mcastbuf + i,6);
  445. i += 6;
  446. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  447. // exclude the nulls that may be returned or any other junk Windows puts in there
  448. newGroups.insert(MulticastGroup(mac,0));
  449. }
  450. }
  451. }
  452. bool changed = false;
  453. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  454. if (!groups.count(*mg)) {
  455. groups.insert(*mg);
  456. changed = true;
  457. }
  458. }
  459. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  460. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  461. groups.erase(mg++);
  462. changed = true;
  463. } else ++mg;
  464. }
  465. return changed;
  466. }
  467. void WindowsEthernetTap::threadMain()
  468. throw()
  469. {
  470. char tapPath[256];
  471. OVERLAPPED tapOvlRead,tapOvlWrite;
  472. HANDLE wait4[3];
  473. char *tapReadBuf = (char *)0;
  474. // Shouldn't be needed, but Windows does not overcommit. This Windows
  475. // tap code is defensive to schizoid paranoia degrees.
  476. while (!tapReadBuf) {
  477. tapReadBuf = (char *)::malloc(ZT_IF_MTU + 32);
  478. if (!tapReadBuf)
  479. Sleep(1000);
  480. }
  481. // Tap is in this weird Windows global pseudo file space
  482. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  483. /* More insanity: repetatively try to enable/disable tap device. The first
  484. * time we succeed, close it and do it again. This is to fix a driver init
  485. * bug that seems to be extremely non-deterministic and to only occur after
  486. * headless MSI upgrade. It cannot be reproduced in any other circumstance.
  487. *
  488. * Eventually when ZeroTier has actual money we will have someone create an
  489. * NDIS6 tap driver. Yes, we'll likely be cool and open source it. */
  490. bool throwOneAway = true;
  491. while (_run) {
  492. _disableTapDevice();
  493. Sleep(250);
  494. if (!_enableTapDevice()) {
  495. ::free(tapReadBuf);
  496. _enabled = false;
  497. return; // only happens if devcon is missing or totally fails
  498. }
  499. Sleep(250);
  500. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  501. if (_tap == INVALID_HANDLE_VALUE) {
  502. Sleep(500);
  503. continue;
  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. if (throwOneAway) {
  509. throwOneAway = false;
  510. CloseHandle(_tap);
  511. _tap = INVALID_HANDLE_VALUE;
  512. Sleep(250);
  513. continue;
  514. } else break;
  515. }
  516. /* code not currently used, but keep it around cause it was hard to figure out...
  517. CoInitializeEx(NULL,COINIT_MULTITHREADED);
  518. CComPtr<INetworkListManager> nlm;
  519. nlm.CoCreateInstance(CLSID_NetworkListManager);
  520. if (nlm) {
  521. for(int i=0;i<8;++i) { // wait up to 8s for the NLM (network awareness) to find and initialize its awareness of our new network
  522. CComPtr<IEnumNetworks> nlmNets;
  523. bool foundMyNet = false;
  524. if (SUCCEEDED(nlm->GetNetworks(NLM_ENUM_NETWORK_ALL,&nlmNets))) {
  525. DWORD dwReturn = 0;
  526. while (!foundMyNet) {
  527. CComPtr<INetwork> nlmNet;
  528. HRESULT hr = nlmNets->Next(1,&nlmNet,&dwReturn);
  529. if ((hr == S_OK)&&(dwReturn > 0)&&(nlmNet)) {
  530. CComPtr<IEnumNetworkConnections> nlmNetConns;
  531. if (SUCCEEDED(nlmNet->GetNetworkConnections(&nlmNetConns))) {
  532. for(;;) {
  533. CComPtr<INetworkConnection> nlmNetConn;
  534. hr = nlmNetConns->Next(1,&nlmNetConn,&dwReturn);
  535. if ((hr == S_OK)&&(dwReturn > 0)&&(nlmNetConn)) {
  536. GUID netAdapterId;
  537. nlmNetConn->GetAdapterId(&netAdapterId);
  538. if (netAdapterId == _deviceGuid) {
  539. foundMyNet = true;
  540. printf("*** Found my net!\n");
  541. nlmNet->SetName(L"ZeroTier One Network");
  542. break;
  543. }
  544. } else break;
  545. }
  546. }
  547. } else break;
  548. }
  549. }
  550. if (foundMyNet)
  551. break;
  552. else Thread::sleep(1000);
  553. }
  554. }
  555. */
  556. #ifdef ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  557. /* This inserts a fake default route and a fake ARP entry, forcing
  558. * Windows to detect this as a "real" network and apply proper
  559. * firewall rules.
  560. *
  561. * This hack is completely stupid, but Windows made me do it
  562. * by being broken and insane.
  563. *
  564. * Background: Windows tries to detect its network location by
  565. * matching it to the ARP address of the default route. Networks
  566. * without default routes are "unidentified networks" and cannot
  567. * have their firewall classification changed by the user (easily).
  568. *
  569. * Yes, you read that right.
  570. *
  571. * The common workaround is to set *NdisDeviceType to 1, which
  572. * totally disables all Windows firewall functionality. This is
  573. * the answer you'll find on most forums for things like OpenVPN.
  574. *
  575. * Yes, you read that right.
  576. *
  577. * But these networks don't usually have default routes, so what
  578. * do we do? Answer: add a fake one that's never used and goes
  579. * nowhere. But it's got to resolve to an ARP address. So why
  580. * don't we just make up one of those too?!? Shove it in there
  581. * as a permanent statuc ARP entry and now Windows will think it
  582. * has a real live default route at our bogus IP.
  583. *
  584. * We'll have to see what DHCP does with this. In the future we
  585. * probably will not want to do this on DHCP-enabled networks, so
  586. * when we enable DHCP we will go in and yank this wacko hacko from
  587. * the routing table before doing so.
  588. *
  589. * But yes, this works, and it makes our networks look and behave
  590. * the way they should.
  591. *
  592. * Like Jesse Pinkman would say: "YEEEEAAH BITCH!" */
  593. for(int i=0;i<8;++i) { // also wait up to 8s for this, though if we got the NLM part we're probably okay
  594. MIB_IPFORWARD_ROW2 nr;
  595. memset(&nr,0,sizeof(nr));
  596. InitializeIpForwardEntry(&nr);
  597. nr.InterfaceLuid.Value = _deviceLuid.Value;
  598. nr.DestinationPrefix.Prefix.si_family = AF_INET; // rest is left as 0.0.0.0/0
  599. nr.NextHop.si_family = AF_INET;
  600. nr.NextHop.Ipv4.sin_addr.s_addr = 0x01010101; // 1.1.1.1
  601. nr.Metric = 9999; // do not use as real default route
  602. nr.Protocol = MIB_IPPROTO_NETMGMT;
  603. DWORD result = CreateIpForwardEntry2(&nr);
  604. if (result == NO_ERROR) {
  605. MIB_IPNET_ROW2 ipnr;
  606. memset(&ipnr,0,sizeof(ipnr));
  607. ipnr.Address.si_family = AF_INET;
  608. ipnr.Address.Ipv4.sin_addr.s_addr = 0x01010101;
  609. ipnr.InterfaceLuid.Value = _deviceLuid.Value;
  610. ipnr.PhysicalAddress[0] = _mac[0] ^ 0x10; // just make something up that's consistent and not part of this net
  611. ipnr.PhysicalAddress[1] = 0x00;
  612. ipnr.PhysicalAddress[2] = (UCHAR)((_deviceGuid.Data1 >> 24) & 0xff);
  613. ipnr.PhysicalAddress[3] = (UCHAR)((_deviceGuid.Data1 >> 16) & 0xff);
  614. ipnr.PhysicalAddress[4] = (UCHAR)((_deviceGuid.Data1 >> 8) & 0xff);
  615. ipnr.PhysicalAddress[5] = (UCHAR)(_deviceGuid.Data1 & 0xff);
  616. ipnr.PhysicalAddressLength = 6;
  617. ipnr.State = NlnsPermanent;
  618. ipnr.IsRouter = 1;
  619. ipnr.IsUnreachable = 0;
  620. ipnr.ReachabilityTime.LastReachable = 0x0fffffff;
  621. CreateIpNetEntry2(&ipnr);
  622. break; // stop retrying, we're done
  623. } else Thread::sleep(1000);
  624. }
  625. #endif
  626. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  627. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  628. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  629. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  630. wait4[0] = _injectSemaphore;
  631. wait4[1] = tapOvlRead.hEvent;
  632. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  633. // Start overlapped read, which is always active
  634. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  635. bool writeInProgress = false;
  636. for(;;) {
  637. if (!_run) break;
  638. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,10000,TRUE);
  639. if (!_run) break;
  640. if ((r == WAIT_TIMEOUT)||(r == WAIT_FAILED))
  641. continue;
  642. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  643. DWORD bytesRead = 0;
  644. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  645. if ((bytesRead > 14)&&(_enabled)) {
  646. MAC to(tapReadBuf,6);
  647. MAC from(tapReadBuf + 6,6);
  648. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  649. try {
  650. Buffer<4096> tmp(tapReadBuf + 14,bytesRead - 14);
  651. _handler(_arg,from,to,etherType,tmp);
  652. } catch ( ... ) {} // handlers should not throw
  653. }
  654. }
  655. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  656. }
  657. if (writeInProgress) {
  658. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  659. writeInProgress = false;
  660. _injectPending_m.lock();
  661. _injectPending.pop();
  662. } else continue; // still writing, so skip code below and wait
  663. } else _injectPending_m.lock();
  664. if (!_injectPending.empty()) {
  665. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  666. writeInProgress = true;
  667. }
  668. _injectPending_m.unlock();
  669. }
  670. CancelIo(_tap);
  671. CloseHandle(tapOvlRead.hEvent);
  672. CloseHandle(tapOvlWrite.hEvent);
  673. CloseHandle(_tap);
  674. _tap = INVALID_HANDLE_VALUE;
  675. ::free(tapReadBuf);
  676. }
  677. bool WindowsEthernetTap::_disableTapDevice()
  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 + "\" disable @" + _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. bool WindowsEthernetTap::_enableTapDevice()
  704. {
  705. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  706. if (devconLog != INVALID_HANDLE_VALUE)
  707. SetFilePointer(devconLog,0,0,FILE_END);
  708. STARTUPINFOA startupInfo;
  709. startupInfo.cb = sizeof(startupInfo);
  710. if (devconLog != INVALID_HANDLE_VALUE) {
  711. startupInfo.hStdOutput = devconLog;
  712. startupInfo.hStdError = devconLog;
  713. }
  714. PROCESS_INFORMATION processInfo;
  715. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  716. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  717. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" enable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  718. if (devconLog != INVALID_HANDLE_VALUE)
  719. CloseHandle(devconLog);
  720. return false;
  721. }
  722. WaitForSingleObject(processInfo.hProcess,INFINITE);
  723. CloseHandle(processInfo.hProcess);
  724. CloseHandle(processInfo.hThread);
  725. if (devconLog != INVALID_HANDLE_VALUE)
  726. CloseHandle(devconLog);
  727. return true;
  728. }
  729. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  730. {
  731. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  732. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  733. throw std::runtime_error("GetIfTable2Ex() failed");
  734. for(ULONG i=0;i<ift->NumEntries;++i) {
  735. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  736. NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
  737. FreeMibTable(ift);
  738. return idx;
  739. }
  740. }
  741. FreeMibTable(&ift);
  742. throw std::runtime_error("interface not found");
  743. }
  744. std::vector<std::string> WindowsEthernetTap::_getRegistryIPv4Value(const char *regKey)
  745. {
  746. std::vector<std::string> value;
  747. HKEY tcpIpInterfaces;
  748. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  749. char buf[16384];
  750. DWORD len = sizeof(buf);
  751. DWORD kt = REG_MULTI_SZ;
  752. if (RegGetValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,0,&kt,&buf,&len) == ERROR_SUCCESS) {
  753. switch(kt) {
  754. case REG_SZ:
  755. if (len > 0)
  756. value.push_back(std::string(buf));
  757. break;
  758. case REG_MULTI_SZ: {
  759. for(DWORD k=0,s=0;k<len;++k) {
  760. if (!buf[k]) {
  761. if (s < k) {
  762. value.push_back(std::string(buf + s));
  763. s = k + 1;
  764. } else break;
  765. }
  766. }
  767. } break;
  768. }
  769. }
  770. RegCloseKey(tcpIpInterfaces);
  771. }
  772. return value;
  773. }
  774. void WindowsEthernetTap::_setRegistryIPv4Value(const char *regKey,const std::vector<std::string> &value)
  775. {
  776. std::string regMulti;
  777. for(std::vector<std::string>::const_iterator s(value.begin());s!=value.end();++s) {
  778. regMulti.append(*s);
  779. regMulti.push_back((char)0);
  780. }
  781. HKEY tcpIpInterfaces;
  782. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  783. if (regMulti.length() > 0) {
  784. regMulti.push_back((char)0);
  785. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,REG_MULTI_SZ,regMulti.data(),(DWORD)regMulti.length());
  786. } else {
  787. RegDeleteKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey);
  788. }
  789. RegCloseKey(tcpIpInterfaces);
  790. }
  791. }
  792. } // namespace ZeroTier