one.cpp 45 KB

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