EmbeddedNetworkController.cpp 63 KB

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