EmbeddedNetworkController.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdint.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <time.h>
  23. #ifndef _WIN32
  24. #include <sys/time.h>
  25. #endif
  26. #include <sys/types.h>
  27. #include <algorithm>
  28. #include <utility>
  29. #include <stdexcept>
  30. #include <set>
  31. #include <map>
  32. #include "../include/ZeroTierOne.h"
  33. #include "../node/Constants.hpp"
  34. #include "EmbeddedNetworkController.hpp"
  35. #include "../node/Node.hpp"
  36. #include "../node/Utils.hpp"
  37. #include "../node/CertificateOfMembership.hpp"
  38. #include "../node/NetworkConfig.hpp"
  39. #include "../node/Dictionary.hpp"
  40. #include "../node/InetAddress.hpp"
  41. #include "../node/MAC.hpp"
  42. #include "../node/Address.hpp"
  43. using json = nlohmann::json;
  44. // API version reported via JSON control plane
  45. #define ZT_NETCONF_CONTROLLER_API_VERSION 3
  46. // Number of requests to remember in member history
  47. #define ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH 24
  48. // Min duration between requests for an address/nwid combo to prevent floods
  49. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  50. // Nodes are considered active if they've queried in less than this long
  51. #define ZT_NETCONF_NODE_ACTIVE_THRESHOLD (ZT_NETWORK_AUTOCONF_DELAY * 2)
  52. namespace ZeroTier {
  53. // JSON blob I/O
  54. static json _readJson(const std::string &path)
  55. {
  56. std::string buf;
  57. if (OSUtils::readFile(path.c_str(),buf)) {
  58. try {
  59. return json::parse(buf);
  60. } catch ( ... ) {}
  61. }
  62. return json::object();
  63. }
  64. static bool _writeJson(const std::string &path,const json &obj)
  65. {
  66. return OSUtils::writeFile(path.c_str(),obj.dump(2));
  67. }
  68. // Get JSON values as unsigned integers, strings, or booleans, doing type conversion if possible
  69. static uint64_t _jI(const json &jv,const uint64_t dfl)
  70. {
  71. if (jv.is_number()) {
  72. return (uint64_t)jv;
  73. } else if (jv.is_string()) {
  74. std::string s = jv;
  75. return Utils::strToU64(s.c_str());
  76. } else if (jv.is_boolean()) {
  77. return ((bool)jv ? 1ULL : 0ULL);
  78. }
  79. return dfl;
  80. }
  81. static bool _jB(const json &jv,const bool dfl)
  82. {
  83. if (jv.is_boolean()) {
  84. return (bool)jv;
  85. } else if (jv.is_number()) {
  86. return ((uint64_t)jv > 0ULL);
  87. } else if (jv.is_string()) {
  88. std::string s = jv;
  89. if (s.length() > 0) {
  90. switch(s[0]) {
  91. case 't':
  92. case 'T':
  93. case '1':
  94. return true;
  95. }
  96. }
  97. return false;
  98. }
  99. return dfl;
  100. }
  101. static std::string _jS(const json &jv,const char *dfl)
  102. {
  103. if (jv.is_string()) {
  104. return jv;
  105. } else if (jv.is_number()) {
  106. char tmp[64];
  107. Utils::snprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  108. return tmp;
  109. } else if (jv.is_boolean()) {
  110. return ((bool)jv ? std::string("1") : std::string("0"));
  111. }
  112. return std::string((dfl) ? dfl : "");
  113. }
  114. static json _renderRule(ZT_VirtualNetworkRule &rule)
  115. {
  116. char tmp[128];
  117. json r = json::object();
  118. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  119. switch(rt) {
  120. case ZT_NETWORK_RULE_ACTION_DROP:
  121. r["type"] = "ACTION_DROP";
  122. break;
  123. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  124. r["type"] = "ACTION_ACCEPT";
  125. break;
  126. case ZT_NETWORK_RULE_ACTION_TEE:
  127. r["type"] = "ACTION_TEE";
  128. r["address"] = Address(rule.v.fwd.address).toString();
  129. r["flags"] = (unsigned int)rule.v.fwd.flags;
  130. r["length"] = (unsigned int)rule.v.fwd.length;
  131. break;
  132. case ZT_NETWORK_RULE_ACTION_WATCH:
  133. r["type"] = "ACTION_WATCH";
  134. r["address"] = Address(rule.v.fwd.address).toString();
  135. r["flags"] = (unsigned int)rule.v.fwd.flags;
  136. r["length"] = (unsigned int)rule.v.fwd.length;
  137. break;
  138. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  139. r["type"] = "ACTION_REDIRECT";
  140. r["address"] = Address(rule.v.fwd.address).toString();
  141. r["flags"] = (unsigned int)rule.v.fwd.flags;
  142. break;
  143. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG:
  144. r["type"] = "ACTION_DEBUG_LOG";
  145. break;
  146. default:
  147. break;
  148. }
  149. if (r.size() == 0) {
  150. switch(rt) {
  151. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  152. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  153. r["zt"] = Address(rule.v.zt).toString();
  154. break;
  155. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  156. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  157. r["zt"] = Address(rule.v.zt).toString();
  158. break;
  159. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  160. r["type"] = "MATCH_VLAN_ID";
  161. r["vlanId"] = (unsigned int)rule.v.vlanId;
  162. break;
  163. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  164. r["type"] = "MATCH_VLAN_PCP";
  165. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  166. break;
  167. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  168. r["type"] = "MATCH_VLAN_DEI";
  169. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  170. break;
  171. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  172. r["type"] = "MATCH_MAC_SOURCE";
  173. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  174. r["mac"] = tmp;
  175. break;
  176. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  177. r["type"] = "MATCH_MAC_DEST";
  178. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  179. r["mac"] = tmp;
  180. break;
  181. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  182. r["type"] = "MATCH_IPV4_SOURCE";
  183. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  184. break;
  185. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  186. r["type"] = "MATCH_IPV4_DEST";
  187. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  188. break;
  189. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  190. r["type"] = "MATCH_IPV6_SOURCE";
  191. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  192. break;
  193. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  194. r["type"] = "MATCH_IPV6_DEST";
  195. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  196. break;
  197. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  198. r["type"] = "MATCH_IP_TOS";
  199. r["ipTos"] = (unsigned int)rule.v.ipTos;
  200. break;
  201. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  202. r["type"] = "MATCH_IP_PROTOCOL";
  203. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  204. break;
  205. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  206. r["type"] = "MATCH_ETHERTYPE";
  207. r["etherType"] = (unsigned int)rule.v.etherType;
  208. break;
  209. case ZT_NETWORK_RULE_MATCH_ICMP:
  210. r["type"] = "MATCH_ICMP";
  211. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  212. if ((rule.v.icmp.flags & 0x01) != 0)
  213. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  214. else r["icmpCode"] = json();
  215. break;
  216. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  217. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  218. r["start"] = (unsigned int)rule.v.port[0];
  219. r["end"] = (unsigned int)rule.v.port[1];
  220. break;
  221. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  222. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  223. r["start"] = (unsigned int)rule.v.port[0];
  224. r["end"] = (unsigned int)rule.v.port[1];
  225. break;
  226. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  227. r["type"] = "MATCH_CHARACTERISTICS";
  228. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics);
  229. r["mask"] = tmp;
  230. break;
  231. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  232. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  233. r["start"] = (unsigned int)rule.v.frameSize[0];
  234. r["end"] = (unsigned int)rule.v.frameSize[1];
  235. break;
  236. case ZT_NETWORK_RULE_MATCH_RANDOM:
  237. r["type"] = "MATCH_RANDOM";
  238. r["probability"] = (unsigned long)rule.v.randomProbability;
  239. break;
  240. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  241. r["type"] = "MATCH_TAGS_DIFFERENCE";
  242. r["id"] = rule.v.tag.id;
  243. r["value"] = rule.v.tag.value;
  244. break;
  245. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  246. r["type"] = "MATCH_TAGS_BITWISE_AND";
  247. r["id"] = rule.v.tag.id;
  248. r["value"] = rule.v.tag.value;
  249. break;
  250. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  251. r["type"] = "MATCH_TAGS_BITWISE_OR";
  252. r["id"] = rule.v.tag.id;
  253. r["value"] = rule.v.tag.value;
  254. break;
  255. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  256. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  257. r["id"] = rule.v.tag.id;
  258. r["value"] = rule.v.tag.value;
  259. break;
  260. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  261. r["type"] = "MATCH_TAGS_EQUAL";
  262. r["id"] = rule.v.tag.id;
  263. r["value"] = rule.v.tag.value;
  264. break;
  265. default:
  266. break;
  267. }
  268. if (r.size() > 0) {
  269. r["not"] = ((rule.t & 0x80) != 0);
  270. r["or"] = ((rule.t & 0x40) != 0);
  271. }
  272. }
  273. return r;
  274. }
  275. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  276. {
  277. if (!r.is_object())
  278. return false;
  279. const std::string t(_jS(r["type"],""));
  280. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  281. if (_jB(r["not"],false))
  282. rule.t = 0x80;
  283. else rule.t = 0x00;
  284. if (_jB(r["or"],false))
  285. rule.t |= 0x40;
  286. if (t == "ACTION_DROP") {
  287. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  288. return true;
  289. } else if (t == "ACTION_ACCEPT") {
  290. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  291. return true;
  292. } else if (t == "ACTION_TEE") {
  293. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  294. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["address"],"0").c_str()) & 0xffffffffffULL;
  295. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  296. rule.v.fwd.length = (uint16_t)(_jI(r["length"],0ULL) & 0xffffULL);
  297. return true;
  298. } else if (t == "ACTION_WATCH") {
  299. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  300. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["address"],"0").c_str()) & 0xffffffffffULL;
  301. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  302. rule.v.fwd.length = (uint16_t)(_jI(r["length"],0ULL) & 0xffffULL);
  303. return true;
  304. } else if (t == "ACTION_REDIRECT") {
  305. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  306. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  307. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  308. return true;
  309. } else if (t == "ACTION_DEBUG_LOG") {
  310. rule.t |= ZT_NETWORK_RULE_ACTION_DEBUG_LOG;
  311. return true;
  312. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  313. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  314. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  315. return true;
  316. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  317. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  318. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  319. return true;
  320. } else if (t == "MATCH_VLAN_ID") {
  321. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  322. rule.v.vlanId = (uint16_t)(_jI(r["vlanId"],0ULL) & 0xffffULL);
  323. return true;
  324. } else if (t == "MATCH_VLAN_PCP") {
  325. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  326. rule.v.vlanPcp = (uint8_t)(_jI(r["vlanPcp"],0ULL) & 0xffULL);
  327. return true;
  328. } else if (t == "MATCH_VLAN_DEI") {
  329. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  330. rule.v.vlanDei = (uint8_t)(_jI(r["vlanDei"],0ULL) & 0xffULL);
  331. return true;
  332. } else if (t == "MATCH_MAC_SOURCE") {
  333. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  334. const std::string mac(_jS(r["mac"],"0"));
  335. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  336. return true;
  337. } else if (t == "MATCH_MAC_DEST") {
  338. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  339. const std::string mac(_jS(r["mac"],"0"));
  340. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  341. return true;
  342. } else if (t == "MATCH_IPV4_SOURCE") {
  343. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  344. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  345. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  346. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  347. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  348. return true;
  349. } else if (t == "MATCH_IPV4_DEST") {
  350. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  351. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  352. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  353. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  354. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  355. return true;
  356. } else if (t == "MATCH_IPV6_SOURCE") {
  357. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  358. InetAddress ip(_jS(r["ip"],"::0"));
  359. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  360. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  361. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  362. return true;
  363. } else if (t == "MATCH_IPV6_DEST") {
  364. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  365. InetAddress ip(_jS(r["ip"],"::0"));
  366. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  367. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  368. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  369. return true;
  370. } else if (t == "MATCH_IP_TOS") {
  371. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  372. rule.v.ipTos = (uint8_t)(_jI(r["ipTos"],0ULL) & 0xffULL);
  373. return true;
  374. } else if (t == "MATCH_IP_PROTOCOL") {
  375. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  376. rule.v.ipProtocol = (uint8_t)(_jI(r["ipProtocol"],0ULL) & 0xffULL);
  377. return true;
  378. } else if (t == "MATCH_ETHERTYPE") {
  379. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  380. rule.v.etherType = (uint16_t)(_jI(r["etherType"],0ULL) & 0xffffULL);
  381. return true;
  382. } else if (t == "MATCH_ICMP") {
  383. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  384. rule.v.icmp.type = (uint8_t)(_jI(r["icmpType"],0ULL) & 0xffULL);
  385. json &code = r["icmpCode"];
  386. if (code.is_null()) {
  387. rule.v.icmp.code = 0;
  388. rule.v.icmp.flags = 0x00;
  389. } else {
  390. rule.v.icmp.code = (uint8_t)(_jI(code,0ULL) & 0xffULL);
  391. rule.v.icmp.flags = 0x01;
  392. }
  393. return true;
  394. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  395. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  396. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  397. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  398. return true;
  399. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  400. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  401. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  402. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  403. return true;
  404. } else if (t == "MATCH_CHARACTERISTICS") {
  405. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  406. if (r.count("mask")) {
  407. json &v = r["mask"];
  408. if (v.is_number()) {
  409. rule.v.characteristics = v;
  410. } else {
  411. std::string tmp = v;
  412. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  413. }
  414. }
  415. return true;
  416. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  417. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  418. rule.v.frameSize[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  419. rule.v.frameSize[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  420. return true;
  421. } else if (t == "MATCH_RANDOM") {
  422. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  423. rule.v.randomProbability = (uint32_t)(_jI(r["probability"],0ULL) & 0xffffffffULL);
  424. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  425. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  426. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  427. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  428. return true;
  429. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  430. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  431. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  432. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  433. return true;
  434. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  435. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  436. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  437. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  438. return true;
  439. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  440. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  441. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  442. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  443. return true;
  444. } else if (t == "MATCH_TAGS_EQUAL") {
  445. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  446. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  447. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  448. return true;
  449. }
  450. return false;
  451. }
  452. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath) :
  453. _node(node),
  454. _path(dbPath),
  455. _daemonRun(true)
  456. {
  457. OSUtils::mkdir(dbPath);
  458. OSUtils::lockDownFile(dbPath,true); // networks might contain auth tokens, etc., so restrict directory permissions
  459. _daemon = Thread::start(this);
  460. }
  461. EmbeddedNetworkController::~EmbeddedNetworkController()
  462. {
  463. }
  464. void EmbeddedNetworkController::threadMain()
  465. throw()
  466. {
  467. uint64_t lastUpdatedNetworkMemberCache = 0;
  468. while (_daemonRun) {
  469. // Every 60 seconds we rescan the filesystem for network members and rebuild our cache
  470. if ((OSUtils::now() - lastUpdatedNetworkMemberCache) >= 60000) {
  471. const std::vector<std::string> networks(OSUtils::listSubdirectories((_path + ZT_PATH_SEPARATOR_S + "network").c_str()));
  472. for(auto n=networks.begin();n!=networks.end();++n) {
  473. if (n->length() == 16) {
  474. const std::vector<std::string> members(OSUtils::listSubdirectories((*n + ZT_PATH_SEPARATOR_S + "member").c_str()));
  475. std::map<Address,nlohmann::json> newCache;
  476. for(auto m=members.begin();m!=members.end();++m) {
  477. if (m->length() == ZT_ADDRESS_LENGTH_HEX) {
  478. const Address maddr(*m);
  479. try {
  480. const json mj(_readJson((_path + ZT_PATH_SEPARATOR_S + "network" + ZT_PATH_SEPARATOR_S + *n + ZT_PATH_SEPARATOR_S + "member" + ZT_PATH_SEPARATOR_S + *m + ZT_PATH_SEPARATOR_S + "config.json")));
  481. if ((mj.is_object())&&(mj.size() > 0)) {
  482. newCache[maddr] = mj;
  483. }
  484. } catch ( ... ) {}
  485. }
  486. }
  487. {
  488. Mutex::Lock _l(_networkMemberCache_m);
  489. _networkMemberCache[Utils::hexStrToU64(n->c_str())] = newCache;
  490. }
  491. }
  492. }
  493. lastUpdatedNetworkMemberCache = OSUtils::now();
  494. }
  495. Thread::sleep(25);
  496. }
  497. }
  498. NetworkController::ResultCode EmbeddedNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData,NetworkConfig &nc)
  499. {
  500. if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
  501. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  502. }
  503. const uint64_t now = OSUtils::now();
  504. // Check rate limit circuit breaker to prevent flooding
  505. {
  506. Mutex::Lock _l(_lastRequestTime_m);
  507. uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
  508. if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  509. return NetworkController::NETCONF_QUERY_IGNORE;
  510. lrt = now;
  511. }
  512. json network(_readJson(_networkJP(nwid,false)));
  513. if (!network.size())
  514. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  515. const std::string memberJP(_memberJP(nwid,identity.address(),true));
  516. json member(_readJson(memberJP));
  517. _initMember(member);
  518. {
  519. std::string haveIdStr(_jS(member["identity"],""));
  520. if (haveIdStr.length() > 0) {
  521. // If we already know this member's identity perform a full compare. This prevents
  522. // a "collision" from being able to auth onto our network in place of an already
  523. // known member.
  524. try {
  525. if (Identity(haveIdStr.c_str()) != identity)
  526. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  527. } catch ( ... ) {
  528. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  529. }
  530. } else {
  531. // If we do not yet know this member's identity, learn it.
  532. member["identity"] = identity.toString(false);
  533. }
  534. }
  535. // These are always the same, but make sure they are set
  536. member["id"] = identity.address().toString();
  537. member["address"] = member["id"];
  538. member["nwid"] = network["id"];
  539. // Determine whether and how member is authorized
  540. const char *authorizedBy = (const char *)0;
  541. if (_jB(member["authorized"],false)) {
  542. authorizedBy = "memberIsAuthorized";
  543. } else if (!_jB(network["private"],true)) {
  544. authorizedBy = "networkIsPublic";
  545. if (!member.count("authorized")) {
  546. member["authorized"] = true;
  547. json ah;
  548. ah["a"] = true;
  549. ah["by"] = authorizedBy;
  550. ah["ts"] = now;
  551. ah["ct"] = json();
  552. ah["c"] = json();
  553. member["authHistory"].push_back(ah);
  554. member["lastModified"] = now;
  555. json &revj = member["revision"];
  556. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  557. }
  558. } else {
  559. char presentedAuth[512];
  560. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  561. presentedAuth[511] = (char)0; // sanity check
  562. // Check for bearer token presented by member
  563. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  564. const char *const presentedToken = presentedAuth + 6;
  565. json &authTokens = network["authTokens"];
  566. if (authTokens.is_array()) {
  567. for(unsigned long i=0;i<authTokens.size();++i) {
  568. json &token = authTokens[i];
  569. if (token.is_object()) {
  570. const uint64_t expires = _jI(token["expires"],0ULL);
  571. const uint64_t maxUses = _jI(token["maxUsesPerMember"],0ULL);
  572. std::string tstr = _jS(token["token"],"");
  573. if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
  574. bool usable = (maxUses == 0);
  575. if (!usable) {
  576. uint64_t useCount = 0;
  577. json &ahist = member["authHistory"];
  578. if (ahist.is_array()) {
  579. for(unsigned long j=0;j<ahist.size();++j) {
  580. json &ah = ahist[j];
  581. if ((_jS(ah["ct"],"") == "token")&&(_jS(ah["c"],"") == tstr)&&(_jB(ah["a"],false)))
  582. ++useCount;
  583. }
  584. }
  585. usable = (useCount < maxUses);
  586. }
  587. if (usable) {
  588. authorizedBy = "token";
  589. member["authorized"] = true;
  590. json ah;
  591. ah["a"] = true;
  592. ah["by"] = authorizedBy;
  593. ah["ts"] = now;
  594. ah["ct"] = "token";
  595. ah["c"] = tstr;
  596. member["authHistory"].push_back(ah);
  597. member["lastModified"] = now;
  598. json &revj = member["revision"];
  599. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  600. }
  601. }
  602. }
  603. }
  604. }
  605. }
  606. }
  607. }
  608. // Log this request
  609. {
  610. json rlEntry = json::object();
  611. rlEntry["ts"] = now;
  612. rlEntry["authorized"] = (authorizedBy) ? true : false;
  613. rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
  614. rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  615. rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  616. rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  617. rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  618. if (fromAddr)
  619. rlEntry["fromAddr"] = fromAddr.toString();
  620. json recentLog = json::array();
  621. recentLog.push_back(rlEntry);
  622. json &oldLog = member["recentLog"];
  623. if (oldLog.is_array()) {
  624. for(unsigned long i=0;i<oldLog.size();++i) {
  625. recentLog.push_back(oldLog[i]);
  626. if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
  627. break;
  628. }
  629. }
  630. member["recentLog"] = recentLog;
  631. }
  632. // If they are not authorized, STOP!
  633. if (!authorizedBy) {
  634. _writeJson(memberJP,member);
  635. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  636. }
  637. // -------------------------------------------------------------------------
  638. // If we made it this far, they are authorized.
  639. // -------------------------------------------------------------------------
  640. _NetworkMemberInfo nmi;
  641. _getNetworkMemberInfo(now,nwid,nmi);
  642. // Compute credential TTL. This is the "moving window" for COM agreement and
  643. // the global TTL for Capability and Tag objects. (The same value is used
  644. // for both.) This is computed by reference to the last time we deauthorized
  645. // a member, since within the time period since this event any temporal
  646. // differences are not particularly relevant.
  647. uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  648. if (now > nmi.mostRecentDeauthTime)
  649. credentialtmd += (now - nmi.mostRecentDeauthTime);
  650. if (credentialtmd > ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA)
  651. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  652. nc.networkId = nwid;
  653. nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  654. nc.timestamp = now;
  655. nc.credentialTimeMaxDelta = credentialtmd;
  656. nc.revision = _jI(network["revision"],0ULL);
  657. nc.issuedTo = identity.address();
  658. if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  659. if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  660. Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
  661. nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
  662. for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab)
  663. nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  664. json &v4AssignMode = network["v4AssignMode"];
  665. json &v6AssignMode = network["v6AssignMode"];
  666. json &ipAssignmentPools = network["ipAssignmentPools"];
  667. json &routes = network["routes"];
  668. json &rules = network["rules"];
  669. json &capabilities = network["capabilities"];
  670. json &memberCapabilities = member["capabilities"];
  671. json &memberTags = member["tags"];
  672. if (rules.is_array()) {
  673. for(unsigned long i=0;i<rules.size();++i) {
  674. if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
  675. break;
  676. if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
  677. ++nc.ruleCount;
  678. }
  679. }
  680. if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
  681. std::map< uint64_t,json * > capsById;
  682. for(unsigned long i=0;i<capabilities.size();++i) {
  683. json &cap = capabilities[i];
  684. if (cap.is_object())
  685. capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
  686. }
  687. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  688. const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
  689. json *cap = capsById[capId];
  690. if ((cap->is_object())&&(cap->size() > 0)) {
  691. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  692. unsigned int caprc = 0;
  693. json &caprj = (*cap)["rules"];
  694. if ((caprj.is_array())&&(caprj.size() > 0)) {
  695. for(unsigned long j=0;j<caprj.size();++j) {
  696. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  697. break;
  698. if (_parseRule(caprj[j],capr[caprc]))
  699. ++caprc;
  700. }
  701. }
  702. nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  703. if (nc.capabilities[nc.capabilityCount].sign(signingId,identity.address()))
  704. ++nc.capabilityCount;
  705. if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  706. break;
  707. }
  708. }
  709. }
  710. if (memberTags.is_array()) {
  711. std::map< uint32_t,uint32_t > tagsById;
  712. for(unsigned long i=0;i<memberTags.size();++i) {
  713. json &t = memberTags[i];
  714. if ((t.is_array())&&(t.size() == 2))
  715. tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
  716. }
  717. for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
  718. if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
  719. break;
  720. nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  721. if (nc.tags[nc.tagCount].sign(signingId))
  722. ++nc.tagCount;
  723. }
  724. }
  725. if (routes.is_array()) {
  726. for(unsigned long i=0;i<routes.size();++i) {
  727. if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
  728. break;
  729. json &route = routes[i];
  730. json &target = route["target"];
  731. json &via = route["via"];
  732. if (target.is_string()) {
  733. const InetAddress t(target.get<std::string>());
  734. InetAddress v;
  735. if (via.is_string()) v.fromString(via.get<std::string>());
  736. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  737. ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
  738. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  739. if (v.ss_family == t.ss_family)
  740. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  741. ++nc.routeCount;
  742. }
  743. }
  744. }
  745. }
  746. const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
  747. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  748. if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  749. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  750. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  751. }
  752. if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  753. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  754. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  755. }
  756. }
  757. bool haveManagedIpv4AutoAssignment = false;
  758. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  759. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  760. if (ipAssignments.is_array()) {
  761. for(unsigned long i=0;i<ipAssignments.size();++i) {
  762. if (!ipAssignments[i].is_string())
  763. continue;
  764. std::string ips = ipAssignments[i];
  765. InetAddress ip(ips);
  766. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  767. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  768. // of user error / poor UX.
  769. int routedNetmaskBits = 0;
  770. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  771. if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
  772. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  773. }
  774. if (routedNetmaskBits > 0) {
  775. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  776. ip.setPort(routedNetmaskBits);
  777. nc.staticIps[nc.staticIpCount++] = ip;
  778. }
  779. if (ip.ss_family == AF_INET)
  780. haveManagedIpv4AutoAssignment = true;
  781. else if (ip.ss_family == AF_INET6)
  782. haveManagedIpv6AutoAssignment = true;
  783. }
  784. }
  785. } else {
  786. ipAssignments = json::array();
  787. }
  788. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  789. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  790. json &pool = ipAssignmentPools[p];
  791. if (pool.is_object()) {
  792. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  793. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  794. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  795. uint64_t s[2],e[2],x[2],xx[2];
  796. memcpy(s,ipRangeStart.rawIpData(),16);
  797. memcpy(e,ipRangeEnd.rawIpData(),16);
  798. s[0] = Utils::ntoh(s[0]);
  799. s[1] = Utils::ntoh(s[1]);
  800. e[0] = Utils::ntoh(e[0]);
  801. e[1] = Utils::ntoh(e[1]);
  802. x[0] = s[0];
  803. x[1] = s[1];
  804. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  805. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  806. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  807. xx[0] = Utils::hton(x[0]);
  808. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  809. } else {
  810. // Otherwise pick random addresses -- this technically doesn't explore the whole range if the lower 64 bit range is >= 1 but that won't matter since that would be huge anyway
  811. Utils::getSecureRandom((void *)xx,16);
  812. if ((e[0] > s[0]))
  813. xx[0] %= (e[0] - s[0]);
  814. else xx[0] = 0;
  815. if ((e[1] > s[1]))
  816. xx[1] %= (e[1] - s[1]);
  817. else xx[1] = 0;
  818. xx[0] = Utils::hton(x[0] + xx[0]);
  819. xx[1] = Utils::hton(x[1] + xx[1]);
  820. }
  821. InetAddress ip6((const void *)xx,16,0);
  822. // Check if this IP is within a local-to-Ethernet routed network
  823. int routedNetmaskBits = 0;
  824. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  825. if ( (!nc.routes[rk].via.ss_family) && (nc.routes[rk].target.ss_family == AF_INET6) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip6)) )
  826. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  827. }
  828. // If it's routed, then try to claim and assign it and if successful end loop
  829. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
  830. ipAssignments.push_back(ip6.toIpString());
  831. member["ipAssignments"] = ipAssignments;
  832. ip6.setPort((unsigned int)routedNetmaskBits);
  833. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  834. nc.staticIps[nc.staticIpCount++] = ip6;
  835. haveManagedIpv6AutoAssignment = true;
  836. break;
  837. }
  838. }
  839. }
  840. }
  841. }
  842. }
  843. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  844. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  845. json &pool = ipAssignmentPools[p];
  846. if (pool.is_object()) {
  847. InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
  848. InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
  849. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  850. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  851. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  852. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  853. continue;
  854. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  855. // Start with the LSB of the member's address
  856. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  857. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  858. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  859. ++ipTrialCounter;
  860. if ((ip & 0x000000ff) == 0x000000ff)
  861. continue; // don't allow addresses that end in .255
  862. // Check if this IP is within a local-to-Ethernet routed network
  863. int routedNetmaskBits = -1;
  864. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  865. if (nc.routes[rk].target.ss_family == AF_INET) {
  866. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
  867. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
  868. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  869. routedNetmaskBits = targetBits;
  870. break;
  871. }
  872. }
  873. }
  874. // If it's routed, then try to claim and assign it and if successful end loop
  875. const InetAddress ip4(Utils::hton(ip),0);
  876. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
  877. ipAssignments.push_back(ip4.toIpString());
  878. member["ipAssignments"] = ipAssignments;
  879. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  880. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
  881. v4ip->sin_family = AF_INET;
  882. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  883. v4ip->sin_addr.s_addr = Utils::hton(ip);
  884. }
  885. haveManagedIpv4AutoAssignment = true;
  886. break;
  887. }
  888. }
  889. }
  890. }
  891. }
  892. }
  893. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  894. if (com.sign(signingId)) {
  895. nc.com = com;
  896. } else {
  897. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  898. }
  899. _writeJson(memberJP,member);
  900. return NetworkController::NETCONF_QUERY_OK;
  901. }
  902. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  903. const std::vector<std::string> &path,
  904. const std::map<std::string,std::string> &urlArgs,
  905. const std::map<std::string,std::string> &headers,
  906. const std::string &body,
  907. std::string &responseBody,
  908. std::string &responseContentType)
  909. {
  910. if ((path.size() > 0)&&(path[0] == "network")) {
  911. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  912. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  913. char nwids[24];
  914. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  915. json network(_readJson(_networkJP(nwid,false)));
  916. if (!network.size())
  917. return 404;
  918. if (path.size() >= 3) {
  919. if (path[2] == "member") {
  920. if (path.size() >= 4) {
  921. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  922. json member(_readJson(_memberJP(nwid,Address(address),false)));
  923. if (!member.size())
  924. return 404;
  925. _addMemberNonPersistedFields(member,OSUtils::now());
  926. responseBody = member.dump(2);
  927. responseContentType = "application/json";
  928. return 200;
  929. } else {
  930. responseBody = "{";
  931. std::vector<std::string> members(OSUtils::listSubdirectories((_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member").c_str()));
  932. for(std::vector<std::string>::iterator i(members.begin());i!=members.end();++i) {
  933. if (i->length() == ZT_ADDRESS_LENGTH_HEX) {
  934. json member(_readJson(_memberJP(nwid,Address(Utils::hexStrToU64(i->c_str())),false)));
  935. if (member.size()) {
  936. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  937. responseBody.append(*i);
  938. responseBody.append("\":");
  939. responseBody.append(_jS(member["revision"],"0"));
  940. }
  941. }
  942. }
  943. responseBody.push_back('}');
  944. responseContentType = "application/json";
  945. return 200;
  946. }
  947. } else if ((path[2] == "test")&&(path.size() >= 4)) {
  948. Mutex::Lock _l(_circuitTests_m);
  949. std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
  950. if ((cte != _circuitTests.end())&&(cte->second.test)) {
  951. responseBody = "[";
  952. responseBody.append(cte->second.jsonResults);
  953. responseBody.push_back(']');
  954. responseContentType = "application/json";
  955. return 200;
  956. } // else 404
  957. } // else 404
  958. } else {
  959. const uint64_t now = OSUtils::now();
  960. _NetworkMemberInfo nmi;
  961. _getNetworkMemberInfo(now,nwid,nmi);
  962. _addNetworkNonPersistedFields(network,now,nmi);
  963. responseBody = network.dump(2);
  964. responseContentType = "application/json";
  965. return 200;
  966. }
  967. } else if (path.size() == 1) {
  968. responseBody = "[";
  969. std::vector<std::string> networks(OSUtils::listSubdirectories((_path + ZT_PATH_SEPARATOR_S + "network").c_str()));
  970. for(auto i(networks.begin());i!=networks.end();++i) {
  971. if (i->length() == 16) {
  972. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  973. responseBody.append(*i);
  974. responseBody.append("\"");
  975. }
  976. }
  977. responseBody.push_back(']');
  978. responseContentType = "application/json";
  979. return 200;
  980. } // else 404
  981. } else {
  982. char tmp[4096];
  983. Utils::snprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now());
  984. responseBody = tmp;
  985. responseContentType = "application/json";
  986. return 200;
  987. }
  988. return 404;
  989. }
  990. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  991. const std::vector<std::string> &path,
  992. const std::map<std::string,std::string> &urlArgs,
  993. const std::map<std::string,std::string> &headers,
  994. const std::string &body,
  995. std::string &responseBody,
  996. std::string &responseContentType)
  997. {
  998. if (path.empty())
  999. return 404;
  1000. json b;
  1001. try {
  1002. b = json::parse(body);
  1003. if (!b.is_object()) {
  1004. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  1005. responseContentType = "application/json";
  1006. return 400;
  1007. }
  1008. } catch (std::exception &exc) {
  1009. responseBody = std::string("{ \"message\": \"body JSON is invalid: ") + exc.what() + "\" }";
  1010. responseContentType = "application/json";
  1011. return 400;
  1012. } catch ( ... ) {
  1013. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  1014. responseContentType = "application/json";
  1015. return 400;
  1016. }
  1017. const uint64_t now = OSUtils::now();
  1018. if (path[0] == "network") {
  1019. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1020. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1021. char nwids[24];
  1022. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  1023. if (path.size() >= 3) {
  1024. json network(_readJson(_networkJP(nwid,false)));
  1025. if (!network.size())
  1026. return 404;
  1027. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1028. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1029. char addrs[24];
  1030. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  1031. json member(_readJson(_memberJP(nwid,Address(address),true)));
  1032. _initMember(member);
  1033. try {
  1034. if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
  1035. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
  1036. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  1037. if (b.count("authorized")) {
  1038. const bool newAuth = _jB(b["authorized"],false);
  1039. if (newAuth != _jB(member["authorized"],false)) {
  1040. member["authorized"] = newAuth;
  1041. json ah;
  1042. ah["a"] = newAuth;
  1043. ah["by"] = "api";
  1044. ah["ts"] = now;
  1045. ah["ct"] = json();
  1046. ah["c"] = json();
  1047. member["authHistory"].push_back(ah);
  1048. }
  1049. }
  1050. if (b.count("ipAssignments")) {
  1051. auto ipa = b["ipAssignments"];
  1052. if (ipa.is_array()) {
  1053. json mipa(json::array());
  1054. for(unsigned long i=0;i<ipa.size();++i) {
  1055. std::string ips = ipa[i];
  1056. InetAddress ip(ips);
  1057. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1058. mipa.push_back(ip.toIpString());
  1059. }
  1060. }
  1061. member["ipAssignments"] = mipa;
  1062. }
  1063. }
  1064. if (b.count("tags")) {
  1065. auto tags = b["tags"];
  1066. if (tags.is_array()) {
  1067. std::map<uint64_t,uint64_t> mtags;
  1068. for(unsigned long i=0;i<tags.size();++i) {
  1069. auto tag = tags[i];
  1070. if ((tag.is_array())&&(tag.size() == 2))
  1071. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  1072. }
  1073. json mtagsa = json::array();
  1074. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1075. json ta = json::array();
  1076. ta.push_back(t->first);
  1077. ta.push_back(t->second);
  1078. mtagsa.push_back(ta);
  1079. }
  1080. member["tags"] = mtagsa;
  1081. }
  1082. }
  1083. if (b.count("capabilities")) {
  1084. auto capabilities = b["capabilities"];
  1085. if (capabilities.is_array()) {
  1086. json mcaps = json::array();
  1087. for(unsigned long i=0;i<capabilities.size();++i) {
  1088. mcaps.push_back(_jI(capabilities[i],0ULL));
  1089. }
  1090. std::sort(mcaps.begin(),mcaps.end());
  1091. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1092. member["capabilities"] = mcaps;
  1093. }
  1094. }
  1095. } catch ( ... ) {
  1096. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  1097. responseContentType = "application/json";
  1098. return 400;
  1099. }
  1100. member["id"] = addrs;
  1101. member["address"] = addrs; // legacy
  1102. member["nwid"] = nwids;
  1103. member["lastModified"] = now;
  1104. auto revj = member["revision"];
  1105. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  1106. _writeJson(_memberJP(nwid,Address(address),true).c_str(),member);
  1107. {
  1108. Mutex::Lock _l(_networkMemberCache_m);
  1109. _networkMemberCache[nwid][Address(address)] = member;
  1110. }
  1111. // Add non-persisted fields
  1112. member["clock"] = now;
  1113. responseBody = member.dump(2);
  1114. responseContentType = "application/json";
  1115. return 200;
  1116. } else if ((path.size() == 3)&&(path[2] == "test")) {
  1117. Mutex::Lock _l(_circuitTests_m);
  1118. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  1119. memset(test,0,sizeof(ZT_CircuitTest));
  1120. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  1121. test->credentialNetworkId = nwid;
  1122. test->ptr = (void *)this;
  1123. json hops = b["hops"];
  1124. if (hops.is_array()) {
  1125. for(unsigned long i=0;i<hops.size();++i) {
  1126. auto hops2 = hops[i];
  1127. if (hops2.is_array()) {
  1128. for(unsigned long j=0;j<hops2.size();++j) {
  1129. std::string s = hops2[j];
  1130. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1131. }
  1132. } else if (hops2.is_string()) {
  1133. std::string s = hops2;
  1134. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1135. }
  1136. }
  1137. }
  1138. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1139. if (!test->hopCount) {
  1140. ::free((void *)test);
  1141. responseBody = "{ \"message\": \"a test must contain at least one hop\" }";
  1142. responseContentType = "application/json";
  1143. return 400;
  1144. }
  1145. test->timestamp = OSUtils::now();
  1146. _CircuitTestEntry &te = _circuitTests[test->testId];
  1147. te.test = test;
  1148. te.jsonResults = "";
  1149. if (_node)
  1150. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1151. else return 500;
  1152. char json[1024];
  1153. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1154. responseBody = json;
  1155. responseContentType = "application/json";
  1156. return 200;
  1157. } // else 404
  1158. } else {
  1159. // POST to network ID
  1160. // Magic ID ending with ______ picks a random unused network ID
  1161. if (path[1].substr(10) == "______") {
  1162. nwid = 0;
  1163. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1164. uint64_t nwidPostfix = 0;
  1165. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1166. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1167. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1168. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1169. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1170. if (!OSUtils::fileExists(_networkJP(tryNwid,false).c_str())) {
  1171. nwid = tryNwid;
  1172. break;
  1173. }
  1174. }
  1175. if (!nwid)
  1176. return 503;
  1177. }
  1178. json network(_readJson(_networkJP(nwid,true)));
  1179. _initNetwork(network);
  1180. try {
  1181. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1182. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1183. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1184. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1185. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1186. if (b.count("v4AssignMode")) {
  1187. json nv4m;
  1188. json &v4m = b["v4AssignMode"];
  1189. if (v4m.is_string()) { // backward compatibility
  1190. nv4m["zt"] = (_jS(v4m,"") == "zt");
  1191. } else if (v4m.is_object()) {
  1192. nv4m["zt"] = _jB(v4m["zt"],false);
  1193. } else nv4m["zt"] = false;
  1194. network["v4AssignMode"] = nv4m;
  1195. }
  1196. if (b.count("v6AssignMode")) {
  1197. json nv6m;
  1198. json &v6m = b["v6AssignMode"];
  1199. if (!nv6m.is_object()) nv6m = json::object();
  1200. if (v6m.is_string()) { // backward compatibility
  1201. std::vector<std::string> v6ms(Utils::split(_jS(v6m,"").c_str(),",","",""));
  1202. std::sort(v6ms.begin(),v6ms.end());
  1203. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  1204. nv6m["rfc4193"] = false;
  1205. nv6m["zt"] = false;
  1206. nv6m["6plane"] = false;
  1207. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  1208. if (*i == "rfc4193")
  1209. nv6m["rfc4193"] = true;
  1210. else if (*i == "zt")
  1211. nv6m["zt"] = true;
  1212. else if (*i == "6plane")
  1213. nv6m["6plane"] = true;
  1214. }
  1215. } else if (v6m.is_object()) {
  1216. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1217. if (v6m.count("zt")) nv6m["zt"] = _jB(v6m["zt"],false);
  1218. if (v6m.count("6plane")) nv6m["6plane"] = _jB(v6m["6plane"],false);
  1219. } else {
  1220. nv6m["rfc4193"] = false;
  1221. nv6m["zt"] = false;
  1222. nv6m["6plane"] = false;
  1223. }
  1224. network["v6AssignMode"] = nv6m;
  1225. }
  1226. if (b.count("routes")) {
  1227. json &rts = b["routes"];
  1228. if (rts.is_array()) {
  1229. json nrts = json::array();
  1230. for(unsigned long i=0;i<rts.size();++i) {
  1231. json &rt = rts[i];
  1232. if (rt.is_object()) {
  1233. json &target = rt["target"];
  1234. json &via = rt["via"];
  1235. if (target.is_string()) {
  1236. InetAddress t(target.get<std::string>());
  1237. InetAddress v;
  1238. if (via.is_string()) v.fromString(via.get<std::string>());
  1239. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  1240. json tmp;
  1241. tmp["target"] = t.toString();
  1242. if (v.ss_family == t.ss_family)
  1243. tmp["via"] = v.toIpString();
  1244. else tmp["via"] = json();
  1245. nrts.push_back(tmp);
  1246. }
  1247. }
  1248. }
  1249. }
  1250. network["routes"] = nrts;
  1251. }
  1252. }
  1253. if (b.count("ipAssignmentPools")) {
  1254. json &ipp = b["ipAssignmentPools"];
  1255. if (ipp.is_array()) {
  1256. json nipp = json::array();
  1257. for(unsigned long i=0;i<ipp.size();++i) {
  1258. auto ip = ipp[i];
  1259. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1260. InetAddress f(_jS(ip["ipRangeStart"],""));
  1261. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1262. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1263. json tmp = json::object();
  1264. tmp["ipRangeStart"] = f.toIpString();
  1265. tmp["ipRangeEnd"] = t.toIpString();
  1266. nipp.push_back(tmp);
  1267. }
  1268. }
  1269. }
  1270. network["ipAssignmentPools"] = nipp;
  1271. }
  1272. }
  1273. if (b.count("rules")) {
  1274. json &rules = b["rules"];
  1275. if (rules.is_array()) {
  1276. json nrules = json::array();
  1277. for(unsigned long i=0;i<rules.size();++i) {
  1278. json &rule = rules[i];
  1279. if (rule.is_object()) {
  1280. ZT_VirtualNetworkRule ztr;
  1281. if (_parseRule(rule,ztr))
  1282. nrules.push_back(_renderRule(ztr));
  1283. }
  1284. }
  1285. network["rules"] = nrules;
  1286. }
  1287. }
  1288. if (b.count("authTokens")) {
  1289. json &authTokens = b["authTokens"];
  1290. if (authTokens.is_array()) {
  1291. json nat = json::array();
  1292. for(unsigned long i=0;i<authTokens.size();++i) {
  1293. json &token = authTokens[i];
  1294. if (token.is_object()) {
  1295. std::string tstr = token["token"];
  1296. if (tstr.length() > 0) {
  1297. json t = json::object();
  1298. t["token"] = tstr;
  1299. t["expires"] = _jI(token["expires"],0ULL);
  1300. t["maxUsesPerMember"] = _jI(token["maxUsesPerMember"],0ULL);
  1301. nat.push_back(t);
  1302. }
  1303. }
  1304. }
  1305. network["authTokens"] = nat;
  1306. }
  1307. }
  1308. if (b.count("capabilities")) {
  1309. json &capabilities = b["capabilities"];
  1310. if (capabilities.is_array()) {
  1311. std::map< uint64_t,json > ncaps;
  1312. for(unsigned long i=0;i<capabilities.size();++i) {
  1313. json &cap = capabilities[i];
  1314. if (cap.is_object()) {
  1315. json ncap = json::object();
  1316. const uint64_t capId = _jI(cap["id"],0ULL);
  1317. ncap["id"] = capId;
  1318. json &rules = cap["rules"];
  1319. json nrules = json::array();
  1320. if (rules.is_array()) {
  1321. for(unsigned long i=0;i<rules.size();++i) {
  1322. json rule = rules[i];
  1323. if (rule.is_object()) {
  1324. ZT_VirtualNetworkRule ztr;
  1325. if (_parseRule(rule,ztr))
  1326. nrules.push_back(_renderRule(ztr));
  1327. }
  1328. }
  1329. }
  1330. ncap["rules"] = nrules;
  1331. ncaps[capId] = ncap;
  1332. }
  1333. }
  1334. json ncapsa = json::array();
  1335. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1336. ncapsa.push_back(c->second);
  1337. network["capabilities"] = ncapsa;
  1338. }
  1339. }
  1340. } catch ( ... ) {
  1341. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  1342. responseContentType = "application/json";
  1343. return 400;
  1344. }
  1345. network["id"] = nwids;
  1346. network["nwid"] = nwids; // legacy
  1347. auto rev = network["revision"];
  1348. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1349. network["lastModified"] = now;
  1350. _writeJson(_networkJP(nwid,true),network);
  1351. _NetworkMemberInfo nmi;
  1352. _getNetworkMemberInfo(now,nwid,nmi);
  1353. _addNetworkNonPersistedFields(network,now,nmi);
  1354. responseBody = network.dump(2);
  1355. responseContentType = "application/json";
  1356. return 200;
  1357. } // else 404
  1358. } // else 404
  1359. } // else 404
  1360. return 404;
  1361. }
  1362. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1363. const std::vector<std::string> &path,
  1364. const std::map<std::string,std::string> &urlArgs,
  1365. const std::map<std::string,std::string> &headers,
  1366. const std::string &body,
  1367. std::string &responseBody,
  1368. std::string &responseContentType)
  1369. {
  1370. if (path.empty())
  1371. return 404;
  1372. if (path[0] == "network") {
  1373. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1374. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1375. json network(_readJson(_networkJP(nwid,false)));
  1376. if (!network.size())
  1377. return 404;
  1378. if (path.size() >= 3) {
  1379. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1380. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1381. json member(_readJson(_memberJP(nwid,Address(address),false)));
  1382. if (!member.size())
  1383. return 404;
  1384. OSUtils::rmDashRf(_memberBP(nwid,Address(address),false).c_str());
  1385. responseBody = member.dump(2);
  1386. responseContentType = "application/json";
  1387. return 200;
  1388. }
  1389. } else {
  1390. OSUtils::rmDashRf(_networkBP(nwid,false).c_str());
  1391. {
  1392. Mutex::Lock _l(_networkMemberCache_m);
  1393. _networkMemberCache.erase(nwid);
  1394. }
  1395. responseBody = network.dump(2);
  1396. responseContentType = "application/json";
  1397. return 200;
  1398. }
  1399. } // else 404
  1400. } // else 404
  1401. return 404;
  1402. }
  1403. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1404. {
  1405. char tmp[65535];
  1406. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1407. if (!test)
  1408. return;
  1409. if (!report)
  1410. return;
  1411. Mutex::Lock _l(self->_circuitTests_m);
  1412. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1413. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1414. self->_node->circuitTestEnd(test);
  1415. ::free((void *)test);
  1416. return;
  1417. }
  1418. Utils::snprintf(tmp,sizeof(tmp),
  1419. "%s{\n"
  1420. "\t\"timestamp\": %llu," ZT_EOL_S
  1421. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1422. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1423. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1424. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1425. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1426. "\t\"flags\": %llu," ZT_EOL_S
  1427. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1428. "\t\"errorCode\": %u," ZT_EOL_S
  1429. "\t\"vendor\": %d," ZT_EOL_S
  1430. "\t\"protocolVersion\": %u," ZT_EOL_S
  1431. "\t\"majorVersion\": %u," ZT_EOL_S
  1432. "\t\"minorVersion\": %u," ZT_EOL_S
  1433. "\t\"revision\": %u," ZT_EOL_S
  1434. "\t\"platform\": %d," ZT_EOL_S
  1435. "\t\"architecture\": %d," ZT_EOL_S
  1436. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1437. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1438. "}",
  1439. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1440. (unsigned long long)report->timestamp,
  1441. (unsigned long long)test->testId,
  1442. (unsigned long long)report->upstream,
  1443. (unsigned long long)report->current,
  1444. (unsigned long long)OSUtils::now(),
  1445. (unsigned long long)report->sourcePacketId,
  1446. (unsigned long long)report->flags,
  1447. report->sourcePacketHopCount,
  1448. report->errorCode,
  1449. (int)report->vendor,
  1450. report->protocolVersion,
  1451. report->majorVersion,
  1452. report->minorVersion,
  1453. report->revision,
  1454. (int)report->platform,
  1455. (int)report->architecture,
  1456. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1457. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1458. cte->second.jsonResults.append(tmp);
  1459. }
  1460. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1461. {
  1462. Mutex::Lock _mcl(_networkMemberCache_m);
  1463. std::map< Address,nlohmann::json > &memberCacheEntry = _networkMemberCache[nwid];
  1464. nmi.totalMemberCount = memberCacheEntry.size();
  1465. for(std::map< Address,nlohmann::json >::iterator nm(memberCacheEntry.begin());nm!=memberCacheEntry.end();++nm) {
  1466. if (_jB(nm->second["authorized"],false)) {
  1467. ++nmi.authorizedMemberCount;
  1468. if (nm->second.count("recentLog")) {
  1469. json &mlog = nm->second["recentLog"];
  1470. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1471. json &mlog1 = mlog[0];
  1472. if (mlog1.is_object()) {
  1473. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1474. ++nmi.activeMemberCount;
  1475. }
  1476. }
  1477. }
  1478. if (_jB(nm->second["activeBridge"],false)) {
  1479. nmi.activeBridges.insert(nm->first);
  1480. }
  1481. if (nm->second.count("ipAssignments")) {
  1482. json &mips = nm->second["ipAssignments"];
  1483. if (mips.is_array()) {
  1484. for(unsigned long i=0;i<mips.size();++i) {
  1485. InetAddress mip(_jS(mips[i],""));
  1486. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1487. nmi.allocatedIps.insert(mip);
  1488. }
  1489. }
  1490. }
  1491. } else {
  1492. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(nm->second["lastDeauthorizedTime"],0ULL));
  1493. }
  1494. }
  1495. }
  1496. } // namespace ZeroTier