EmbeddedNetworkController.cpp 62 KB

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