one.cpp 45 KB

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