one.cpp 47 KB

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