2
0

EmbeddedNetworkController.cpp 57 KB

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