one.cpp 48 KB

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