one.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdint.h>
  17. #include <time.h>
  18. #include <errno.h>
  19. #include "node/Constants.hpp"
  20. #ifdef __WINDOWS__
  21. #include <WinSock2.h>
  22. #include <Windows.h>
  23. #include <tchar.h>
  24. #include <wchar.h>
  25. #include <lmcons.h>
  26. #include <newdev.h>
  27. #include <atlbase.h>
  28. #include "osdep/WindowsEthernetTap.hpp"
  29. #include "windows/ZeroTierOne/ServiceInstaller.h"
  30. #include "windows/ZeroTierOne/ServiceBase.h"
  31. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  32. #else
  33. #include <unistd.h>
  34. #include <pwd.h>
  35. #include <fcntl.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/uio.h>
  39. #include <dirent.h>
  40. #include <signal.h>
  41. #ifdef __LINUX__
  42. #include <sys/prctl.h>
  43. #include <sys/syscall.h>
  44. #include <sys/wait.h>
  45. #ifndef ZT_NO_CAPABILITIES
  46. #include <linux/capability.h>
  47. #include <linux/securebits.h>
  48. #endif
  49. #endif
  50. #endif
  51. #include <string>
  52. #include <stdexcept>
  53. #include <iostream>
  54. #include <sstream>
  55. #include <algorithm>
  56. #include "version.h"
  57. #include "include/ZeroTierOne.h"
  58. #include "node/Identity.hpp"
  59. #include "node/CertificateOfMembership.hpp"
  60. #include "node/Utils.hpp"
  61. #include "node/NetworkController.hpp"
  62. #include "node/Buffer.hpp"
  63. #include "osdep/OSUtils.hpp"
  64. #include "osdep/Http.hpp"
  65. #include "osdep/Thread.hpp"
  66. #include "service/OneService.hpp"
  67. #include "ext/json/json.hpp"
  68. #define ZT_PID_PATH "zerotier-one.pid"
  69. using namespace ZeroTier;
  70. static OneService *volatile zt1Service = (OneService *)0;
  71. #define PROGRAM_NAME "ZeroTier One"
  72. #define COPYRIGHT_NOTICE "Copyright (c) 2019 ZeroTier, Inc."
  73. #define LICENSE_GRANT "Licensed under the ZeroTier BSL 1.1 (see LICENSE.txt)"
  74. /****************************************************************************/
  75. /* zerotier-cli personality */
  76. /****************************************************************************/
  77. // This is getting deprecated soon in favor of the stuff in cli/
  78. static void cliPrintHelp(const char *pn,FILE *out)
  79. {
  80. fprintf(out,
  81. "%s version %d.%d.%d build %d (platform %d arch %d)" ZT_EOL_S,
  82. PROGRAM_NAME,
  83. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION, ZEROTIER_ONE_VERSION_BUILD,
  84. ZT_BUILD_PLATFORM, ZT_BUILD_ARCHITECTURE);
  85. fprintf(out,
  86. COPYRIGHT_NOTICE ZT_EOL_S
  87. LICENSE_GRANT ZT_EOL_S);
  88. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  89. fprintf(out,"Available switches:" ZT_EOL_S);
  90. fprintf(out," -h - Display this help" ZT_EOL_S);
  91. fprintf(out," -v - Show version" ZT_EOL_S);
  92. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  93. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  94. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  95. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  96. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  97. fprintf(out," info - Display status info" ZT_EOL_S);
  98. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  99. fprintf(out," peers - List all peers (prettier)" ZT_EOL_S);
  100. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  101. fprintf(out," join <network> - Join a network" ZT_EOL_S);
  102. fprintf(out," leave <network> - Leave a network" ZT_EOL_S);
  103. fprintf(out," set <network> <setting> - Set a network setting" ZT_EOL_S);
  104. fprintf(out," get <network> <setting> - Get a network setting" ZT_EOL_S);
  105. fprintf(out,ZT_EOL_S"Available settings:" ZT_EOL_S);
  106. fprintf(out," Settings to use with [get/set] may include property names from " ZT_EOL_S);
  107. fprintf(out," the JSON output of \"zerotier-cli -j listnetworks\". Additionally, " ZT_EOL_S);
  108. fprintf(out," (ip, ip4, ip6, ip6plane, and ip6prefix can be used). For instance:" ZT_EOL_S);
  109. fprintf(out," zerotier-cli get <nwid> ip6plane will return the 6PLANE address" ZT_EOL_S);
  110. fprintf(out," assigned to this node." ZT_EOL_S);
  111. }
  112. static std::string cliFixJsonCRs(const std::string &s)
  113. {
  114. std::string r;
  115. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  116. if (*c == '\n')
  117. r.append(ZT_EOL_S);
  118. else r.push_back(*c);
  119. }
  120. return r;
  121. }
  122. #ifdef __WINDOWS__
  123. static int cli(int argc, _TCHAR* argv[])
  124. #else
  125. static int cli(int argc,char **argv)
  126. #endif
  127. {
  128. unsigned int port = 0;
  129. std::string homeDir,command,arg1,arg2,authToken;
  130. std::string ip("127.0.0.1");
  131. bool json = false;
  132. for(int i=1;i<argc;++i) {
  133. if (argv[i][0] == '-') {
  134. switch(argv[i][1]) {
  135. case 'q': // ignore -q used to invoke this personality
  136. if (argv[i][2]) {
  137. cliPrintHelp(argv[0],stdout);
  138. return 1;
  139. }
  140. break;
  141. case 'j':
  142. if (argv[i][2]) {
  143. cliPrintHelp(argv[0],stdout);
  144. return 1;
  145. }
  146. json = true;
  147. break;
  148. case 'p':
  149. port = Utils::strToUInt(argv[i] + 2);
  150. if ((port > 0xffff)||(port == 0)) {
  151. cliPrintHelp(argv[0],stdout);
  152. return 1;
  153. }
  154. break;
  155. case 'D':
  156. if (argv[i][2]) {
  157. homeDir = argv[i] + 2;
  158. } else {
  159. cliPrintHelp(argv[0],stdout);
  160. return 1;
  161. }
  162. break;
  163. case 'H':
  164. if (argv[i][2]) {
  165. ip = argv[i] + 2;
  166. } else {
  167. cliPrintHelp(argv[0],stdout);
  168. return 1;
  169. }
  170. break;
  171. case 'T':
  172. if (argv[i][2]) {
  173. authToken = argv[i] + 2;
  174. } else {
  175. cliPrintHelp(argv[0],stdout);
  176. return 1;
  177. }
  178. break;
  179. case 'v':
  180. if (argv[i][2]) {
  181. cliPrintHelp(argv[0],stdout);
  182. return 1;
  183. }
  184. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  185. return 0;
  186. case 'h':
  187. case '?':
  188. default:
  189. cliPrintHelp(argv[0],stdout);
  190. return 0;
  191. }
  192. } else {
  193. if (arg1.length())
  194. arg2 = argv[i];
  195. else if (command.length())
  196. arg1 = argv[i];
  197. else command = argv[i];
  198. }
  199. }
  200. if (!homeDir.length())
  201. homeDir = OneService::platformDefaultHomePath();
  202. if ((!port)||(!authToken.length())) {
  203. if (!homeDir.length()) {
  204. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  205. return 2;
  206. }
  207. if (!port) {
  208. std::string portStr;
  209. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  210. port = Utils::strToUInt(portStr.c_str());
  211. if ((port == 0)||(port > 0xffff)) {
  212. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  213. return 2;
  214. }
  215. }
  216. if (!authToken.length()) {
  217. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  218. #ifdef __UNIX_LIKE__
  219. if (!authToken.length()) {
  220. const char *hd = getenv("HOME");
  221. if (hd) {
  222. char p[4096];
  223. #ifdef __APPLE__
  224. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  225. #else
  226. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  227. #endif
  228. OSUtils::readFile(p,authToken);
  229. }
  230. }
  231. #endif
  232. if (!authToken.length()) {
  233. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  234. return 2;
  235. }
  236. }
  237. }
  238. InetAddress addr;
  239. {
  240. char addrtmp[256];
  241. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  242. addr = InetAddress(addrtmp);
  243. }
  244. std::map<std::string,std::string> requestHeaders;
  245. std::map<std::string,std::string> responseHeaders;
  246. std::string responseBody;
  247. requestHeaders["X-ZT1-Auth"] = authToken;
  248. if ((command.length() > 0)&&(command[0] == '/')) {
  249. unsigned int scode = Http::GET(
  250. 1024 * 1024 * 16,
  251. 60000,
  252. (const struct sockaddr *)&addr,
  253. command.c_str(),
  254. requestHeaders,
  255. responseHeaders,
  256. responseBody);
  257. if (scode == 200) {
  258. printf("%s", cliFixJsonCRs(responseBody).c_str());
  259. return 0;
  260. } else {
  261. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  262. return 1;
  263. }
  264. } else if ((command == "info")||(command == "status")) {
  265. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  266. if (scode == 0) {
  267. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  268. return 1;
  269. }
  270. nlohmann::json j;
  271. try {
  272. j = OSUtils::jsonParse(responseBody);
  273. } catch (std::exception &exc) {
  274. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  275. return 1;
  276. } catch ( ... ) {
  277. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  278. return 1;
  279. }
  280. if (scode == 200) {
  281. if (json) {
  282. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  283. } else {
  284. if (j.is_object()) {
  285. printf("200 info %s %s %s" ZT_EOL_S,
  286. OSUtils::jsonString(j["address"],"-").c_str(),
  287. OSUtils::jsonString(j["version"],"-").c_str(),
  288. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  289. }
  290. }
  291. return 0;
  292. } else {
  293. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  294. return 1;
  295. }
  296. } else if (command == "listpeers") {
  297. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  298. if (scode == 0) {
  299. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  300. return 1;
  301. }
  302. nlohmann::json j;
  303. try {
  304. j = OSUtils::jsonParse(responseBody);
  305. } catch (std::exception &exc) {
  306. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  307. return 1;
  308. } catch ( ... ) {
  309. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  310. return 1;
  311. }
  312. if (scode == 200) {
  313. if (json) {
  314. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  315. } else {
  316. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  317. if (j.is_array()) {
  318. for(unsigned long k=0;k<j.size();++k) {
  319. nlohmann::json &p = j[k];
  320. std::string bestPath;
  321. nlohmann::json &paths = p["paths"];
  322. if (paths.is_array()) {
  323. for(unsigned long i=0;i<paths.size();++i) {
  324. nlohmann::json &path = paths[i];
  325. if (path["preferred"]) {
  326. char tmp[256];
  327. std::string addr = path["address"];
  328. const int64_t now = OSUtils::now();
  329. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"]);
  330. bestPath = tmp;
  331. break;
  332. }
  333. }
  334. }
  335. if (bestPath.length() == 0) bestPath = "-";
  336. char ver[128];
  337. int64_t vmaj = p["versionMajor"];
  338. int64_t vmin = p["versionMinor"];
  339. int64_t vrev = p["versionRev"];
  340. if (vmaj >= 0) {
  341. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  342. } else {
  343. ver[0] = '-';
  344. ver[1] = (char)0;
  345. }
  346. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  347. OSUtils::jsonString(p["address"],"-").c_str(),
  348. bestPath.c_str(),
  349. (int)OSUtils::jsonInt(p["latency"],0),
  350. ver,
  351. OSUtils::jsonString(p["role"],"-").c_str());
  352. }
  353. }
  354. }
  355. return 0;
  356. } else {
  357. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  358. return 1;
  359. }
  360. } else if (command == "peers") {
  361. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  362. if (scode == 0) {
  363. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  364. return 1;
  365. }
  366. nlohmann::json j;
  367. try {
  368. j = OSUtils::jsonParse(responseBody);
  369. } catch (std::exception &exc) {
  370. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  371. return 1;
  372. } catch ( ... ) {
  373. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  374. return 1;
  375. }
  376. if (scode == 200) {
  377. if (json) {
  378. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  379. } else {
  380. printf("200 peers\n<ztaddr> <ver> <role> <lat> <link> <lastTX> <lastRX> <path>" ZT_EOL_S);
  381. if (j.is_array()) {
  382. for(unsigned long k=0;k<j.size();++k) {
  383. nlohmann::json &p = j[k];
  384. std::string bestPath;
  385. nlohmann::json &paths = p["paths"];
  386. if (paths.is_array()) {
  387. for(unsigned long i=0;i<paths.size();++i) {
  388. nlohmann::json &path = paths[i];
  389. if (path["preferred"]) {
  390. char tmp[256];
  391. std::string addr = path["address"];
  392. const int64_t now = OSUtils::now();
  393. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%-8lld %-8lld %s",now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"],addr.c_str());
  394. bestPath = std::string("DIRECT ") + tmp;
  395. break;
  396. }
  397. }
  398. }
  399. if (bestPath.length() == 0) bestPath = "RELAY";
  400. char ver[128];
  401. int64_t vmaj = p["versionMajor"];
  402. int64_t vmin = p["versionMinor"];
  403. int64_t vrev = p["versionRev"];
  404. if (vmaj >= 0) {
  405. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  406. } else {
  407. ver[0] = '-';
  408. ver[1] = (char)0;
  409. }
  410. printf("%s %-6s %-6s %5d %s" ZT_EOL_S,
  411. OSUtils::jsonString(p["address"],"-").c_str(),
  412. ver,
  413. OSUtils::jsonString(p["role"],"-").c_str(),
  414. (int)OSUtils::jsonInt(p["latency"],0),
  415. bestPath.c_str());
  416. }
  417. }
  418. }
  419. return 0;
  420. } else {
  421. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  422. return 1;
  423. }
  424. } else if (command == "listnetworks") {
  425. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  426. if (scode == 0) {
  427. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  428. return 1;
  429. }
  430. nlohmann::json j;
  431. try {
  432. j = OSUtils::jsonParse(responseBody);
  433. } catch (std::exception &exc) {
  434. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  435. return 1;
  436. } catch ( ... ) {
  437. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  438. return 1;
  439. }
  440. if (scode == 200) {
  441. if (json) {
  442. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  443. } else {
  444. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  445. if (j.is_array()) {
  446. for(unsigned long i=0;i<j.size();++i) {
  447. nlohmann::json &n = j[i];
  448. if (n.is_object()) {
  449. std::string aa;
  450. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  451. if (assignedAddresses.is_array()) {
  452. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  453. nlohmann::json &addr = assignedAddresses[j];
  454. if (addr.is_string()) {
  455. if (aa.length() > 0) aa.push_back(',');
  456. aa.append(addr.get<std::string>());
  457. }
  458. }
  459. }
  460. if (aa.length() == 0) aa = "-";
  461. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  462. OSUtils::jsonString(n["nwid"],"-").c_str(),
  463. OSUtils::jsonString(n["name"],"-").c_str(),
  464. OSUtils::jsonString(n["mac"],"-").c_str(),
  465. OSUtils::jsonString(n["status"],"-").c_str(),
  466. OSUtils::jsonString(n["type"],"-").c_str(),
  467. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  468. aa.c_str());
  469. }
  470. }
  471. }
  472. }
  473. return 0;
  474. } else {
  475. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  476. return 1;
  477. }
  478. } else if (command == "join") {
  479. if (arg1.length() != 16) {
  480. printf("invalid network id" ZT_EOL_S);
  481. return 2;
  482. }
  483. requestHeaders["Content-Type"] = "application/json";
  484. requestHeaders["Content-Length"] = "2";
  485. unsigned int scode = Http::POST(
  486. 1024 * 1024 * 16,
  487. 60000,
  488. (const struct sockaddr *)&addr,
  489. (std::string("/network/") + arg1).c_str(),
  490. requestHeaders,
  491. "{}",
  492. 2,
  493. responseHeaders,
  494. responseBody);
  495. if (scode == 200) {
  496. if (json) {
  497. printf("%s",cliFixJsonCRs(responseBody).c_str());
  498. } else {
  499. printf("200 join OK" ZT_EOL_S);
  500. }
  501. return 0;
  502. } else {
  503. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  504. return 1;
  505. }
  506. } else if (command == "leave") {
  507. if (arg1.length() != 16) {
  508. printf("invalid network id" ZT_EOL_S);
  509. return 2;
  510. }
  511. unsigned int scode = Http::DEL(
  512. 1024 * 1024 * 16,
  513. 60000,
  514. (const struct sockaddr *)&addr,
  515. (std::string("/network/") + arg1).c_str(),
  516. requestHeaders,
  517. responseHeaders,
  518. responseBody);
  519. if (scode == 200) {
  520. if (json) {
  521. printf("%s",cliFixJsonCRs(responseBody).c_str());
  522. } else {
  523. printf("200 leave OK" ZT_EOL_S);
  524. }
  525. return 0;
  526. } else {
  527. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  528. return 1;
  529. }
  530. } else if (command == "set") {
  531. if (arg1.length() != 16) {
  532. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  533. return 2;
  534. }
  535. if (!arg2.length()) {
  536. fprintf(stderr,"invalid format: include a property name to set\n");
  537. return 2;
  538. }
  539. std::size_t eqidx = arg2.find('=');
  540. if (eqidx != std::string::npos) {
  541. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  542. char jsons[1024];
  543. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  544. arg2.substr(0,eqidx).c_str(),
  545. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  546. char cl[128];
  547. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  548. requestHeaders["Content-Type"] = "application/json";
  549. requestHeaders["Content-Length"] = cl;
  550. unsigned int scode = Http::POST(
  551. 1024 * 1024 * 16,
  552. 60000,
  553. (const struct sockaddr *)&addr,
  554. (std::string("/network/") + arg1).c_str(),
  555. requestHeaders,
  556. jsons,
  557. (unsigned long)strlen(jsons),
  558. responseHeaders,
  559. responseBody);
  560. if (scode == 200) {
  561. printf("%s",cliFixJsonCRs(responseBody).c_str());
  562. return 0;
  563. } else {
  564. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  565. return 1;
  566. }
  567. }
  568. } else {
  569. cliPrintHelp(argv[0],stderr);
  570. return 2;
  571. }
  572. } else if (command == "get") {
  573. if (arg1.length() != 16) {
  574. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  575. return 2;
  576. }
  577. if (!arg2.length()) {
  578. fprintf(stderr,"invalid format: include a property name to get\n");
  579. return 2;
  580. }
  581. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  582. if (scode == 0) {
  583. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  584. return 1;
  585. }
  586. nlohmann::json j;
  587. try {
  588. j = OSUtils::jsonParse(responseBody);
  589. } catch (std::exception &exc) {
  590. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  591. return 1;
  592. } catch ( ... ) {
  593. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  594. return 1;
  595. }
  596. bool bNetworkFound = false;
  597. if (j.is_array()) {
  598. for(unsigned long i=0;i<j.size();++i) {
  599. nlohmann::json &n = j[i];
  600. if (n.is_object()) {
  601. if (n["id"] == arg1) {
  602. bNetworkFound = true;
  603. std::string aa;
  604. if (arg2 != "ip" && arg2 != "ip4" && arg2 != "ip6" && arg2 != "ip6plane" && arg2 != "ip6prefix") {
  605. aa.append(OSUtils::jsonString(n[arg2],"-")); // Standard network property field
  606. if (aa == "-") {
  607. printf("error, unknown property name\n");
  608. break;
  609. }
  610. printf("%s\n",aa.c_str());
  611. break;
  612. }
  613. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  614. if (assignedAddresses.is_array()) {
  615. int matchingIdxs[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  616. int addressCountOfType = 0;
  617. for (int k = 0; k<std::min(ZT_MAX_ZT_ASSIGNED_ADDRESSES, (int)assignedAddresses.size());++k) {
  618. nlohmann::json &addr = assignedAddresses[k];
  619. if ((arg2 == "ip4" && addr.get<std::string>().find(".") != std::string::npos)
  620. || ((arg2.find("ip6") == 0) && addr.get<std::string>().find(":") != std::string::npos)
  621. || (arg2 == "ip")
  622. ) {
  623. matchingIdxs[addressCountOfType++] = k;
  624. }
  625. }
  626. for (int k=0; k<addressCountOfType; k++) {
  627. nlohmann::json &addr = assignedAddresses[matchingIdxs[k]];
  628. if (!addr.is_string()) {
  629. continue;
  630. }
  631. if (arg2.find("ip6p") == 0) {
  632. if (arg2 == "ip6plane") {
  633. if (addr.get<std::string>().find("fc") == 0) {
  634. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  635. if (k < addressCountOfType-1) aa.append("\n");
  636. }
  637. }
  638. if (arg2 == "ip6prefix") {
  639. if (addr.get<std::string>().find("fc") == 0) {
  640. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")).substr(0,24));
  641. if (k < addressCountOfType-1) aa.append("\n");
  642. }
  643. }
  644. }
  645. else {
  646. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  647. if (k < addressCountOfType-1) aa.append("\n");
  648. }
  649. }
  650. }
  651. printf("%s\n",aa.c_str());
  652. }
  653. }
  654. }
  655. }
  656. if (!bNetworkFound) {
  657. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  658. }
  659. if (scode == 200) {
  660. return 0;
  661. } else {
  662. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  663. return 1;
  664. }
  665. } else {
  666. cliPrintHelp(argv[0],stderr);
  667. return 0;
  668. }
  669. return 0;
  670. }
  671. /****************************************************************************/
  672. /* zerotier-idtool personality */
  673. /****************************************************************************/
  674. static void idtoolPrintHelp(FILE *out,const char *pn)
  675. {
  676. fprintf(out,
  677. "%s version %d.%d.%d" ZT_EOL_S,
  678. PROGRAM_NAME,
  679. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  680. fprintf(out,
  681. COPYRIGHT_NOTICE ZT_EOL_S
  682. LICENSE_GRANT ZT_EOL_S);
  683. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  684. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  685. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  686. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  687. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  688. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  689. }
  690. static Identity getIdFromArg(char *arg)
  691. {
  692. Identity id;
  693. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  694. if (id.fromString(arg))
  695. return id;
  696. } else { // identity is to be read from a file
  697. std::string idser;
  698. if (OSUtils::readFile(arg,idser)) {
  699. if (id.fromString(idser.c_str()))
  700. return id;
  701. }
  702. }
  703. return Identity();
  704. }
  705. #ifdef __WINDOWS__
  706. static int idtool(int argc, _TCHAR* argv[])
  707. #else
  708. static int idtool(int argc,char **argv)
  709. #endif
  710. {
  711. if (argc < 2) {
  712. idtoolPrintHelp(stdout,argv[0]);
  713. return 1;
  714. }
  715. if (!strcmp(argv[1],"generate")) {
  716. uint64_t vanity = 0;
  717. int vanityBits = 0;
  718. if (argc >= 5) {
  719. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  720. vanityBits = 4 * (int)strlen(argv[4]);
  721. if (vanityBits > 40)
  722. vanityBits = 40;
  723. }
  724. Identity id;
  725. for(;;) {
  726. id.generate(Identity::C25519);
  727. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  728. if (vanityBits > 0) {
  729. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  730. }
  731. break;
  732. } else {
  733. fprintf(stderr,"vanity address: tried %.10llx looking for first %d bits of %.10llx\n",(unsigned long long)id.address().toInt(),vanityBits,(unsigned long long)(vanity << (40 - vanityBits)));
  734. }
  735. }
  736. char idtmp[1024];
  737. std::string idser = id.toString(true,idtmp);
  738. if (argc >= 3) {
  739. if (!OSUtils::writeFile(argv[2],idser)) {
  740. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  741. return 1;
  742. } else printf("%s written" ZT_EOL_S,argv[2]);
  743. if (argc >= 4) {
  744. idser = id.toString(false,idtmp);
  745. if (!OSUtils::writeFile(argv[3],idser)) {
  746. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  747. return 1;
  748. } else printf("%s written" ZT_EOL_S,argv[3]);
  749. }
  750. } else printf("%s",idser.c_str());
  751. } else if (!strcmp(argv[1],"validate")) {
  752. if (argc < 3) {
  753. idtoolPrintHelp(stdout,argv[0]);
  754. return 1;
  755. }
  756. Identity id = getIdFromArg(argv[2]);
  757. if (!id) {
  758. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  759. return 1;
  760. }
  761. if (!id.locallyValidate()) {
  762. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  763. return 1;
  764. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  765. } else if (!strcmp(argv[1],"getpublic")) {
  766. if (argc < 3) {
  767. idtoolPrintHelp(stdout,argv[0]);
  768. return 1;
  769. }
  770. Identity id = getIdFromArg(argv[2]);
  771. if (!id) {
  772. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  773. return 1;
  774. }
  775. char idtmp[1024];
  776. printf("%s",id.toString(false,idtmp));
  777. } else if (!strcmp(argv[1],"sign")) {
  778. if (argc < 4) {
  779. idtoolPrintHelp(stdout,argv[0]);
  780. return 1;
  781. }
  782. Identity id = getIdFromArg(argv[2]);
  783. if (!id) {
  784. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  785. return 1;
  786. }
  787. if (!id.hasPrivate()) {
  788. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  789. return 1;
  790. }
  791. std::string inf;
  792. if (!OSUtils::readFile(argv[3],inf)) {
  793. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  794. return 1;
  795. }
  796. uint8_t signature[ZT_SIGNATURE_BUFFER_SIZE];
  797. const unsigned int siglen = id.sign(inf.data(),(unsigned int)inf.length(),signature,sizeof(signature));
  798. char hexbuf[256];
  799. printf("%s",Utils::hex(signature,siglen,hexbuf));
  800. } else if (!strcmp(argv[1],"verify")) {
  801. if (argc < 5) {
  802. idtoolPrintHelp(stdout,argv[0]);
  803. return 1;
  804. }
  805. Identity id = getIdFromArg(argv[2]);
  806. if (!id) {
  807. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  808. return 1;
  809. }
  810. std::string inf;
  811. if (!OSUtils::readFile(argv[3],inf)) {
  812. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  813. return 1;
  814. }
  815. char buf[4096];
  816. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  817. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  818. printf("%s signature valid" ZT_EOL_S,argv[3]);
  819. } else {
  820. signature.clear();
  821. if (OSUtils::readFile(argv[4],signature)) {
  822. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  823. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  824. printf("%s signature valid" ZT_EOL_S,argv[3]);
  825. } else {
  826. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  827. return 1;
  828. }
  829. } else {
  830. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  831. return 1;
  832. }
  833. }
  834. } else {
  835. idtoolPrintHelp(stdout,argv[0]);
  836. return 1;
  837. }
  838. return 0;
  839. }
  840. /****************************************************************************/
  841. /* Unix helper functions and signal handlers */
  842. /****************************************************************************/
  843. #ifdef __UNIX_LIKE__
  844. static void _sighandlerHup(int sig)
  845. {
  846. }
  847. static void _sighandlerQuit(int sig)
  848. {
  849. OneService *s = zt1Service;
  850. if (s)
  851. s->terminate();
  852. else exit(0);
  853. }
  854. #endif
  855. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  856. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  857. #ifndef PR_CAP_AMBIENT
  858. #define PR_CAP_AMBIENT 47
  859. #define PR_CAP_AMBIENT_IS_SET 1
  860. #define PR_CAP_AMBIENT_RAISE 2
  861. #define PR_CAP_AMBIENT_LOWER 3
  862. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  863. #endif
  864. #define ZT_LINUX_USER "zerotier-one"
  865. #define ZT_HAVE_DROP_PRIVILEGES 1
  866. namespace {
  867. // libc doesn't export capset, it is instead located in libcap
  868. // We ignore libcap and call it manually.
  869. struct cap_header_struct {
  870. __u32 version;
  871. int pid;
  872. };
  873. struct cap_data_struct {
  874. __u32 effective;
  875. __u32 permitted;
  876. __u32 inheritable;
  877. };
  878. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  879. static void _notDropping(const char *procName,const std::string &homeDir)
  880. {
  881. struct stat buf;
  882. if (lstat(homeDir.c_str(),&buf) < 0) {
  883. if (buf.st_uid != 0 || buf.st_gid != 0) {
  884. fprintf(stderr, "%s: FATAL: failed to drop privileges and can't run as root since privileges were previously dropped (home directory not owned by root)" ZT_EOL_S,procName);
  885. exit(1);
  886. }
  887. }
  888. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  889. }
  890. static int _setCapabilities(int flags)
  891. {
  892. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  893. cap_data_struct capdata;
  894. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  895. return _zt_capset(&capheader, &capdata);
  896. }
  897. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  898. {
  899. struct dirent de;
  900. struct dirent *dptr;
  901. lchown(path,uid,gid);
  902. DIR *d = opendir(path);
  903. if (!d)
  904. return;
  905. dptr = (struct dirent *)0;
  906. for(;;) {
  907. if (readdir_r(d,&de,&dptr) != 0)
  908. break;
  909. if (!dptr)
  910. break;
  911. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  912. std::string p(path);
  913. p.push_back(ZT_PATH_SEPARATOR);
  914. p.append(dptr->d_name);
  915. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  916. }
  917. }
  918. closedir(d);
  919. }
  920. static void dropPrivileges(const char *procName,const std::string &homeDir)
  921. {
  922. if (getuid() != 0)
  923. return;
  924. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  925. // and CAP_NET_RAW capabilities.
  926. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  927. if (!targetUser)
  928. return;
  929. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  930. // Kernel has no support for ambient capabilities.
  931. _notDropping(procName,homeDir);
  932. return;
  933. }
  934. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  935. _notDropping(procName,homeDir);
  936. return;
  937. }
  938. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  939. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  940. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  941. _notDropping(procName,homeDir);
  942. return;
  943. }
  944. int oldDumpable = prctl(PR_GET_DUMPABLE);
  945. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  946. // Disable ptracing. Otherwise there is a small window when previous
  947. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  948. // (this is mitigated anyway on most distros by ptrace_scope=1)
  949. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  950. exit(1);
  951. }
  952. // Relinquish root
  953. if (setgid(targetUser->pw_gid) < 0) {
  954. perror("setgid");
  955. exit(1);
  956. }
  957. if (setuid(targetUser->pw_uid) < 0) {
  958. perror("setuid");
  959. exit(1);
  960. }
  961. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  962. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  963. exit(1);
  964. }
  965. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  966. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  967. exit(1);
  968. }
  969. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  970. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_ADMIN) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  971. exit(1);
  972. }
  973. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  974. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_RAW) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  975. exit(1);
  976. }
  977. }
  978. } // anonymous namespace
  979. #endif // __LINUX__
  980. /****************************************************************************/
  981. /* Windows helper functions and signal handlers */
  982. /****************************************************************************/
  983. #ifdef __WINDOWS__
  984. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  985. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  986. {
  987. switch(dwCtrlType) {
  988. case CTRL_C_EVENT:
  989. case CTRL_BREAK_EVENT:
  990. case CTRL_CLOSE_EVENT:
  991. case CTRL_SHUTDOWN_EVENT:
  992. OneService *s = zt1Service;
  993. if (s)
  994. s->terminate();
  995. return TRUE;
  996. }
  997. return FALSE;
  998. }
  999. static void _winPokeAHole()
  1000. {
  1001. char myPath[MAX_PATH];
  1002. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1003. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1004. STARTUPINFOA startupInfo;
  1005. PROCESS_INFORMATION processInfo;
  1006. startupInfo.cb = sizeof(startupInfo);
  1007. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1008. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1009. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1010. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1011. CloseHandle(processInfo.hProcess);
  1012. CloseHandle(processInfo.hThread);
  1013. }
  1014. startupInfo.cb = sizeof(startupInfo);
  1015. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1016. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1017. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1018. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1019. CloseHandle(processInfo.hProcess);
  1020. CloseHandle(processInfo.hThread);
  1021. }
  1022. startupInfo.cb = sizeof(startupInfo);
  1023. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1024. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1025. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  1026. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1027. CloseHandle(processInfo.hProcess);
  1028. CloseHandle(processInfo.hThread);
  1029. }
  1030. }
  1031. }
  1032. // Returns true if this is running as the local administrator
  1033. static BOOL IsCurrentUserLocalAdministrator(void)
  1034. {
  1035. BOOL fReturn = FALSE;
  1036. DWORD dwStatus;
  1037. DWORD dwAccessMask;
  1038. DWORD dwAccessDesired;
  1039. DWORD dwACLSize;
  1040. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1041. PACL pACL = NULL;
  1042. PSID psidAdmin = NULL;
  1043. HANDLE hToken = NULL;
  1044. HANDLE hImpersonationToken = NULL;
  1045. PRIVILEGE_SET ps;
  1046. GENERIC_MAPPING GenericMapping;
  1047. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1048. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1049. const DWORD ACCESS_READ = 1;
  1050. const DWORD ACCESS_WRITE = 2;
  1051. __try
  1052. {
  1053. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1054. {
  1055. if (GetLastError() != ERROR_NO_TOKEN)
  1056. __leave;
  1057. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1058. __leave;
  1059. }
  1060. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1061. __leave;
  1062. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1063. SECURITY_BUILTIN_DOMAIN_RID,
  1064. DOMAIN_ALIAS_RID_ADMINS,
  1065. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1066. __leave;
  1067. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1068. if (psdAdmin == NULL)
  1069. __leave;
  1070. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1071. __leave;
  1072. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1073. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1074. if (pACL == NULL)
  1075. __leave;
  1076. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1077. __leave;
  1078. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1079. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1080. __leave;
  1081. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1082. __leave;
  1083. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1084. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1085. if (!IsValidSecurityDescriptor(psdAdmin))
  1086. __leave;
  1087. dwAccessDesired = ACCESS_READ;
  1088. GenericMapping.GenericRead = ACCESS_READ;
  1089. GenericMapping.GenericWrite = ACCESS_WRITE;
  1090. GenericMapping.GenericExecute = 0;
  1091. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1092. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1093. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1094. &fReturn))
  1095. {
  1096. fReturn = FALSE;
  1097. __leave;
  1098. }
  1099. }
  1100. __finally
  1101. {
  1102. // Clean up.
  1103. if (pACL) LocalFree(pACL);
  1104. if (psdAdmin) LocalFree(psdAdmin);
  1105. if (psidAdmin) FreeSid(psidAdmin);
  1106. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1107. if (hToken) CloseHandle (hToken);
  1108. }
  1109. return fReturn;
  1110. }
  1111. #endif // __WINDOWS__
  1112. /****************************************************************************/
  1113. /* main() and friends */
  1114. /****************************************************************************/
  1115. static void printHelp(const char *cn,FILE *out)
  1116. {
  1117. fprintf(out,
  1118. "%s version %d.%d.%d" ZT_EOL_S,
  1119. PROGRAM_NAME,
  1120. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1121. fprintf(out,
  1122. COPYRIGHT_NOTICE ZT_EOL_S
  1123. LICENSE_GRANT ZT_EOL_S);
  1124. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1125. fprintf(out,"Available switches:" ZT_EOL_S);
  1126. fprintf(out," -h - Display this help" ZT_EOL_S);
  1127. fprintf(out," -v - Show version" ZT_EOL_S);
  1128. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1129. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1130. #ifdef __UNIX_LIKE__
  1131. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1132. #endif // __UNIX_LIKE__
  1133. #ifdef __WINDOWS__
  1134. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1135. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1136. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1137. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1138. #endif // __WINDOWS__
  1139. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1140. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1141. }
  1142. class _OneServiceRunner
  1143. {
  1144. public:
  1145. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1146. void threadMain()
  1147. throw()
  1148. {
  1149. try {
  1150. for(;;) {
  1151. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1152. switch(zt1Service->run()) {
  1153. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1154. case OneService::ONE_NORMAL_TERMINATION:
  1155. break;
  1156. case OneService::ONE_UNRECOVERABLE_ERROR:
  1157. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1158. returnValue = 1;
  1159. break;
  1160. case OneService::ONE_IDENTITY_COLLISION: {
  1161. delete zt1Service;
  1162. zt1Service = (OneService *)0;
  1163. std::string oldid;
  1164. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1165. if (oldid.length()) {
  1166. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1167. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1168. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1169. }
  1170. } continue; // restart!
  1171. }
  1172. break; // terminate loop -- normally we don't keep restarting
  1173. }
  1174. delete zt1Service;
  1175. zt1Service = (OneService *)0;
  1176. } catch ( ... ) {
  1177. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1178. returnValue = 1;
  1179. }
  1180. }
  1181. const char *progname;
  1182. unsigned int returnValue;
  1183. unsigned int port;
  1184. const std::string &homeDir;
  1185. };
  1186. #ifdef __WINDOWS__
  1187. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1188. #else
  1189. int main(int argc,char **argv)
  1190. #endif
  1191. {
  1192. #ifdef __UNIX_LIKE__
  1193. signal(SIGHUP,&_sighandlerHup);
  1194. signal(SIGPIPE,SIG_IGN);
  1195. signal(SIGIO,SIG_IGN);
  1196. signal(SIGUSR1,SIG_IGN);
  1197. signal(SIGUSR2,SIG_IGN);
  1198. signal(SIGALRM,SIG_IGN);
  1199. signal(SIGINT,&_sighandlerQuit);
  1200. signal(SIGTERM,&_sighandlerQuit);
  1201. signal(SIGQUIT,&_sighandlerQuit);
  1202. signal(SIGINT,&_sighandlerQuit);
  1203. /* Ensure that there are no inherited file descriptors open from a previous
  1204. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1205. * of it do not return, and should not do anything otherwise bad. */
  1206. {
  1207. int mfd = STDIN_FILENO;
  1208. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1209. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1210. for(int f=mfd+1;f<1024;++f)
  1211. ::close(f);
  1212. }
  1213. bool runAsDaemon = false;
  1214. #endif // __UNIX_LIKE__
  1215. #ifdef __WINDOWS__
  1216. {
  1217. WSADATA wsaData;
  1218. WSAStartup(MAKEWORD(2,2),&wsaData);
  1219. }
  1220. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1221. bool winRunFromCommandLine = true;
  1222. #else
  1223. bool winRunFromCommandLine = false;
  1224. #endif
  1225. #endif // __WINDOWS__
  1226. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1227. return idtool(argc,argv);
  1228. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1229. return cli(argc,argv);
  1230. std::string homeDir;
  1231. unsigned int port = ZT_DEFAULT_PORT;
  1232. bool skipRootCheck = false;
  1233. for(int i=1;i<argc;++i) {
  1234. if (argv[i][0] == '-') {
  1235. switch(argv[i][1]) {
  1236. case 'p': // port -- for both UDP and TCP, packets and control plane
  1237. port = Utils::strToUInt(argv[i] + 2);
  1238. if (port > 0xffff) {
  1239. printHelp(argv[0],stdout);
  1240. return 1;
  1241. }
  1242. break;
  1243. #ifdef __UNIX_LIKE__
  1244. case 'd': // Run in background as daemon
  1245. runAsDaemon = true;
  1246. break;
  1247. #endif // __UNIX_LIKE__
  1248. case 'U':
  1249. skipRootCheck = true;
  1250. break;
  1251. case 'v': // Display version
  1252. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1253. return 0;
  1254. case 'i': // Invoke idtool personality
  1255. if (argv[i][2]) {
  1256. printHelp(argv[0],stdout);
  1257. return 0;
  1258. } else return idtool(argc-1,argv+1);
  1259. case 'q': // Invoke cli personality
  1260. if (argv[i][2]) {
  1261. printHelp(argv[0],stdout);
  1262. return 0;
  1263. } else return cli(argc,argv);
  1264. #ifdef __WINDOWS__
  1265. case 'C': // Run from command line instead of as Windows service
  1266. winRunFromCommandLine = true;
  1267. break;
  1268. case 'I': { // Install this binary as a Windows service
  1269. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1270. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1271. return 1;
  1272. }
  1273. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1274. if (ret.length()) {
  1275. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1276. return 3;
  1277. }
  1278. return 0;
  1279. } break;
  1280. case 'R': { // Uninstall this binary as Windows service
  1281. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1282. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1283. return 1;
  1284. }
  1285. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1286. if (ret.length()) {
  1287. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1288. return 3;
  1289. }
  1290. return 0;
  1291. } break;
  1292. case 'D': {
  1293. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1294. if (err.length() > 0) {
  1295. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1296. return 3;
  1297. }
  1298. return 0;
  1299. } break;
  1300. #endif // __WINDOWS__
  1301. case 'h':
  1302. case '?':
  1303. default:
  1304. printHelp(argv[0],stdout);
  1305. return 0;
  1306. }
  1307. } else {
  1308. if (homeDir.length()) {
  1309. printHelp(argv[0],stdout);
  1310. return 0;
  1311. } else {
  1312. homeDir = argv[i];
  1313. }
  1314. }
  1315. }
  1316. if (!homeDir.length())
  1317. homeDir = OneService::platformDefaultHomePath();
  1318. if (!homeDir.length()) {
  1319. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1320. return 1;
  1321. } else {
  1322. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1323. std::string ptmp;
  1324. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1325. ptmp.push_back(ZT_PATH_SEPARATOR);
  1326. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1327. if (ptmp.length() > 0)
  1328. ptmp.push_back(ZT_PATH_SEPARATOR);
  1329. ptmp.append(*pi);
  1330. if ((*pi != ".")&&(*pi != "..")) {
  1331. if (!OSUtils::mkdir(ptmp))
  1332. throw std::runtime_error("home path does not exist, and could not create");
  1333. }
  1334. }
  1335. }
  1336. // This can be removed once the new controller code has been around for many versions
  1337. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1338. fprintf(stderr,"%s: FATAL: an old controller.db exists in %s -- see instructions in controller/README.md for how to migrate!" ZT_EOL_S,argv[0],homeDir.c_str());
  1339. return 1;
  1340. }
  1341. #ifdef __UNIX_LIKE__
  1342. #ifndef ZT_ONE_NO_ROOT_CHECK
  1343. if ((!skipRootCheck)&&(getuid() != 0)) {
  1344. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1345. return 1;
  1346. }
  1347. #endif // !ZT_ONE_NO_ROOT_CHECK
  1348. if (runAsDaemon) {
  1349. long p = (long)fork();
  1350. if (p < 0) {
  1351. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1352. return 1;
  1353. } else if (p > 0)
  1354. return 0; // forked
  1355. // else p == 0, so we are daemonized
  1356. }
  1357. #endif // __UNIX_LIKE__
  1358. #ifdef __WINDOWS__
  1359. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1360. // when tap instances are created.
  1361. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1362. if (winRunFromCommandLine) {
  1363. // Running in "interactive" mode (mostly for debugging)
  1364. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1365. if (!skipRootCheck) {
  1366. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1367. return 1;
  1368. }
  1369. } else {
  1370. _winPokeAHole();
  1371. }
  1372. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1373. // continues on to ordinary command line execution code below...
  1374. } else {
  1375. // Running from service manager
  1376. _winPokeAHole();
  1377. ZeroTierOneService zt1WindowsService;
  1378. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1379. return 0;
  1380. } else {
  1381. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1382. return 1;
  1383. }
  1384. }
  1385. #endif // __WINDOWS__
  1386. #ifdef __UNIX_LIKE__
  1387. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1388. if (!skipRootCheck)
  1389. dropPrivileges(argv[0],homeDir);
  1390. #endif
  1391. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1392. {
  1393. // Write .pid file to home folder
  1394. FILE *pf = fopen(pidPath.c_str(),"w");
  1395. if (pf) {
  1396. fprintf(pf,"%ld",(long)getpid());
  1397. fclose(pf);
  1398. }
  1399. }
  1400. #endif // __UNIX_LIKE__
  1401. _OneServiceRunner thr(argv[0],homeDir,port);
  1402. thr.threadMain();
  1403. //Thread::join(Thread::start(&thr));
  1404. #ifdef __UNIX_LIKE__
  1405. OSUtils::rm(pidPath.c_str());
  1406. #endif
  1407. return thr.returnValue;
  1408. }