EmbeddedNetworkController.cpp 64 KB

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