EmbeddedNetworkController.cpp 61 KB

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