one.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  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. Utils::snprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  235. #else
  236. Utils::snprintf(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. Utils::snprintf(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. Utils::snprintf(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. Utils::snprintf(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. Utils::snprintf(jsons,sizeof(jsons),"{\"seed\":\"%s\"}",arg2.c_str());
  490. char cl[128];
  491. Utils::snprintf(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. Utils::snprintf(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. Utils::snprintf(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))
  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. std::string idser = id.toString(true);
  644. if (argc >= 3) {
  645. if (!OSUtils::writeFile(argv[2],idser)) {
  646. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  647. return 1;
  648. } else printf("%s written" ZT_EOL_S,argv[2]);
  649. if (argc >= 4) {
  650. idser = id.toString(false);
  651. if (!OSUtils::writeFile(argv[3],idser)) {
  652. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  653. return 1;
  654. } else printf("%s written" ZT_EOL_S,argv[3]);
  655. }
  656. } else printf("%s",idser.c_str());
  657. } else if (!strcmp(argv[1],"validate")) {
  658. if (argc < 3) {
  659. idtoolPrintHelp(stdout,argv[0]);
  660. return 1;
  661. }
  662. Identity id = getIdFromArg(argv[2]);
  663. if (!id) {
  664. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  665. return 1;
  666. }
  667. if (!id.locallyValidate()) {
  668. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  669. return 1;
  670. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  671. } else if (!strcmp(argv[1],"getpublic")) {
  672. if (argc < 3) {
  673. idtoolPrintHelp(stdout,argv[0]);
  674. return 1;
  675. }
  676. Identity id = getIdFromArg(argv[2]);
  677. if (!id) {
  678. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  679. return 1;
  680. }
  681. printf("%s",id.toString(false).c_str());
  682. } else if (!strcmp(argv[1],"sign")) {
  683. if (argc < 4) {
  684. idtoolPrintHelp(stdout,argv[0]);
  685. return 1;
  686. }
  687. Identity id = getIdFromArg(argv[2]);
  688. if (!id) {
  689. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  690. return 1;
  691. }
  692. if (!id.hasPrivate()) {
  693. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  694. return 1;
  695. }
  696. std::string inf;
  697. if (!OSUtils::readFile(argv[3],inf)) {
  698. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  699. return 1;
  700. }
  701. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  702. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  703. } else if (!strcmp(argv[1],"verify")) {
  704. if (argc < 4) {
  705. idtoolPrintHelp(stdout,argv[0]);
  706. return 1;
  707. }
  708. Identity id = getIdFromArg(argv[2]);
  709. if (!id) {
  710. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  711. return 1;
  712. }
  713. std::string inf;
  714. if (!OSUtils::readFile(argv[3],inf)) {
  715. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  716. return 1;
  717. }
  718. std::string signature(Utils::unhex(argv[4]));
  719. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  720. printf("%s signature valid" ZT_EOL_S,argv[3]);
  721. } else {
  722. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  723. return 1;
  724. }
  725. } else if (!strcmp(argv[1],"initmoon")) {
  726. if (argc < 3) {
  727. idtoolPrintHelp(stdout,argv[0]);
  728. } else {
  729. const Identity id = getIdFromArg(argv[2]);
  730. if (!id) {
  731. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  732. return 1;
  733. }
  734. C25519::Pair kp(C25519::generate());
  735. nlohmann::json mj;
  736. mj["objtype"] = "world";
  737. mj["worldType"] = "moon";
  738. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,(unsigned int)kp.pub.size());
  739. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,(unsigned int)kp.priv.size());
  740. mj["id"] = id.address().toString();
  741. nlohmann::json seedj;
  742. seedj["identity"] = id.toString(false);
  743. seedj["stableEndpoints"] = nlohmann::json::array();
  744. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  745. std::string mjd(OSUtils::jsonDump(mj));
  746. printf("%s" ZT_EOL_S,mjd.c_str());
  747. }
  748. } else if (!strcmp(argv[1],"genmoon")) {
  749. if (argc < 3) {
  750. idtoolPrintHelp(stdout,argv[0]);
  751. } else {
  752. std::string buf;
  753. if (!OSUtils::readFile(argv[2],buf)) {
  754. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  755. return 1;
  756. }
  757. nlohmann::json mj(OSUtils::jsonParse(buf));
  758. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  759. if (!id) {
  760. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  761. return 1;
  762. }
  763. World::Type t;
  764. if (mj["worldType"] == "moon") {
  765. t = World::TYPE_MOON;
  766. } else if (mj["worldType"] == "planet") {
  767. t = World::TYPE_PLANET;
  768. } else {
  769. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  770. return 1;
  771. }
  772. C25519::Pair signingKey;
  773. C25519::Public updatesMustBeSignedBy;
  774. Utils::unhex(OSUtils::jsonString(mj["signingKey"],""),signingKey.pub.data,(unsigned int)signingKey.pub.size());
  775. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],""),signingKey.priv.data,(unsigned int)signingKey.priv.size());
  776. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],""),updatesMustBeSignedBy.data,(unsigned int)updatesMustBeSignedBy.size());
  777. std::vector<World::Root> roots;
  778. nlohmann::json &rootsj = mj["roots"];
  779. if (rootsj.is_array()) {
  780. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  781. nlohmann::json &r = rootsj[i];
  782. if (r.is_object()) {
  783. roots.push_back(World::Root());
  784. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],""));
  785. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  786. if (stableEndpointsj.is_array()) {
  787. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  788. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"")));
  789. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  790. }
  791. }
  792. }
  793. }
  794. std::sort(roots.begin(),roots.end());
  795. const uint64_t now = OSUtils::now();
  796. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  797. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  798. w.serialize(wbuf);
  799. char fn[128];
  800. Utils::snprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  801. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  802. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  803. }
  804. } else {
  805. idtoolPrintHelp(stdout,argv[0]);
  806. return 1;
  807. }
  808. return 0;
  809. }
  810. /****************************************************************************/
  811. /* Unix helper functions and signal handlers */
  812. /****************************************************************************/
  813. #ifdef __UNIX_LIKE__
  814. static void _sighandlerHup(int sig)
  815. {
  816. }
  817. static void _sighandlerQuit(int sig)
  818. {
  819. OneService *s = zt1Service;
  820. if (s)
  821. s->terminate();
  822. else exit(0);
  823. }
  824. #endif
  825. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  826. #ifdef __LINUX__
  827. #ifndef PR_CAP_AMBIENT
  828. #define PR_CAP_AMBIENT 47
  829. #define PR_CAP_AMBIENT_IS_SET 1
  830. #define PR_CAP_AMBIENT_RAISE 2
  831. #define PR_CAP_AMBIENT_LOWER 3
  832. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  833. #endif
  834. #define ZT_LINUX_USER "zerotier-one"
  835. #define ZT_HAVE_DROP_PRIVILEGES 1
  836. namespace {
  837. // libc doesn't export capset, it is instead located in libcap
  838. // We ignore libcap and call it manually.
  839. struct cap_header_struct {
  840. __u32 version;
  841. int pid;
  842. };
  843. struct cap_data_struct {
  844. __u32 effective;
  845. __u32 permitted;
  846. __u32 inheritable;
  847. };
  848. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  849. static void _notDropping(const char *procName,const std::string &homeDir)
  850. {
  851. struct stat buf;
  852. if (lstat(homeDir.c_str(),&buf) < 0) {
  853. if (buf.st_uid != 0 || buf.st_gid != 0) {
  854. 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);
  855. exit(1);
  856. }
  857. }
  858. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  859. }
  860. static int _setCapabilities(int flags)
  861. {
  862. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  863. cap_data_struct capdata;
  864. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  865. return _zt_capset(&capheader, &capdata);
  866. }
  867. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  868. {
  869. struct dirent de;
  870. struct dirent *dptr;
  871. lchown(path,uid,gid);
  872. DIR *d = opendir(path);
  873. if (!d)
  874. return;
  875. dptr = (struct dirent *)0;
  876. for(;;) {
  877. if (readdir_r(d,&de,&dptr) != 0)
  878. break;
  879. if (!dptr)
  880. break;
  881. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  882. std::string p(path);
  883. p.push_back(ZT_PATH_SEPARATOR);
  884. p.append(dptr->d_name);
  885. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  886. }
  887. }
  888. closedir(d);
  889. }
  890. static void dropPrivileges(const char *procName,const std::string &homeDir)
  891. {
  892. if (getuid() != 0)
  893. return;
  894. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  895. // and CAP_NET_RAW capabilities.
  896. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  897. if (!targetUser)
  898. return;
  899. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  900. // Kernel has no support for ambient capabilities.
  901. _notDropping(procName,homeDir);
  902. return;
  903. }
  904. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  905. _notDropping(procName,homeDir);
  906. return;
  907. }
  908. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  909. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  910. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID)) < 0) {
  911. _notDropping(procName,homeDir);
  912. return;
  913. }
  914. int oldDumpable = prctl(PR_GET_DUMPABLE);
  915. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  916. // Disable ptracing. Otherwise there is a small window when previous
  917. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  918. // (this is mitigated anyway on most distros by ptrace_scope=1)
  919. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  920. exit(1);
  921. }
  922. // Relinquish root
  923. if (setgid(targetUser->pw_gid) < 0) {
  924. perror("setgid");
  925. exit(1);
  926. }
  927. if (setuid(targetUser->pw_uid) < 0) {
  928. perror("setuid");
  929. exit(1);
  930. }
  931. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW)) < 0) {
  932. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  933. exit(1);
  934. }
  935. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  936. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  937. exit(1);
  938. }
  939. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  940. 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);
  941. exit(1);
  942. }
  943. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  944. 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);
  945. exit(1);
  946. }
  947. }
  948. } // anonymous namespace
  949. #endif // __LINUX__
  950. /****************************************************************************/
  951. /* Windows helper functions and signal handlers */
  952. /****************************************************************************/
  953. #ifdef __WINDOWS__
  954. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  955. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  956. {
  957. switch(dwCtrlType) {
  958. case CTRL_C_EVENT:
  959. case CTRL_BREAK_EVENT:
  960. case CTRL_CLOSE_EVENT:
  961. case CTRL_SHUTDOWN_EVENT:
  962. OneService *s = zt1Service;
  963. if (s)
  964. s->terminate();
  965. return TRUE;
  966. }
  967. return FALSE;
  968. }
  969. static void _winPokeAHole()
  970. {
  971. char myPath[MAX_PATH];
  972. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  973. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  974. STARTUPINFOA startupInfo;
  975. PROCESS_INFORMATION processInfo;
  976. startupInfo.cb = sizeof(startupInfo);
  977. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  978. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  979. 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)) {
  980. WaitForSingleObject(processInfo.hProcess,INFINITE);
  981. CloseHandle(processInfo.hProcess);
  982. CloseHandle(processInfo.hThread);
  983. }
  984. startupInfo.cb = sizeof(startupInfo);
  985. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  986. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  987. 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)) {
  988. WaitForSingleObject(processInfo.hProcess,INFINITE);
  989. CloseHandle(processInfo.hProcess);
  990. CloseHandle(processInfo.hThread);
  991. }
  992. startupInfo.cb = sizeof(startupInfo);
  993. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  994. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  995. 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)) {
  996. WaitForSingleObject(processInfo.hProcess,INFINITE);
  997. CloseHandle(processInfo.hProcess);
  998. CloseHandle(processInfo.hThread);
  999. }
  1000. }
  1001. }
  1002. // Returns true if this is running as the local administrator
  1003. static BOOL IsCurrentUserLocalAdministrator(void)
  1004. {
  1005. BOOL fReturn = FALSE;
  1006. DWORD dwStatus;
  1007. DWORD dwAccessMask;
  1008. DWORD dwAccessDesired;
  1009. DWORD dwACLSize;
  1010. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1011. PACL pACL = NULL;
  1012. PSID psidAdmin = NULL;
  1013. HANDLE hToken = NULL;
  1014. HANDLE hImpersonationToken = NULL;
  1015. PRIVILEGE_SET ps;
  1016. GENERIC_MAPPING GenericMapping;
  1017. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1018. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1019. const DWORD ACCESS_READ = 1;
  1020. const DWORD ACCESS_WRITE = 2;
  1021. __try
  1022. {
  1023. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1024. {
  1025. if (GetLastError() != ERROR_NO_TOKEN)
  1026. __leave;
  1027. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1028. __leave;
  1029. }
  1030. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1031. __leave;
  1032. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1033. SECURITY_BUILTIN_DOMAIN_RID,
  1034. DOMAIN_ALIAS_RID_ADMINS,
  1035. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1036. __leave;
  1037. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1038. if (psdAdmin == NULL)
  1039. __leave;
  1040. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1041. __leave;
  1042. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1043. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1044. if (pACL == NULL)
  1045. __leave;
  1046. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1047. __leave;
  1048. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1049. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1050. __leave;
  1051. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1052. __leave;
  1053. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1054. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1055. if (!IsValidSecurityDescriptor(psdAdmin))
  1056. __leave;
  1057. dwAccessDesired = ACCESS_READ;
  1058. GenericMapping.GenericRead = ACCESS_READ;
  1059. GenericMapping.GenericWrite = ACCESS_WRITE;
  1060. GenericMapping.GenericExecute = 0;
  1061. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1062. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1063. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1064. &fReturn))
  1065. {
  1066. fReturn = FALSE;
  1067. __leave;
  1068. }
  1069. }
  1070. __finally
  1071. {
  1072. // Clean up.
  1073. if (pACL) LocalFree(pACL);
  1074. if (psdAdmin) LocalFree(psdAdmin);
  1075. if (psidAdmin) FreeSid(psidAdmin);
  1076. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1077. if (hToken) CloseHandle (hToken);
  1078. }
  1079. return fReturn;
  1080. }
  1081. #endif // __WINDOWS__
  1082. /****************************************************************************/
  1083. /* main() and friends */
  1084. /****************************************************************************/
  1085. static void printHelp(const char *cn,FILE *out)
  1086. {
  1087. fprintf(out,
  1088. "%s version %d.%d.%d" ZT_EOL_S,
  1089. PROGRAM_NAME,
  1090. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1091. fprintf(out,
  1092. COPYRIGHT_NOTICE ZT_EOL_S
  1093. LICENSE_GRANT ZT_EOL_S);
  1094. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1095. fprintf(out,"Available switches:" ZT_EOL_S);
  1096. fprintf(out," -h - Display this help" ZT_EOL_S);
  1097. fprintf(out," -v - Show version" ZT_EOL_S);
  1098. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1099. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1100. #ifdef __UNIX_LIKE__
  1101. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1102. #endif // __UNIX_LIKE__
  1103. #ifdef __WINDOWS__
  1104. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1105. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1106. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1107. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1108. #endif // __WINDOWS__
  1109. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1110. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1111. }
  1112. class _OneServiceRunner
  1113. {
  1114. public:
  1115. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1116. void threadMain()
  1117. throw()
  1118. {
  1119. try {
  1120. for(;;) {
  1121. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1122. switch(zt1Service->run()) {
  1123. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1124. case OneService::ONE_NORMAL_TERMINATION:
  1125. break;
  1126. case OneService::ONE_UNRECOVERABLE_ERROR:
  1127. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1128. returnValue = 1;
  1129. break;
  1130. case OneService::ONE_IDENTITY_COLLISION: {
  1131. delete zt1Service;
  1132. zt1Service = (OneService *)0;
  1133. std::string oldid;
  1134. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1135. if (oldid.length()) {
  1136. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1137. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1138. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1139. }
  1140. } continue; // restart!
  1141. }
  1142. break; // terminate loop -- normally we don't keep restarting
  1143. }
  1144. delete zt1Service;
  1145. zt1Service = (OneService *)0;
  1146. } catch ( ... ) {
  1147. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1148. returnValue = 1;
  1149. }
  1150. }
  1151. const char *progname;
  1152. unsigned int returnValue;
  1153. unsigned int port;
  1154. const std::string &homeDir;
  1155. };
  1156. #ifdef __WINDOWS__
  1157. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1158. #else
  1159. int main(int argc,char **argv)
  1160. #endif
  1161. {
  1162. #ifdef __UNIX_LIKE__
  1163. signal(SIGHUP,&_sighandlerHup);
  1164. signal(SIGPIPE,SIG_IGN);
  1165. signal(SIGUSR1,SIG_IGN);
  1166. signal(SIGUSR2,SIG_IGN);
  1167. signal(SIGALRM,SIG_IGN);
  1168. signal(SIGINT,&_sighandlerQuit);
  1169. signal(SIGTERM,&_sighandlerQuit);
  1170. signal(SIGQUIT,&_sighandlerQuit);
  1171. /* Ensure that there are no inherited file descriptors open from a previous
  1172. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1173. * of it do not return, and should not do anything otherwise bad. */
  1174. {
  1175. int mfd = STDIN_FILENO;
  1176. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1177. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1178. for(int f=mfd+1;f<1024;++f)
  1179. ::close(f);
  1180. }
  1181. bool runAsDaemon = false;
  1182. #endif // __UNIX_LIKE__
  1183. #ifdef __WINDOWS__
  1184. {
  1185. WSADATA wsaData;
  1186. WSAStartup(MAKEWORD(2,2),&wsaData);
  1187. }
  1188. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1189. bool winRunFromCommandLine = true;
  1190. #else
  1191. bool winRunFromCommandLine = false;
  1192. #endif
  1193. #endif // __WINDOWS__
  1194. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1195. return idtool(argc,argv);
  1196. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1197. return cli(argc,argv);
  1198. std::string homeDir;
  1199. unsigned int port = ZT_DEFAULT_PORT;
  1200. bool skipRootCheck = false;
  1201. for(int i=1;i<argc;++i) {
  1202. if (argv[i][0] == '-') {
  1203. switch(argv[i][1]) {
  1204. case 'p': // port -- for both UDP and TCP, packets and control plane
  1205. port = Utils::strToUInt(argv[i] + 2);
  1206. if (port > 0xffff) {
  1207. printHelp(argv[0],stdout);
  1208. return 1;
  1209. }
  1210. break;
  1211. #ifdef __UNIX_LIKE__
  1212. case 'd': // Run in background as daemon
  1213. runAsDaemon = true;
  1214. break;
  1215. #endif // __UNIX_LIKE__
  1216. case 'U':
  1217. skipRootCheck = true;
  1218. break;
  1219. case 'v': // Display version
  1220. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1221. return 0;
  1222. case 'i': // Invoke idtool personality
  1223. if (argv[i][2]) {
  1224. printHelp(argv[0],stdout);
  1225. return 0;
  1226. } else return idtool(argc,argv);
  1227. case 'q': // Invoke cli personality
  1228. if (argv[i][2]) {
  1229. printHelp(argv[0],stdout);
  1230. return 0;
  1231. } else return cli(argc,argv);
  1232. #ifdef __WINDOWS__
  1233. case 'C': // Run from command line instead of as Windows service
  1234. winRunFromCommandLine = true;
  1235. break;
  1236. case 'I': { // Install this binary as a Windows service
  1237. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1238. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1239. return 1;
  1240. }
  1241. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1242. if (ret.length()) {
  1243. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1244. return 3;
  1245. }
  1246. return 0;
  1247. } break;
  1248. case 'R': { // Uninstall this binary as Windows service
  1249. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1250. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1251. return 1;
  1252. }
  1253. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1254. if (ret.length()) {
  1255. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1256. return 3;
  1257. }
  1258. return 0;
  1259. } break;
  1260. case 'D': {
  1261. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1262. if (err.length() > 0) {
  1263. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1264. return 3;
  1265. }
  1266. return 0;
  1267. } break;
  1268. #endif // __WINDOWS__
  1269. case 'h':
  1270. case '?':
  1271. default:
  1272. printHelp(argv[0],stdout);
  1273. return 0;
  1274. }
  1275. } else {
  1276. if (homeDir.length()) {
  1277. printHelp(argv[0],stdout);
  1278. return 0;
  1279. } else {
  1280. homeDir = argv[i];
  1281. }
  1282. }
  1283. }
  1284. if (!homeDir.length())
  1285. homeDir = OneService::platformDefaultHomePath();
  1286. if (!homeDir.length()) {
  1287. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1288. return 1;
  1289. } else {
  1290. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1291. std::string ptmp;
  1292. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1293. ptmp.push_back(ZT_PATH_SEPARATOR);
  1294. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1295. if (ptmp.length() > 0)
  1296. ptmp.push_back(ZT_PATH_SEPARATOR);
  1297. ptmp.append(*pi);
  1298. if ((*pi != ".")&&(*pi != "..")) {
  1299. if (!OSUtils::mkdir(ptmp))
  1300. throw std::runtime_error("home path does not exist, and could not create");
  1301. }
  1302. }
  1303. }
  1304. // This can be removed once the new controller code has been around for many versions
  1305. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1306. 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());
  1307. return 1;
  1308. }
  1309. #ifdef __UNIX_LIKE__
  1310. #ifndef ZT_ONE_NO_ROOT_CHECK
  1311. if ((!skipRootCheck)&&(getuid() != 0)) {
  1312. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1313. return 1;
  1314. }
  1315. #endif // !ZT_ONE_NO_ROOT_CHECK
  1316. if (runAsDaemon) {
  1317. long p = (long)fork();
  1318. if (p < 0) {
  1319. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1320. return 1;
  1321. } else if (p > 0)
  1322. return 0; // forked
  1323. // else p == 0, so we are daemonized
  1324. }
  1325. #endif // __UNIX_LIKE__
  1326. #ifdef __WINDOWS__
  1327. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1328. // when tap instances are created.
  1329. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1330. if (winRunFromCommandLine) {
  1331. // Running in "interactive" mode (mostly for debugging)
  1332. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1333. if (!skipRootCheck) {
  1334. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1335. return 1;
  1336. }
  1337. } else {
  1338. _winPokeAHole();
  1339. }
  1340. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1341. // continues on to ordinary command line execution code below...
  1342. } else {
  1343. // Running from service manager
  1344. _winPokeAHole();
  1345. ZeroTierOneService zt1WindowsService;
  1346. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1347. return 0;
  1348. } else {
  1349. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1350. return 1;
  1351. }
  1352. }
  1353. #endif // __WINDOWS__
  1354. #ifdef __UNIX_LIKE__
  1355. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1356. dropPrivileges(argv[0],homeDir);
  1357. #endif
  1358. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1359. {
  1360. // Write .pid file to home folder
  1361. FILE *pf = fopen(pidPath.c_str(),"w");
  1362. if (pf) {
  1363. fprintf(pf,"%ld",(long)getpid());
  1364. fclose(pf);
  1365. }
  1366. }
  1367. #endif // __UNIX_LIKE__
  1368. _OneServiceRunner thr(argv[0],homeDir,port);
  1369. thr.threadMain();
  1370. //Thread::join(Thread::start(&thr));
  1371. #ifdef __UNIX_LIKE__
  1372. OSUtils::rm(pidPath.c_str());
  1373. #endif
  1374. return thr.returnValue;
  1375. }