EmbeddedNetworkController.cpp 64 KB

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