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