2
0

EmbeddedNetworkController.cpp 59 KB

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