main.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. // Uncomment on Windows to assume -C and run in console instead of service
  28. // Useful for Visual Studio debugging (launch VS as Administrator to run)
  29. //#define ZT_WIN_RUN_IN_CONSOLE
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <time.h>
  34. #include <errno.h>
  35. #include <string>
  36. #include <stdexcept>
  37. #include "node/Constants.hpp"
  38. #ifdef __WINDOWS__
  39. #include <WinSock2.h>
  40. #include <Windows.h>
  41. #include <tchar.h>
  42. #include <wchar.h>
  43. #include <lmcons.h>
  44. #include <newdev.h>
  45. #include <atlbase.h>
  46. #include "windows/ZeroTierOne/ServiceInstaller.h"
  47. #include "windows/ZeroTierOne/ServiceBase.h"
  48. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  49. #else
  50. #include <unistd.h>
  51. #include <pwd.h>
  52. #include <fcntl.h>
  53. #include <sys/types.h>
  54. #include <sys/stat.h>
  55. #include <signal.h>
  56. #endif
  57. #include "node/Constants.hpp"
  58. #include "node/Defaults.hpp"
  59. #include "node/Utils.hpp"
  60. #include "node/Node.hpp"
  61. #include "node/C25519.hpp"
  62. #include "node/Identity.hpp"
  63. #include "node/Thread.hpp"
  64. #include "node/CertificateOfMembership.hpp"
  65. #include "node/EthernetTapFactory.hpp"
  66. #include "node/RoutingTable.hpp"
  67. #include "node/SocketManager.hpp"
  68. #include "control/NodeControlClient.hpp"
  69. #include "control/NodeControlService.hpp"
  70. #include "osnet/NativeSocketManager.hpp"
  71. #ifdef __WINDOWS__
  72. #include "osnet/WindowsEthernetTapFactory.hpp"
  73. #include "osnet/WindowsRoutingTable.hpp"
  74. #define ZTCreatePlatformEthernetTapFactory (new WindowsEthernetTapFactory(homeDir))
  75. #define ZTCreatePlatformRoutingTable (new WindowsRoutingTable())
  76. #endif // __WINDOWS__
  77. #ifdef __LINUX__
  78. #include "osnet/LinuxEthernetTapFactory.hpp"
  79. #include "osnet/LinuxRoutingTable.hpp"
  80. #define ZTCreatePlatformEthernetTapFactory (new LinuxEthernetTapFactory())
  81. #define ZTCreatePlatformRoutingTable (new LinuxRoutingTable())
  82. #endif // __LINUX__
  83. #ifdef __APPLE__
  84. #include "osnet/OSXEthernetTapFactory.hpp"
  85. #include "osnet/BSDRoutingTable.hpp"
  86. #define ZTCreatePlatformEthernetTapFactory (new OSXEthernetTapFactory(homeDir,"tap.kext"))
  87. #define ZTCreatePlatformRoutingTable (new BSDRoutingTable())
  88. #endif // __APPLE__
  89. #ifndef ZTCreatePlatformEthernetTapFactory
  90. #ifdef __BSD__
  91. #include "osnet/BSDEthernetTapFactory.hpp"
  92. #include "osnet/BSDRoutingTable.hpp"
  93. #define ZTCreatePlatformEthernetTapFactory (new BSDEthernetTapFactory())
  94. #define ZTCreatePlatformRoutingTable (new BSDRoutingTable())
  95. #else
  96. #error Sorry, this platform has no osnet/ implementation yet. Fork me on GitHub and add one?
  97. #endif // __BSD__
  98. #endif // ZTCreatePlatformEthernetTapFactory
  99. using namespace ZeroTier;
  100. static Node *node = (Node *)0;
  101. namespace ZeroTierCLI { // ---------------------------------------------------
  102. static void printHelp(FILE *out,const char *cn)
  103. {
  104. fprintf(out,"Usage: %s <command> (use 'help' for help)"ZT_EOL_S,cn);
  105. }
  106. static void _CBresultHandler(void *arg,const char *line)
  107. {
  108. if (line) {
  109. if ((line[0] == '.')&&(line[1] == (char)0)) {
  110. fflush(stdout);
  111. ::exit(0); // terminate CLI on end of message
  112. } else {
  113. fprintf(stdout,"%s"ZT_EOL_S,line);
  114. }
  115. }
  116. }
  117. #ifdef __WINDOWS__
  118. static int main(const char *homeDir,int argc,_TCHAR* argv[])
  119. #else
  120. static int main(const char *homeDir,int argc,char **argv)
  121. #endif
  122. {
  123. if (argc < 2) {
  124. printHelp(stdout,argv[0]);
  125. return 1;
  126. }
  127. std::string query;
  128. for(int i=1;i<argc;++i) {
  129. if (argv[i][0] == '-') {
  130. switch(argv[i][1]) {
  131. case 'q': // ignore -q since it's used to invoke this
  132. break;
  133. case 'h':
  134. default:
  135. printHelp(stdout,argv[0]);
  136. return 1;
  137. }
  138. } else if ((!homeDir)||(strcmp(homeDir,argv[i]))) {
  139. if (query.length())
  140. query.push_back(' ');
  141. query.append(argv[i]);
  142. }
  143. }
  144. if (!query.length()) {
  145. printHelp(stdout,argv[0]);
  146. return 1;
  147. }
  148. if (!homeDir)
  149. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  150. try {
  151. std::string buf;
  152. if (!Utils::readFile((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),buf)) {
  153. fprintf(stderr,"%s: fatal error: unable to read node address from identity.public in home path"ZT_EOL_S,argv[0]);
  154. return 1;
  155. }
  156. Identity id;
  157. if (!id.fromString(buf)) {
  158. fprintf(stderr,"%s: fatal error: unable to read node address from identity.public in home path"ZT_EOL_S,argv[0]);
  159. return 1;
  160. }
  161. std::string authToken(NodeControlClient::getAuthToken((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),false));
  162. if (!authToken.length())
  163. authToken = NodeControlClient::getAuthToken(NodeControlClient::authTokenDefaultUserPath(),false);
  164. if (!authToken.length()) {
  165. fprintf(stderr,"%s: fatal error: unable to read authentication token from home path or user home"ZT_EOL_S,argv[0]);
  166. return 1;
  167. }
  168. NodeControlClient client((std::string(ZT_IPC_ENDPOINT_BASE) + id.address().toString()).c_str(),authToken.c_str(),&_CBresultHandler,(void *)0);
  169. const char *err = client.error();
  170. if (err) {
  171. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],err);
  172. return 1;
  173. }
  174. client.send(query.c_str());
  175. for(;;) { Thread::sleep(60000); } // exit() is called at end of message from handler
  176. } catch (std::exception &exc) {
  177. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],exc.what());
  178. return 1;
  179. } catch ( ... ) {
  180. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (unknown exception)"ZT_EOL_S,argv[0]);
  181. return 1;
  182. }
  183. return 0;
  184. }
  185. } // namespace ZeroTierCLI ---------------------------------------------------
  186. namespace ZeroTierIdTool { // ------------------------------------------------
  187. static void printHelp(FILE *out,const char *pn)
  188. {
  189. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  190. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  191. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  192. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  193. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  194. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  195. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  196. }
  197. static Identity getIdFromArg(char *arg)
  198. {
  199. Identity id;
  200. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  201. if (id.fromString(arg))
  202. return id;
  203. } else { // identity is to be read from a file
  204. std::string idser;
  205. if (Utils::readFile(arg,idser)) {
  206. if (id.fromString(idser))
  207. return id;
  208. }
  209. }
  210. return Identity();
  211. }
  212. #ifdef __WINDOWS__
  213. static int main(int argc,_TCHAR* argv[])
  214. #else
  215. static int main(int argc,char **argv)
  216. #endif
  217. {
  218. if (argc < 2) {
  219. printHelp(stdout,argv[0]);
  220. return 1;
  221. }
  222. if (!strcmp(argv[1],"generate")) {
  223. Identity id;
  224. id.generate();
  225. std::string idser = id.toString(true);
  226. if (argc >= 3) {
  227. if (!Utils::writeFile(argv[2],idser)) {
  228. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  229. return 1;
  230. } else printf("%s written"ZT_EOL_S,argv[2]);
  231. if (argc >= 4) {
  232. idser = id.toString(false);
  233. if (!Utils::writeFile(argv[3],idser)) {
  234. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  235. return 1;
  236. } else printf("%s written"ZT_EOL_S,argv[3]);
  237. }
  238. } else printf("%s",idser.c_str());
  239. } else if (!strcmp(argv[1],"validate")) {
  240. if (argc < 3) {
  241. printHelp(stdout,argv[0]);
  242. return 1;
  243. }
  244. Identity id = getIdFromArg(argv[2]);
  245. if (!id) {
  246. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  247. return 1;
  248. }
  249. if (!id.locallyValidate()) {
  250. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  251. return 1;
  252. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  253. } else if (!strcmp(argv[1],"getpublic")) {
  254. if (argc < 3) {
  255. printHelp(stdout,argv[0]);
  256. return 1;
  257. }
  258. Identity id = getIdFromArg(argv[2]);
  259. if (!id) {
  260. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  261. return 1;
  262. }
  263. printf("%s",id.toString(false).c_str());
  264. } else if (!strcmp(argv[1],"sign")) {
  265. if (argc < 4) {
  266. printHelp(stdout,argv[0]);
  267. return 1;
  268. }
  269. Identity id = getIdFromArg(argv[2]);
  270. if (!id) {
  271. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  272. return 1;
  273. }
  274. if (!id.hasPrivate()) {
  275. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  276. return 1;
  277. }
  278. std::string inf;
  279. if (!Utils::readFile(argv[3],inf)) {
  280. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  281. return 1;
  282. }
  283. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  284. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  285. } else if (!strcmp(argv[1],"verify")) {
  286. if (argc < 4) {
  287. printHelp(stdout,argv[0]);
  288. return 1;
  289. }
  290. Identity id = getIdFromArg(argv[2]);
  291. if (!id) {
  292. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  293. return 1;
  294. }
  295. std::string inf;
  296. if (!Utils::readFile(argv[3],inf)) {
  297. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  298. return 1;
  299. }
  300. std::string signature(Utils::unhex(argv[4]));
  301. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  302. printf("%s signature valid"ZT_EOL_S,argv[3]);
  303. } else {
  304. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  305. return 1;
  306. }
  307. } else if (!strcmp(argv[1],"mkcom")) {
  308. if (argc < 3) {
  309. printHelp(stdout,argv[0]);
  310. return 1;
  311. }
  312. Identity id = getIdFromArg(argv[2]);
  313. if ((!id)||(!id.hasPrivate())) {
  314. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  315. return 1;
  316. }
  317. CertificateOfMembership com;
  318. for(int a=3;a<argc;++a) {
  319. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  320. if (params.size() == 3) {
  321. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  322. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  323. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  324. com.setQualifier(qId,qValue,qMaxDelta);
  325. }
  326. }
  327. if (!com.sign(id)) {
  328. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  329. return 1;
  330. }
  331. printf("%s",com.toString().c_str());
  332. } else {
  333. printHelp(stdout,argv[0]);
  334. return 1;
  335. }
  336. return 0;
  337. }
  338. } // namespace ZeroTierIdTool ------------------------------------------------
  339. #ifdef __UNIX_LIKE__
  340. static void sighandlerHup(int sig)
  341. {
  342. Node *n = node;
  343. if (n)
  344. n->resync();
  345. }
  346. static void sighandlerQuit(int sig)
  347. {
  348. Node *n = node;
  349. if (n)
  350. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  351. else exit(0);
  352. }
  353. #endif
  354. #ifdef __WINDOWS__
  355. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  356. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  357. {
  358. switch(dwCtrlType) {
  359. case CTRL_C_EVENT:
  360. case CTRL_BREAK_EVENT:
  361. case CTRL_CLOSE_EVENT:
  362. case CTRL_SHUTDOWN_EVENT:
  363. Node *n = node;
  364. if (n)
  365. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  366. return TRUE;
  367. }
  368. return FALSE;
  369. }
  370. // Pokes a hole in the Windows firewall (advfirewall) for the running program
  371. static void _winPokeAHole()
  372. {
  373. char myPath[MAX_PATH];
  374. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  375. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  376. STARTUPINFOA startupInfo;
  377. PROCESS_INFORMATION processInfo;
  378. startupInfo.cb = sizeof(startupInfo);
  379. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  380. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  381. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall delete rule name=\"ZeroTier One\" program=\"") + myPath + "\"").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  382. WaitForSingleObject(processInfo.hProcess,INFINITE);
  383. CloseHandle(processInfo.hProcess);
  384. CloseHandle(processInfo.hThread);
  385. }
  386. startupInfo.cb = sizeof(startupInfo);
  387. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  388. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  389. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=in action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  390. WaitForSingleObject(processInfo.hProcess,INFINITE);
  391. CloseHandle(processInfo.hProcess);
  392. CloseHandle(processInfo.hThread);
  393. }
  394. startupInfo.cb = sizeof(startupInfo);
  395. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  396. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  397. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=out action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  398. WaitForSingleObject(processInfo.hProcess,INFINITE);
  399. CloseHandle(processInfo.hProcess);
  400. CloseHandle(processInfo.hThread);
  401. }
  402. }
  403. }
  404. // Returns true if this is running as the local administrator
  405. static BOOL IsCurrentUserLocalAdministrator(void)
  406. {
  407. BOOL fReturn = FALSE;
  408. DWORD dwStatus;
  409. DWORD dwAccessMask;
  410. DWORD dwAccessDesired;
  411. DWORD dwACLSize;
  412. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  413. PACL pACL = NULL;
  414. PSID psidAdmin = NULL;
  415. HANDLE hToken = NULL;
  416. HANDLE hImpersonationToken = NULL;
  417. PRIVILEGE_SET ps;
  418. GENERIC_MAPPING GenericMapping;
  419. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  420. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  421. const DWORD ACCESS_READ = 1;
  422. const DWORD ACCESS_WRITE = 2;
  423. __try
  424. {
  425. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  426. {
  427. if (GetLastError() != ERROR_NO_TOKEN)
  428. __leave;
  429. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  430. __leave;
  431. }
  432. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  433. __leave;
  434. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  435. SECURITY_BUILTIN_DOMAIN_RID,
  436. DOMAIN_ALIAS_RID_ADMINS,
  437. 0, 0, 0, 0, 0, 0, &psidAdmin))
  438. __leave;
  439. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  440. if (psdAdmin == NULL)
  441. __leave;
  442. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  443. __leave;
  444. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  445. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  446. if (pACL == NULL)
  447. __leave;
  448. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  449. __leave;
  450. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  451. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  452. __leave;
  453. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  454. __leave;
  455. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  456. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  457. if (!IsValidSecurityDescriptor(psdAdmin))
  458. __leave;
  459. dwAccessDesired = ACCESS_READ;
  460. GenericMapping.GenericRead = ACCESS_READ;
  461. GenericMapping.GenericWrite = ACCESS_WRITE;
  462. GenericMapping.GenericExecute = 0;
  463. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  464. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  465. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  466. &fReturn))
  467. {
  468. fReturn = FALSE;
  469. __leave;
  470. }
  471. }
  472. __finally
  473. {
  474. // Clean up.
  475. if (pACL) LocalFree(pACL);
  476. if (psdAdmin) LocalFree(psdAdmin);
  477. if (psidAdmin) FreeSid(psidAdmin);
  478. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  479. if (hToken) CloseHandle (hToken);
  480. }
  481. return fReturn;
  482. }
  483. #endif // __WINDOWS__
  484. // ---------------------------------------------------------------------------
  485. static void printHelp(const char *cn,FILE *out)
  486. {
  487. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2014 ZeroTier Networks LLC"ZT_EOL_S,Node::versionMajor(),Node::versionMinor(),Node::versionRevision());
  488. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  489. #ifdef ZT_AUTO_UPDATE
  490. fprintf(out,"Auto-update enabled build, will update from URL:"ZT_EOL_S);
  491. fprintf(out," %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  492. fprintf(out,"Update authentication signing authorities: "ZT_EOL_S);
  493. int no = 0;
  494. for(std::map< Address,Identity >::const_iterator sa(ZT_DEFAULTS.updateAuthorities.begin());sa!=ZT_DEFAULTS.updateAuthorities.end();++sa) {
  495. if (no == 0)
  496. fprintf(out," %s",sa->first.toString().c_str());
  497. else fprintf(out,", %s",sa->first.toString().c_str());
  498. if (++no == 6) {
  499. fprintf(out,ZT_EOL_S);
  500. no = 0;
  501. }
  502. }
  503. fprintf(out,ZT_EOL_S""ZT_EOL_S);
  504. #else
  505. fprintf(out,"Auto-updates not enabled on this build. You must update manually."ZT_EOL_S""ZT_EOL_S);
  506. #endif
  507. fprintf(out,"Usage: %s [-switches] [home directory] [-q <query>]"ZT_EOL_S""ZT_EOL_S,cn);
  508. fprintf(out,"Available switches:"ZT_EOL_S);
  509. fprintf(out," -h - Display this help"ZT_EOL_S);
  510. fprintf(out," -v - Show version"ZT_EOL_S);
  511. fprintf(out," -p<port> - Port for UDP (default: 9993)"ZT_EOL_S);
  512. fprintf(out," -t<port> - Port for TCP (default: disabled)"ZT_EOL_S);
  513. //fprintf(out," -T<path> - Override root topology, do not authenticate or update"ZT_EOL_S);
  514. #ifdef __UNIX_LIKE__
  515. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  516. #endif
  517. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  518. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  519. #ifdef __WINDOWS__
  520. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  521. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  522. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  523. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  524. #endif
  525. }
  526. #ifdef __WINDOWS__
  527. int _tmain(int argc, _TCHAR* argv[])
  528. #else
  529. int main(int argc,char **argv)
  530. #endif
  531. {
  532. #ifdef __UNIX_LIKE__
  533. signal(SIGHUP,&sighandlerHup);
  534. signal(SIGPIPE,SIG_IGN);
  535. signal(SIGUSR1,SIG_IGN);
  536. signal(SIGUSR2,SIG_IGN);
  537. signal(SIGALRM,SIG_IGN);
  538. signal(SIGINT,&sighandlerQuit);
  539. signal(SIGTERM,&sighandlerQuit);
  540. signal(SIGQUIT,&sighandlerQuit);
  541. /* Ensure that there are no inherited file descriptors open from a previous
  542. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  543. * of it do not return, and should not do anything otherwise bad. */
  544. {
  545. int mfd = STDIN_FILENO;
  546. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  547. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  548. for(int f=mfd+1;f<1024;++f)
  549. ::close(f);
  550. }
  551. #endif
  552. #ifdef __WINDOWS__
  553. WSADATA wsaData;
  554. WSAStartup(MAKEWORD(2,2),&wsaData);
  555. #endif
  556. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  557. return ZeroTierCLI::main((const char *)0,argc,argv);
  558. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  559. return ZeroTierIdTool::main(argc,argv);
  560. const char *homeDir = (const char *)0;
  561. unsigned int udpPort = ZT_DEFAULT_UDP_PORT;
  562. unsigned int tcpPort = 0;
  563. std::string overrideRootTopology;
  564. #ifdef __UNIX_LIKE__
  565. bool runAsDaemon = false;
  566. #endif
  567. #ifdef __WINDOWS__
  568. #ifdef ZT_WIN_RUN_IN_CONSOLE
  569. bool winRunFromCommandLine = true;
  570. #else
  571. bool winRunFromCommandLine = false;
  572. #endif
  573. #endif // __WINDOWS__
  574. for(int i=1;i<argc;++i) {
  575. if (argv[i][0] == '-') {
  576. switch(argv[i][1]) {
  577. case 'p':
  578. udpPort = Utils::strToUInt(argv[i] + 2);
  579. if (udpPort > 65535) {
  580. printHelp(argv[0],stdout);
  581. return 1;
  582. }
  583. break;
  584. case 't':
  585. tcpPort = Utils::strToUInt(argv[i] + 2);
  586. if (tcpPort > 65535) {
  587. printHelp(argv[0],stdout);
  588. return 1;
  589. }
  590. break;
  591. #ifdef __UNIX_LIKE__
  592. case 'd':
  593. runAsDaemon = true;
  594. break;
  595. #endif
  596. case 'T':
  597. if (argv[i][2]) {
  598. if (!Utils::readFile(argv[i] + 2,overrideRootTopology)) {
  599. fprintf(stderr,"%s: cannot read root topology from %s"ZT_EOL_S,argv[0],argv[i] + 2);
  600. return 1;
  601. }
  602. } else {
  603. printHelp(argv[0],stdout);
  604. return 1;
  605. }
  606. break;
  607. case 'v':
  608. printf("%s"ZT_EOL_S,Node::versionString());
  609. return 0;
  610. case 'q':
  611. if (argv[i][2]) {
  612. printHelp(argv[0],stdout);
  613. return 0;
  614. } else return ZeroTierCLI::main(homeDir,argc,argv);
  615. case 'i':
  616. if (argv[i][2]) {
  617. printHelp(argv[0],stdout);
  618. return 0;
  619. } else return ZeroTierIdTool::main(argc,argv);
  620. #ifdef __WINDOWS__
  621. case 'C':
  622. winRunFromCommandLine = true;
  623. break;
  624. case 'I': { // install self as service
  625. if (IsCurrentUserLocalAdministrator() != TRUE) {
  626. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  627. return 1;
  628. }
  629. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  630. if (ret.length()) {
  631. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  632. return 3;
  633. }
  634. return 0;
  635. } break;
  636. case 'R': { // uninstall self as service
  637. if (IsCurrentUserLocalAdministrator() != TRUE) {
  638. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  639. return 1;
  640. }
  641. std::string ret(UninstallService(ZT_SERVICE_NAME));
  642. if (ret.length()) {
  643. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  644. return 3;
  645. }
  646. return 0;
  647. } break;
  648. case 'D': { // install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  649. std::string pathToInf;
  650. #ifdef _WIN64
  651. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  652. #else
  653. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  654. #endif
  655. printf("Installing ZeroTier One virtual Ethernet port driver."ZT_EOL_S""ZT_EOL_S"NOTE: If you don't see a confirmation window to allow driver installation,"ZT_EOL_S"check to make sure it didn't appear under the installer."ZT_EOL_S);
  656. BOOL needReboot = FALSE;
  657. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  658. printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  659. return 0;
  660. } else {
  661. printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  662. return 3;
  663. }
  664. } break;
  665. #endif // __WINDOWS__
  666. case 'h':
  667. case '?':
  668. default:
  669. printHelp(argv[0],stdout);
  670. return 0;
  671. }
  672. } else {
  673. if (homeDir) {
  674. printHelp(argv[0],stdout);
  675. return 0;
  676. } else homeDir = argv[i];
  677. }
  678. }
  679. if ((!homeDir)||(strlen(homeDir) == 0))
  680. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  681. #ifdef __UNIX_LIKE__
  682. if (getuid() != 0) {
  683. fprintf(stderr,"%s: must be run as root (uid 0)\n",argv[0]);
  684. return 1;
  685. }
  686. if (runAsDaemon) {
  687. long p = (long)fork();
  688. if (p < 0) {
  689. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  690. return 1;
  691. } else if (p > 0)
  692. return 0; // forked
  693. // else p == 0, so we are daemonized
  694. }
  695. mkdir(homeDir,0755); // will fail if it already exists, but that's fine
  696. {
  697. // Write .pid file to home folder
  698. char pidpath[4096];
  699. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  700. FILE *pf = fopen(pidpath,"w");
  701. if (pf) {
  702. fprintf(pf,"%ld",(long)getpid());
  703. fclose(pf);
  704. }
  705. }
  706. #endif // __UNIX_LIKE__
  707. #ifdef __WINDOWS__
  708. if (winRunFromCommandLine) {
  709. // Running in "interactive" mode (mostly for debugging)
  710. if (IsCurrentUserLocalAdministrator() != TRUE) {
  711. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  712. return 1;
  713. }
  714. _winPokeAHole();
  715. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  716. // continues on to ordinary command line execution code below...
  717. } else {
  718. // Running from service manager
  719. _winPokeAHole();
  720. ZeroTierOneService zt1Service;
  721. if (CServiceBase::Run(zt1Service) == TRUE) {
  722. return 0;
  723. } else {
  724. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  725. return 1;
  726. }
  727. }
  728. #endif // __WINDOWS__
  729. int exitCode = 0;
  730. bool needsReset = false;
  731. EthernetTapFactory *tapFactory = (EthernetTapFactory *)0;
  732. RoutingTable *routingTable = (RoutingTable *)0;
  733. SocketManager *socketManager = (SocketManager *)0;
  734. NodeControlService *controlService = (NodeControlService *)0;
  735. try {
  736. // Get or create authtoken.secret -- note that if this fails, authentication
  737. // will always fail since an empty auth token won't work. This should always
  738. // succeed unless something is wrong with the filesystem.
  739. std::string authToken(NodeControlClient::getAuthToken((std::string(homeDir) + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),true));
  740. tapFactory = ZTCreatePlatformEthernetTapFactory;
  741. routingTable = ZTCreatePlatformRoutingTable;
  742. try {
  743. socketManager = new NativeSocketManager(udpPort,tcpPort);
  744. } catch ( ... ) {
  745. fprintf(stderr,"%s: unable to bind to port: %u/UDP, %u/TCP (0 == disabled)"ZT_EOL_S,argv[0],udpPort,tcpPort);
  746. throw;
  747. }
  748. node = new Node(homeDir,tapFactory,routingTable,socketManager,needsReset,(overrideRootTopology.length() > 0) ? overrideRootTopology.c_str() : (const char *)0);
  749. controlService = new NodeControlService(node,authToken.c_str());
  750. switch(node->run()) {
  751. #ifdef __WINDOWS__
  752. case Node::NODE_RESTART_FOR_UPGRADE: {
  753. const char *upgPath = node->terminationMessage();
  754. if (upgPath) {
  755. if (!ZeroTierOneService::doStartUpgrade(std::string(upgPath))) {
  756. exitCode = 3;
  757. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (doStartUpgrade failed)"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
  758. }
  759. } else {
  760. exitCode = 3;
  761. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (no upgrade path provided)"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
  762. }
  763. } break;
  764. #else // __UNIX_LIKE__
  765. case Node::NODE_RESTART_FOR_UPGRADE: {
  766. const char *upgPath = node->terminationMessage();
  767. // On Unix-type OSes we exec() right into the upgrade. This in turn will
  768. // end with us being re-launched either via the upgrade itself or something
  769. // like OSX's launchd.
  770. if (upgPath) {
  771. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  772. std::string updateLogPath(homeDir);
  773. updateLogPath.append("/autoupdate.log");
  774. Utils::rm(updateLogPath.c_str());
  775. Utils::redirectUnixOutputs(updateLogPath.c_str(),(const char *)0);
  776. ::execl(upgPath,upgPath,(char *)0);
  777. }
  778. exitCode = 3;
  779. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s"ZT_EOL_S,argv[0],(upgPath) ? upgPath : "(unknown path)");
  780. } break;
  781. #endif // __WINDOWS__ / __UNIX_LIKE__
  782. case Node::NODE_UNRECOVERABLE_ERROR: {
  783. exitCode = 3;
  784. const char *termReason = node->terminationMessage();
  785. fprintf(stderr,"%s: abnormal termination: %s"ZT_EOL_S,argv[0],(termReason) ? termReason : "(unknown reason)");
  786. } break;
  787. default:
  788. break;
  789. }
  790. } catch ( std::exception &exc ) {
  791. fprintf(stderr,"%s: unexpected exception: %s"ZT_EOL_S,argv[0],exc.what());
  792. exitCode = 3;
  793. } catch ( ... ) {
  794. fprintf(stderr,"%s: unexpected exception: unknown exception"ZT_EOL_S,argv[0]);
  795. exitCode = 3;
  796. }
  797. delete controlService;
  798. delete node; node = (Node *)0;
  799. delete socketManager;
  800. delete routingTable;
  801. delete tapFactory;
  802. #ifdef __UNIX_LIKE__
  803. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  804. #endif
  805. return exitCode;
  806. }