one.cpp 47 KB

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