EmbeddedNetworkController.cpp 64 KB

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