EmbeddedNetworkController.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdint.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #include <type_traits>
  19. #ifndef _WIN32
  20. #include <sys/time.h>
  21. #endif
  22. #include <sys/types.h>
  23. #include <algorithm>
  24. #include <utility>
  25. #include <stdexcept>
  26. #include <map>
  27. #include <thread>
  28. #include <memory>
  29. #include <iomanip>
  30. #include <sstream>
  31. #include <cctype>
  32. #include "../include/ZeroTierOne.h"
  33. #include "../version.h"
  34. #include "EmbeddedNetworkController.hpp"
  35. #include "LFDB.hpp"
  36. #include "FileDB.hpp"
  37. #ifdef ZT_CONTROLLER_USE_LIBPQ
  38. #include "CV1.hpp"
  39. #include "CV2.hpp"
  40. #endif
  41. #include "../node/Node.hpp"
  42. #include "../node/CertificateOfMembership.hpp"
  43. #include "../node/NetworkConfig.hpp"
  44. #include "../node/Dictionary.hpp"
  45. #include "../node/MAC.hpp"
  46. using json = nlohmann::json;
  47. // API version reported via JSON control plane
  48. #define ZT_NETCONF_CONTROLLER_API_VERSION 4
  49. // Min duration between requests for an address/nwid combo to prevent floods
  50. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  51. // Global maximum size of arrays in JSON objects
  52. #define ZT_CONTROLLER_MAX_ARRAY_SIZE 16384
  53. namespace ZeroTier {
  54. namespace {
  55. static json _renderRule(ZT_VirtualNetworkRule &rule)
  56. {
  57. char tmp[128];
  58. json r = json::object();
  59. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  60. switch(rt) {
  61. case ZT_NETWORK_RULE_ACTION_DROP:
  62. r["type"] = "ACTION_DROP";
  63. break;
  64. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  65. r["type"] = "ACTION_ACCEPT";
  66. break;
  67. case ZT_NETWORK_RULE_ACTION_TEE:
  68. r["type"] = "ACTION_TEE";
  69. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  70. r["flags"] = (unsigned int)rule.v.fwd.flags;
  71. r["length"] = (unsigned int)rule.v.fwd.length;
  72. break;
  73. case ZT_NETWORK_RULE_ACTION_WATCH:
  74. r["type"] = "ACTION_WATCH";
  75. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  76. r["flags"] = (unsigned int)rule.v.fwd.flags;
  77. r["length"] = (unsigned int)rule.v.fwd.length;
  78. break;
  79. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  80. r["type"] = "ACTION_REDIRECT";
  81. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  82. r["flags"] = (unsigned int)rule.v.fwd.flags;
  83. break;
  84. case ZT_NETWORK_RULE_ACTION_BREAK:
  85. r["type"] = "ACTION_BREAK";
  86. break;
  87. default:
  88. break;
  89. }
  90. if (r.empty()) {
  91. switch(rt) {
  92. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  93. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  94. r["zt"] = Address(rule.v.zt).toString(tmp);
  95. break;
  96. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  97. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  98. r["zt"] = Address(rule.v.zt).toString(tmp);
  99. break;
  100. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  101. r["type"] = "MATCH_VLAN_ID";
  102. r["vlanId"] = (unsigned int)rule.v.vlanId;
  103. break;
  104. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  105. r["type"] = "MATCH_VLAN_PCP";
  106. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  107. break;
  108. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  109. r["type"] = "MATCH_VLAN_DEI";
  110. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  111. break;
  112. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  113. r["type"] = "MATCH_MAC_SOURCE";
  114. 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]);
  115. r["mac"] = tmp;
  116. break;
  117. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  118. r["type"] = "MATCH_MAC_DEST";
  119. 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]);
  120. r["mac"] = tmp;
  121. break;
  122. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  123. r["type"] = "MATCH_IPV4_SOURCE";
  124. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  125. break;
  126. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  127. r["type"] = "MATCH_IPV4_DEST";
  128. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  129. break;
  130. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  131. r["type"] = "MATCH_IPV6_SOURCE";
  132. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  133. break;
  134. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  135. r["type"] = "MATCH_IPV6_DEST";
  136. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  137. break;
  138. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  139. r["type"] = "MATCH_IP_TOS";
  140. r["mask"] = (unsigned int)rule.v.ipTos.mask;
  141. r["start"] = (unsigned int)rule.v.ipTos.value[0];
  142. r["end"] = (unsigned int)rule.v.ipTos.value[1];
  143. break;
  144. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  145. r["type"] = "MATCH_IP_PROTOCOL";
  146. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  147. break;
  148. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  149. r["type"] = "MATCH_ETHERTYPE";
  150. r["etherType"] = (unsigned int)rule.v.etherType;
  151. break;
  152. case ZT_NETWORK_RULE_MATCH_ICMP:
  153. r["type"] = "MATCH_ICMP";
  154. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  155. if ((rule.v.icmp.flags & 0x01) != 0)
  156. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  157. else r["icmpCode"] = json();
  158. break;
  159. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  160. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  161. r["start"] = (unsigned int)rule.v.port[0];
  162. r["end"] = (unsigned int)rule.v.port[1];
  163. break;
  164. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  165. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  166. r["start"] = (unsigned int)rule.v.port[0];
  167. r["end"] = (unsigned int)rule.v.port[1];
  168. break;
  169. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  170. r["type"] = "MATCH_CHARACTERISTICS";
  171. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics);
  172. r["mask"] = tmp;
  173. break;
  174. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  175. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  176. r["start"] = (unsigned int)rule.v.frameSize[0];
  177. r["end"] = (unsigned int)rule.v.frameSize[1];
  178. break;
  179. case ZT_NETWORK_RULE_MATCH_RANDOM:
  180. r["type"] = "MATCH_RANDOM";
  181. r["probability"] = (unsigned long)rule.v.randomProbability;
  182. break;
  183. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  184. r["type"] = "MATCH_TAGS_DIFFERENCE";
  185. r["id"] = rule.v.tag.id;
  186. r["value"] = rule.v.tag.value;
  187. break;
  188. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  189. r["type"] = "MATCH_TAGS_BITWISE_AND";
  190. r["id"] = rule.v.tag.id;
  191. r["value"] = rule.v.tag.value;
  192. break;
  193. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  194. r["type"] = "MATCH_TAGS_BITWISE_OR";
  195. r["id"] = rule.v.tag.id;
  196. r["value"] = rule.v.tag.value;
  197. break;
  198. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  199. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  200. r["id"] = rule.v.tag.id;
  201. r["value"] = rule.v.tag.value;
  202. break;
  203. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  204. r["type"] = "MATCH_TAGS_EQUAL";
  205. r["id"] = rule.v.tag.id;
  206. r["value"] = rule.v.tag.value;
  207. break;
  208. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  209. r["type"] = "MATCH_TAG_SENDER";
  210. r["id"] = rule.v.tag.id;
  211. r["value"] = rule.v.tag.value;
  212. break;
  213. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER:
  214. r["type"] = "MATCH_TAG_RECEIVER";
  215. r["id"] = rule.v.tag.id;
  216. r["value"] = rule.v.tag.value;
  217. break;
  218. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE:
  219. r["type"] = "INTEGER_RANGE";
  220. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start);
  221. r["start"] = tmp;
  222. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start + (uint64_t)rule.v.intRange.end);
  223. r["end"] = tmp;
  224. r["idx"] = rule.v.intRange.idx;
  225. r["little"] = ((rule.v.intRange.format & 0x80) != 0);
  226. r["bits"] = (rule.v.intRange.format & 63) + 1;
  227. break;
  228. default:
  229. break;
  230. }
  231. if (!r.empty()) {
  232. r["not"] = ((rule.t & 0x80) != 0);
  233. r["or"] = ((rule.t & 0x40) != 0);
  234. }
  235. }
  236. return r;
  237. }
  238. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  239. {
  240. if (!r.is_object())
  241. return false;
  242. const std::string t(OSUtils::jsonString(r["type"],""));
  243. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  244. if (OSUtils::jsonBool(r["not"],false))
  245. rule.t = 0x80;
  246. else rule.t = 0x00;
  247. if (OSUtils::jsonBool(r["or"],false))
  248. rule.t |= 0x40;
  249. bool tag = false;
  250. if (t == "ACTION_DROP") {
  251. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  252. return true;
  253. } else if (t == "ACTION_ACCEPT") {
  254. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  255. return true;
  256. } else if (t == "ACTION_TEE") {
  257. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  258. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  259. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  260. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  261. return true;
  262. } else if (t == "ACTION_WATCH") {
  263. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  264. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  265. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  266. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  267. return true;
  268. } else if (t == "ACTION_REDIRECT") {
  269. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  270. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  271. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  272. return true;
  273. } else if (t == "ACTION_BREAK") {
  274. rule.t |= ZT_NETWORK_RULE_ACTION_BREAK;
  275. return true;
  276. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  277. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  278. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  279. return true;
  280. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  281. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  282. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  283. return true;
  284. } else if (t == "MATCH_VLAN_ID") {
  285. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  286. rule.v.vlanId = (uint16_t)(OSUtils::jsonInt(r["vlanId"],0ULL) & 0xffffULL);
  287. return true;
  288. } else if (t == "MATCH_VLAN_PCP") {
  289. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  290. rule.v.vlanPcp = (uint8_t)(OSUtils::jsonInt(r["vlanPcp"],0ULL) & 0xffULL);
  291. return true;
  292. } else if (t == "MATCH_VLAN_DEI") {
  293. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  294. rule.v.vlanDei = (uint8_t)(OSUtils::jsonInt(r["vlanDei"],0ULL) & 0xffULL);
  295. return true;
  296. } else if (t == "MATCH_MAC_SOURCE") {
  297. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  298. std::string mac(OSUtils::jsonString(r["mac"],"0"));
  299. Utils::cleanMac(mac);
  300. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  301. return true;
  302. } else if (t == "MATCH_MAC_DEST") {
  303. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  304. std::string mac(OSUtils::jsonString(r["mac"],"0"));
  305. Utils::cleanMac(mac);
  306. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  307. return true;
  308. } else if (t == "MATCH_IPV4_SOURCE") {
  309. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  310. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  311. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  312. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  313. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  314. return true;
  315. } else if (t == "MATCH_IPV4_DEST") {
  316. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  317. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  318. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  319. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  320. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  321. return true;
  322. } else if (t == "MATCH_IPV6_SOURCE") {
  323. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  324. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  325. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  326. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  327. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  328. return true;
  329. } else if (t == "MATCH_IPV6_DEST") {
  330. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  331. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  332. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  333. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  334. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  335. return true;
  336. } else if (t == "MATCH_IP_TOS") {
  337. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  338. rule.v.ipTos.mask = (uint8_t)(OSUtils::jsonInt(r["mask"],0ULL) & 0xffULL);
  339. rule.v.ipTos.value[0] = (uint8_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffULL);
  340. rule.v.ipTos.value[1] = (uint8_t)(OSUtils::jsonInt(r["end"],0ULL) & 0xffULL);
  341. return true;
  342. } else if (t == "MATCH_IP_PROTOCOL") {
  343. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  344. rule.v.ipProtocol = (uint8_t)(OSUtils::jsonInt(r["ipProtocol"],0ULL) & 0xffULL);
  345. return true;
  346. } else if (t == "MATCH_ETHERTYPE") {
  347. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  348. rule.v.etherType = (uint16_t)(OSUtils::jsonInt(r["etherType"],0ULL) & 0xffffULL);
  349. return true;
  350. } else if (t == "MATCH_ICMP") {
  351. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  352. rule.v.icmp.type = (uint8_t)(OSUtils::jsonInt(r["icmpType"],0ULL) & 0xffULL);
  353. json &code = r["icmpCode"];
  354. if (code.is_null()) {
  355. rule.v.icmp.code = 0;
  356. rule.v.icmp.flags = 0x00;
  357. } else {
  358. rule.v.icmp.code = (uint8_t)(OSUtils::jsonInt(code,0ULL) & 0xffULL);
  359. rule.v.icmp.flags = 0x01;
  360. }
  361. return true;
  362. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  363. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  364. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  365. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  366. return true;
  367. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  368. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  369. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  370. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  371. return true;
  372. } else if (t == "MATCH_CHARACTERISTICS") {
  373. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  374. if (r.count("mask")) {
  375. json &v = r["mask"];
  376. if (v.is_number()) {
  377. rule.v.characteristics = v;
  378. } else {
  379. std::string tmp = v;
  380. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  381. }
  382. }
  383. return true;
  384. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  385. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  386. rule.v.frameSize[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  387. rule.v.frameSize[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  388. return true;
  389. } else if (t == "MATCH_RANDOM") {
  390. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  391. rule.v.randomProbability = (uint32_t)(OSUtils::jsonInt(r["probability"],0ULL) & 0xffffffffULL);
  392. return true;
  393. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  394. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  395. tag = true;
  396. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  397. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  398. tag = true;
  399. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  400. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  401. tag = true;
  402. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  403. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  404. tag = true;
  405. } else if (t == "MATCH_TAGS_EQUAL") {
  406. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  407. tag = true;
  408. } else if (t == "MATCH_TAG_SENDER") {
  409. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_SENDER;
  410. tag = true;
  411. } else if (t == "MATCH_TAG_RECEIVER") {
  412. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_RECEIVER;
  413. tag = true;
  414. } else if (t == "INTEGER_RANGE") {
  415. json &s = r["start"];
  416. if (s.is_string()) {
  417. std::string tmp = s;
  418. rule.v.intRange.start = Utils::hexStrToU64(tmp.c_str());
  419. } else {
  420. rule.v.intRange.start = OSUtils::jsonInt(s,0ULL);
  421. }
  422. json &e = r["end"];
  423. if (e.is_string()) {
  424. std::string tmp = e;
  425. rule.v.intRange.end = (uint32_t)(Utils::hexStrToU64(tmp.c_str()) - rule.v.intRange.start);
  426. } else {
  427. rule.v.intRange.end = (uint32_t)(OSUtils::jsonInt(e,0ULL) - rule.v.intRange.start);
  428. }
  429. rule.v.intRange.idx = (uint16_t)OSUtils::jsonInt(r["idx"],0ULL);
  430. rule.v.intRange.format = (OSUtils::jsonBool(r["little"],false)) ? 0x80 : 0x00;
  431. rule.v.intRange.format |= (uint8_t)((OSUtils::jsonInt(r["bits"],1ULL) - 1) & 63);
  432. }
  433. if (tag) {
  434. rule.v.tag.id = (uint32_t)(OSUtils::jsonInt(r["id"],0ULL) & 0xffffffffULL);
  435. rule.v.tag.value = (uint32_t)(OSUtils::jsonInt(r["value"],0ULL) & 0xffffffffULL);
  436. return true;
  437. }
  438. return false;
  439. }
  440. } // anonymous namespace
  441. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *ztPath,const char *dbPath, int listenPort, RedisConfig *rc)
  442. : _startTime(OSUtils::now())
  443. , _listenPort(listenPort)
  444. , _node(node)
  445. , _ztPath(ztPath)
  446. , _path(dbPath)
  447. , _signingId()
  448. , _signingIdAddressString()
  449. , _sender((NetworkController::Sender *)0)
  450. , _db(this)
  451. , _queue()
  452. , _threads()
  453. , _threads_l()
  454. , _memberStatus()
  455. , _memberStatus_l()
  456. , _expiringSoon()
  457. , _expiringSoon_l()
  458. , _rc(rc)
  459. , _ssoExpiryRunning(true)
  460. , _ssoExpiry(std::thread(&EmbeddedNetworkController::_ssoExpiryThread, this))
  461. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  462. , _member_status_lookup{"nc_member_status_lookup",""}
  463. , _member_status_lookup_count{"nc_member_status_lookup_count",""}
  464. , _node_is_online{"nc_node_is_online",""}
  465. , _node_is_online_count{"nc_node_is_online_count",""}
  466. , _get_and_init_member{"nc_get_and_init_member",""}
  467. , _get_and_init_member_count{"nc_get_and_init_member_count",""}
  468. , _have_identity{"nc_have_identity",""}
  469. , _have_identity_count{"nc_have_identity_count",""}
  470. , _determine_auth{"nc_determine_auth",""}
  471. , _determine_auth_count{"nc_determine_auth_count",""}
  472. , _sso_check{"nc_sso_check",""}
  473. , _sso_check_count{"nc_sso_check_count",""}
  474. , _auth_check{"nc_auth_check",""}
  475. , _auth_check_count{"nc_auth_check_count",""}
  476. , _json_schlep{"nc_json_schlep",""}
  477. , _json_schlep_count{"nc_json_schlep_count",""}
  478. , _issue_certificate{"nc_issue_certificate", ""}
  479. , _issue_certificate_count{"nc_issue_certificate_count",""}
  480. , _save_member{"nc_save_member",""}
  481. , _save_member_count{"nc_save_member_count",""}
  482. , _send_netconf{"nc_send_netconf2",""}
  483. , _send_netconf_count{"nc_send_netconf2_count",""}
  484. #endif
  485. {
  486. }
  487. EmbeddedNetworkController::~EmbeddedNetworkController()
  488. {
  489. std::lock_guard<std::mutex> l(_threads_l);
  490. _queue.stop();
  491. for(auto t=_threads.begin();t!=_threads.end();++t) {
  492. t->join();
  493. }
  494. _ssoExpiryRunning = false;
  495. _ssoExpiry.join();
  496. }
  497. void EmbeddedNetworkController::setSSORedirectURL(const std::string &url) {
  498. _ssoRedirectURL = url;
  499. }
  500. void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
  501. {
  502. char tmp[64];
  503. _signingId = signingId;
  504. _sender = sender;
  505. _signingIdAddressString = signingId.address().toString(tmp);
  506. #ifdef ZT_CONTROLLER_USE_LIBPQ
  507. if ((_path.length() > 9)&&(_path.substr(0,9) == "postgres:")) {
  508. fprintf(stderr, "CV1\n");
  509. _db.addDB(std::shared_ptr<DB>(new CV1(_signingId,_path.substr(9).c_str(), _listenPort, _rc)));
  510. } else if ((_path.length() > 4)&&(_path.substr(0,4) == "cv2:")) {
  511. fprintf(stderr, "CV2\n");
  512. _db.addDB(std::shared_ptr<DB>(new CV2(_signingId,_path.substr(4).c_str(),_listenPort)));
  513. } else {
  514. fprintf(stderr, "FileDB\n");
  515. #endif
  516. _db.addDB(std::shared_ptr<DB>(new FileDB(_path.c_str())));
  517. #ifdef ZT_CONTROLLER_USE_LIBPQ
  518. }
  519. #endif
  520. std::string lfJSON;
  521. OSUtils::readFile((_ztPath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lfJSON);
  522. if (lfJSON.length() > 0) {
  523. nlohmann::json lfConfig(OSUtils::jsonParse(lfJSON));
  524. nlohmann::json &settings = lfConfig["settings"];
  525. if (settings.is_object()) {
  526. nlohmann::json &controllerDb = settings["controllerDb"];
  527. if (controllerDb.is_object()) {
  528. std::string type = controllerDb["type"];
  529. if (type == "lf") {
  530. std::string lfOwner = controllerDb["owner"];
  531. std::string lfHost = controllerDb["host"];
  532. int lfPort = controllerDb["port"];
  533. bool storeOnlineState = controllerDb["storeOnlineState"];
  534. if ((lfOwner.length())&&(lfHost.length())&&(lfPort > 0)&&(lfPort < 65536)) {
  535. std::size_t pubHdrLoc = lfOwner.find("Public: ");
  536. if ((pubHdrLoc > 0)&&((pubHdrLoc + 8) < lfOwner.length())) {
  537. std::string lfOwnerPublic = lfOwner.substr(pubHdrLoc + 8);
  538. std::size_t pubHdrEnd = lfOwnerPublic.find_first_of("\n\r\t ");
  539. if (pubHdrEnd != std::string::npos) {
  540. lfOwnerPublic = lfOwnerPublic.substr(0,pubHdrEnd);
  541. _db.addDB(std::shared_ptr<DB>(new LFDB(_signingId,_path.c_str(),lfOwner.c_str(),lfOwnerPublic.c_str(),lfHost.c_str(),lfPort,storeOnlineState)));
  542. }
  543. }
  544. }
  545. }
  546. }
  547. }
  548. }
  549. _db.waitForReady();
  550. }
  551. void EmbeddedNetworkController::request(
  552. uint64_t nwid,
  553. const InetAddress &fromAddr,
  554. uint64_t requestPacketId,
  555. const Identity &identity,
  556. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  557. {
  558. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  559. return;
  560. _startThreads();
  561. const int64_t now = OSUtils::now();
  562. if (requestPacketId) {
  563. std::lock_guard<std::mutex> l(_memberStatus_l);
  564. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  565. if ((now - ms.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD) {
  566. return;
  567. }
  568. ms.lastRequestTime = now;
  569. }
  570. _RQEntry *qe = new _RQEntry;
  571. qe->nwid = nwid;
  572. qe->requestPacketId = requestPacketId;
  573. qe->fromAddr = fromAddr;
  574. qe->identity = identity;
  575. qe->metaData = metaData;
  576. qe->type = _RQEntry::RQENTRY_TYPE_REQUEST;
  577. _queue.post(qe);
  578. }
  579. std::string EmbeddedNetworkController::networkUpdateFromPostData(uint64_t networkID, const std::string &body)
  580. {
  581. json b = OSUtils::jsonParse(body);
  582. char nwids[24];
  583. OSUtils::ztsnprintf(nwids, sizeof(nwids), "%.16llx", networkID);
  584. json network;
  585. _db.get(networkID, network);
  586. DB::initNetwork(network);
  587. if (b.count("name")) network["name"] = OSUtils::jsonString(b["name"],"");
  588. if (b.count("private")) network["private"] = OSUtils::jsonBool(b["private"],true);
  589. if (b.count("enableBroadcast")) network["enableBroadcast"] = OSUtils::jsonBool(b["enableBroadcast"],false);
  590. if (b.count("multicastLimit")) network["multicastLimit"] = OSUtils::jsonInt(b["multicastLimit"],32ULL);
  591. 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);
  592. if (b.count("remoteTraceTarget")) {
  593. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  594. if (rtt.length() == 10) {
  595. network["remoteTraceTarget"] = rtt;
  596. } else {
  597. network["remoteTraceTarget"] = json();
  598. }
  599. }
  600. if (b.count("remoteTraceLevel")) network["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  601. if (b.count("v4AssignMode")) {
  602. json nv4m;
  603. json &v4m = b["v4AssignMode"];
  604. if (v4m.is_string()) { // backward compatibility
  605. nv4m["zt"] = (OSUtils::jsonString(v4m,"") == "zt");
  606. } else if (v4m.is_object()) {
  607. nv4m["zt"] = OSUtils::jsonBool(v4m["zt"],false);
  608. } else nv4m["zt"] = false;
  609. network["v4AssignMode"] = nv4m;
  610. }
  611. if (b.count("v6AssignMode")) {
  612. json nv6m;
  613. json &v6m = b["v6AssignMode"];
  614. if (!nv6m.is_object()) nv6m = json::object();
  615. if (v6m.is_string()) { // backward compatibility
  616. std::vector<std::string> v6ms(OSUtils::split(OSUtils::jsonString(v6m,"").c_str(),",","",""));
  617. std::sort(v6ms.begin(),v6ms.end());
  618. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  619. nv6m["rfc4193"] = false;
  620. nv6m["zt"] = false;
  621. nv6m["6plane"] = false;
  622. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  623. if (*i == "rfc4193")
  624. nv6m["rfc4193"] = true;
  625. else if (*i == "zt")
  626. nv6m["zt"] = true;
  627. else if (*i == "6plane")
  628. nv6m["6plane"] = true;
  629. }
  630. } else if (v6m.is_object()) {
  631. if (v6m.count("rfc4193")) nv6m["rfc4193"] = OSUtils::jsonBool(v6m["rfc4193"],false);
  632. if (v6m.count("zt")) nv6m["zt"] = OSUtils::jsonBool(v6m["zt"],false);
  633. if (v6m.count("6plane")) nv6m["6plane"] = OSUtils::jsonBool(v6m["6plane"],false);
  634. } else {
  635. nv6m["rfc4193"] = false;
  636. nv6m["zt"] = false;
  637. nv6m["6plane"] = false;
  638. }
  639. network["v6AssignMode"] = nv6m;
  640. }
  641. if (b.count("routes")) {
  642. json &rts = b["routes"];
  643. if (rts.is_array()) {
  644. json nrts = json::array();
  645. for(unsigned long i=0;i<rts.size();++i) {
  646. json &rt = rts[i];
  647. if (rt.is_object()) {
  648. json &target = rt["target"];
  649. json &via = rt["via"];
  650. if (target.is_string()) {
  651. InetAddress t(target.get<std::string>().c_str());
  652. InetAddress v;
  653. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  654. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  655. json tmp;
  656. char tmp2[64];
  657. tmp["target"] = t.toString(tmp2);
  658. if (v.ss_family == t.ss_family)
  659. tmp["via"] = v.toIpString(tmp2);
  660. else tmp["via"] = json();
  661. nrts.push_back(tmp);
  662. if (nrts.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  663. break;
  664. }
  665. }
  666. }
  667. }
  668. network["routes"] = nrts;
  669. }
  670. }
  671. if (b.count("ipAssignmentPools")) {
  672. json &ipp = b["ipAssignmentPools"];
  673. if (ipp.is_array()) {
  674. json nipp = json::array();
  675. for(unsigned long i=0;i<ipp.size();++i) {
  676. json &ip = ipp[i];
  677. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  678. InetAddress f(OSUtils::jsonString(ip["ipRangeStart"],"").c_str());
  679. InetAddress t(OSUtils::jsonString(ip["ipRangeEnd"],"").c_str());
  680. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  681. json tmp = json::object();
  682. char tmp2[64];
  683. tmp["ipRangeStart"] = f.toIpString(tmp2);
  684. tmp["ipRangeEnd"] = t.toIpString(tmp2);
  685. nipp.push_back(tmp);
  686. if (nipp.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  687. break;
  688. }
  689. }
  690. }
  691. network["ipAssignmentPools"] = nipp;
  692. }
  693. }
  694. if (b.count("rules")) {
  695. json &rules = b["rules"];
  696. if (rules.is_array()) {
  697. json nrules = json::array();
  698. for(unsigned long i=0;i<rules.size();++i) {
  699. json &rule = rules[i];
  700. if (rule.is_object()) {
  701. ZT_VirtualNetworkRule ztr;
  702. if (_parseRule(rule,ztr)) {
  703. nrules.push_back(_renderRule(ztr));
  704. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  705. break;
  706. }
  707. }
  708. }
  709. network["rules"] = nrules;
  710. }
  711. }
  712. if (b.count("authTokens")) {
  713. json &authTokens = b["authTokens"];
  714. if (authTokens.is_object()) {
  715. json nat;
  716. for(json::iterator t(authTokens.begin());t!=authTokens.end();++t) {
  717. if ((t.value().is_number())&&(t.value() >= 0))
  718. nat[t.key()] = t.value();
  719. }
  720. network["authTokens"] = nat;
  721. } else {
  722. network["authTokens"] = {{}};
  723. }
  724. }
  725. if (b.count("capabilities")) {
  726. json &capabilities = b["capabilities"];
  727. if (capabilities.is_array()) {
  728. std::map< uint64_t,json > ncaps;
  729. for(unsigned long i=0;i<capabilities.size();++i) {
  730. json &cap = capabilities[i];
  731. if (cap.is_object()) {
  732. json ncap = json::object();
  733. const uint64_t capId = OSUtils::jsonInt(cap["id"],0ULL);
  734. ncap["id"] = capId;
  735. ncap["default"] = OSUtils::jsonBool(cap["default"],false);
  736. json &rules = cap["rules"];
  737. json nrules = json::array();
  738. if (rules.is_array()) {
  739. for(unsigned long i=0;i<rules.size();++i) {
  740. json &rule = rules[i];
  741. if (rule.is_object()) {
  742. ZT_VirtualNetworkRule ztr;
  743. if (_parseRule(rule,ztr)) {
  744. nrules.push_back(_renderRule(ztr));
  745. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  746. break;
  747. }
  748. }
  749. }
  750. }
  751. ncap["rules"] = nrules;
  752. ncaps[capId] = ncap;
  753. }
  754. }
  755. json ncapsa = json::array();
  756. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c) {
  757. ncapsa.push_back(c->second);
  758. if (ncapsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  759. break;
  760. }
  761. network["capabilities"] = ncapsa;
  762. }
  763. }
  764. if (b.count("tags")) {
  765. json &tags = b["tags"];
  766. if (tags.is_array()) {
  767. std::map< uint64_t,json > ntags;
  768. for(unsigned long i=0;i<tags.size();++i) {
  769. json &tag = tags[i];
  770. if (tag.is_object()) {
  771. json ntag = json::object();
  772. const uint64_t tagId = OSUtils::jsonInt(tag["id"],0ULL);
  773. ntag["id"] = tagId;
  774. json &dfl = tag["default"];
  775. if (dfl.is_null())
  776. ntag["default"] = dfl;
  777. else ntag["default"] = OSUtils::jsonInt(dfl,0ULL);
  778. ntags[tagId] = ntag;
  779. }
  780. }
  781. json ntagsa = json::array();
  782. for(std::map< uint64_t,json >::iterator t(ntags.begin());t!=ntags.end();++t) {
  783. ntagsa.push_back(t->second);
  784. if (ntagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  785. break;
  786. }
  787. network["tags"] = ntagsa;
  788. }
  789. }
  790. if (b.count("dns")) {
  791. json &dns = b["dns"];
  792. if (dns.is_object()) {
  793. json nd;
  794. nd["domain"] = dns["domain"];
  795. json &srv = dns["servers"];
  796. if (srv.is_array()) {
  797. json ns = json::array();
  798. for(unsigned int i=0;i<srv.size();++i) {
  799. ns.push_back(srv[i]);
  800. }
  801. nd["servers"] = ns;
  802. }
  803. network["dns"] = nd;
  804. }
  805. }
  806. network["id"] = nwids;
  807. network["nwid"] = nwids;
  808. DB::cleanNetwork(network);
  809. _db.save(network, true);
  810. return network.dump();
  811. }
  812. void EmbeddedNetworkController::configureHTTPControlPlane(
  813. httplib::Server &s,
  814. httplib::Server &sv6,
  815. const std::function<void(const httplib::Request&, httplib::Response&, std::string)> setContent)
  816. {
  817. // Control plane Endpoints
  818. std::string controllerPath = "/controller";
  819. std::string networkListPath = "/controller/network";
  820. std::string networkListPath2 = "/unstable/controller/network";
  821. std::string networkPath = "/controller/network/([0-9a-fA-F]{16})";
  822. std::string oldAndBustedNetworkCreatePath = "/controller/network/([0-9a-fA-F]{10})______";
  823. std::string memberListPath = "/controller/network/([0-9a-fA-F]{16})/member";
  824. std::string memberListPath2 = "/unstable/controller/network/([0-9a-fA-F]{16})/member";
  825. std::string memberPath = "/controller/network/([0-9a-fA-F]{16})/member/([0-9a-fA-F]{10})";
  826. auto controllerGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  827. char tmp[4096];
  828. const bool dbOk = _db.isReady();
  829. OSUtils::ztsnprintf(
  830. tmp,
  831. sizeof(tmp),
  832. "{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",
  833. ZT_NETCONF_CONTROLLER_API_VERSION,
  834. (unsigned long long)OSUtils::now(),
  835. dbOk ? "true" : "false");
  836. if (!dbOk) {
  837. res.status = 503;
  838. }
  839. setContent(req, res, tmp);
  840. };
  841. s.Get(controllerPath, controllerGet);
  842. sv6.Get(controllerPath, controllerGet);
  843. auto networkListGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  844. std::set<uint64_t> networkIds;
  845. _db.networks(networkIds);
  846. char tmp[64];
  847. auto out = json::array();
  848. for(std::set<uint64_t>::const_iterator i(networkIds.begin()); i != networkIds.end(); ++i) {
  849. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%.16llx", *i);
  850. out.push_back(tmp);
  851. }
  852. setContent(req, res, out.dump());
  853. };
  854. s.Get(networkListPath, networkListGet);
  855. sv6.Get(networkListPath, networkListGet);
  856. auto networkListGet2 = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  857. std::set<uint64_t> networkIds;
  858. _db.networks(networkIds);
  859. auto meta = json::object();
  860. auto data = json::array();
  861. uint64_t networkCount = 0;
  862. for(std::set<uint64_t>::const_iterator nwid(networkIds.begin()); nwid != networkIds.end(); ++nwid) {
  863. json network;
  864. if (!_db.get(*nwid, network)) {
  865. continue;
  866. }
  867. std::vector<json> memTmp;
  868. if (_db.get(*nwid, network, memTmp)) {
  869. if (!network.is_null()) {
  870. uint64_t authorizedCount = 0;
  871. uint64_t totalCount = memTmp.size();
  872. networkCount++;
  873. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  874. bool a = OSUtils::jsonBool((*m)["authorized"], 0);
  875. if (a) { authorizedCount++; }
  876. }
  877. auto nwMeta = json::object();
  878. nwMeta["totalMemberCount"] = totalCount;
  879. nwMeta["authorizedMemberCount"] = authorizedCount;
  880. network["meta"] = nwMeta;
  881. data.push_back(network);
  882. }
  883. }
  884. }
  885. meta["networkCount"] = networkCount;
  886. auto out = json::object();
  887. out["data"] = data;
  888. out["meta"] = meta;
  889. setContent(req, res, out.dump());
  890. };
  891. s.Get(networkListPath2, networkListGet2);
  892. sv6.Get(networkListPath2, networkListGet2);
  893. auto networkGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  894. auto networkID = req.matches[1];
  895. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  896. json network;
  897. if (!_db.get(nwid, network)) {
  898. res.status = 404;
  899. return;
  900. }
  901. setContent(req, res, network.dump());
  902. };
  903. s.Get(networkPath, networkGet);
  904. sv6.Get(networkPath, networkGet);
  905. auto createNewNetwork = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  906. // fprintf(stderr, "creating new network (new style)\n");
  907. uint64_t nwid = 0;
  908. uint64_t nwidPrefix = (Utils::hexStrToU64(_signingIdAddressString.c_str()) << 24) & 0xffffffffff000000ULL;
  909. uint64_t nwidPostfix = 0;
  910. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  911. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  912. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  913. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  914. if (!_db.hasNetwork(tryNwid)) {
  915. nwid = tryNwid;
  916. break;
  917. }
  918. }
  919. if (!nwid) {
  920. res.status = 503;
  921. return;
  922. }
  923. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  924. };
  925. s.Put(networkListPath, createNewNetwork);
  926. s.Post(networkListPath, createNewNetwork);
  927. sv6.Put(networkListPath, createNewNetwork);
  928. sv6.Post(networkListPath, createNewNetwork);
  929. auto createNewNetworkOldAndBusted = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  930. auto inID = req.matches[1].str();
  931. if (inID != _signingIdAddressString) {
  932. res.status = 400;
  933. return;
  934. }
  935. uint64_t nwid = 0;
  936. uint64_t nwidPrefix = (Utils::hexStrToU64(inID.c_str()) << 24) & 0xffffffffff000000ULL;
  937. uint64_t nwidPostfix = 0;
  938. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  939. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  940. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  941. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  942. if (!_db.hasNetwork(tryNwid)) {
  943. nwid = tryNwid;
  944. break;
  945. }
  946. }
  947. if (!nwid) {
  948. res.status = 503;
  949. return;
  950. }
  951. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  952. };
  953. s.Put(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  954. s.Post(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  955. sv6.Put(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  956. sv6.Post(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  957. auto networkPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  958. auto networkID = req.matches[1].str();
  959. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  960. res.status = 200;
  961. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  962. };
  963. s.Put(networkPath, networkPost);
  964. s.Post(networkPath, networkPost);
  965. sv6.Put(networkPath, networkPost);
  966. sv6.Post(networkPath, networkPost);
  967. auto networkDelete = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  968. auto networkID = req.matches[1].str();
  969. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  970. json network;
  971. if (!_db.get(nwid,network)) {
  972. res.status = 404;
  973. return;
  974. }
  975. _db.eraseNetwork(nwid);
  976. setContent(req, res, network.dump());
  977. };
  978. s.Delete(networkPath, networkDelete);
  979. sv6.Delete(networkPath, networkDelete);
  980. auto memberListGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  981. auto networkID = req.matches[1];
  982. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  983. json network;
  984. if (!_db.get(nwid, network)) {
  985. res.status = 404;
  986. return;
  987. }
  988. json out = json::object();
  989. std::vector<json> memTmp;
  990. if (_db.get(nwid, network, memTmp)) {
  991. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  992. int revision = OSUtils::jsonInt((*m)["revision"], 0);
  993. std::string id = OSUtils::jsonString((*m)["id"], "");
  994. if (id.length() == 10) {
  995. out[id] = revision;
  996. }
  997. }
  998. }
  999. setContent(req, res, out.dump());
  1000. };
  1001. s.Get(memberListPath, memberListGet);
  1002. sv6.Get(memberListPath, memberListGet);
  1003. auto memberListGet2 = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1004. auto networkID = req.matches[1];
  1005. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  1006. json network;
  1007. if (!_db.get(nwid, network)) {
  1008. res.status = 404;
  1009. return;
  1010. }
  1011. auto out = nlohmann::json::object();
  1012. auto meta = nlohmann::json::object();
  1013. std::vector<json> memTmp;
  1014. if (_db.get(nwid, network, memTmp)) {
  1015. uint64_t authorizedCount = 0;
  1016. uint64_t totalCount = memTmp.size();
  1017. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  1018. bool a = OSUtils::jsonBool((*m)["authorized"], 0);
  1019. if (a) { authorizedCount++; }
  1020. }
  1021. meta["totalCount"] = totalCount;
  1022. meta["authorizedCount"] = authorizedCount;
  1023. out["data"] = memTmp;
  1024. out["meta"] = meta;
  1025. setContent(req, res, out.dump());
  1026. } else {
  1027. res.status = 404;
  1028. return;
  1029. }
  1030. };
  1031. s.Get(memberListPath2, memberListGet2);
  1032. sv6.Get(memberListPath2, memberListGet2);
  1033. auto memberGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1034. auto networkID = req.matches[1];
  1035. auto memberID = req.matches[2];
  1036. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  1037. uint64_t memid = Utils::hexStrToU64(memberID.str().c_str());
  1038. json network;
  1039. json member;
  1040. if (!_db.get(nwid, network, memid, member)) {
  1041. res.status = 404;
  1042. return;
  1043. }
  1044. setContent(req, res, member.dump());
  1045. };
  1046. s.Get(memberPath, memberGet);
  1047. sv6.Get(memberPath, memberGet);
  1048. auto memberPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1049. auto networkID = req.matches[1].str();
  1050. auto memberID = req.matches[2].str();
  1051. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1052. uint64_t memid = Utils::hexStrToU64(memberID.c_str());
  1053. if (!_db.hasNetwork(nwid)) {
  1054. res.status = 404;
  1055. return;
  1056. }
  1057. json network;
  1058. json member;
  1059. _db.get(nwid, network, memid, member);
  1060. DB::initMember(member);
  1061. json b = OSUtils::jsonParse(req.body);
  1062. if (b.count("activeBridge")) member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"], false);
  1063. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"], false);
  1064. if (b.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = (uint64_t)OSUtils::jsonInt(b["authenticationExpiryTime"], 0ULL);
  1065. if (b.count("authenticationURL")) member["authenticationURL"] = OSUtils::jsonString(b["authenticationURL"], "");
  1066. if (b.count("name")) member["name"] = OSUtils::jsonString(b["name"], "");
  1067. if (b.count("remoteTraceTarget")) {
  1068. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  1069. if (rtt.length() == 10) {
  1070. member["remoteTraceTarget"] = rtt;
  1071. } else {
  1072. member["remoteTraceTarget"] = json();
  1073. }
  1074. }
  1075. if (b.count("remoteTraceLevel")) member["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  1076. if (b.count("authorized")) {
  1077. const bool newAuth = OSUtils::jsonBool(b["authorized"],false);
  1078. if (newAuth != OSUtils::jsonBool(member["authorized"],false)) {
  1079. member["authorized"] = newAuth;
  1080. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = OSUtils::now();
  1081. if (newAuth) {
  1082. member["lastAuthorizedCredentialType"] = "api";
  1083. member["lastAuthorizedCredential"] = json();
  1084. }
  1085. }
  1086. }
  1087. if (b.count("ipAssignments")) {
  1088. json &ipa = b["ipAssignments"];
  1089. if (ipa.is_array()) {
  1090. json mipa(json::array());
  1091. for(unsigned long i=0;i<ipa.size();++i) {
  1092. std::string ips = ipa[i];
  1093. InetAddress ip(ips.c_str());
  1094. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1095. char tmpip[64];
  1096. mipa.push_back(ip.toIpString(tmpip));
  1097. if (mipa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1098. break;
  1099. }
  1100. }
  1101. member["ipAssignments"] = mipa;
  1102. }
  1103. }
  1104. if (b.count("tags")) {
  1105. json &tags = b["tags"];
  1106. if (tags.is_array()) {
  1107. std::map<uint64_t,uint64_t> mtags;
  1108. for(unsigned long i=0;i<tags.size();++i) {
  1109. json &tag = tags[i];
  1110. if ((tag.is_array())&&(tag.size() == 2))
  1111. mtags[OSUtils::jsonInt(tag[0],0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1],0ULL) & 0xffffffffULL;
  1112. }
  1113. json mtagsa = json::array();
  1114. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1115. json ta = json::array();
  1116. ta.push_back(t->first);
  1117. ta.push_back(t->second);
  1118. mtagsa.push_back(ta);
  1119. if (mtagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1120. break;
  1121. }
  1122. member["tags"] = mtagsa;
  1123. }
  1124. }
  1125. if (b.count("capabilities")) {
  1126. json &capabilities = b["capabilities"];
  1127. if (capabilities.is_array()) {
  1128. json mcaps = json::array();
  1129. for(unsigned long i=0;i<capabilities.size();++i) {
  1130. mcaps.push_back(OSUtils::jsonInt(capabilities[i],0ULL));
  1131. if (mcaps.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1132. break;
  1133. }
  1134. std::sort(mcaps.begin(),mcaps.end());
  1135. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1136. member["capabilities"] = mcaps;
  1137. }
  1138. }
  1139. member["id"] = memberID;
  1140. member["address"] = memberID;
  1141. member["nwid"] = networkID;
  1142. DB::cleanMember(member);
  1143. _db.save(member, true);
  1144. setContent(req, res, member.dump());
  1145. };
  1146. s.Put(memberPath, memberPost);
  1147. s.Post(memberPath, memberPost);
  1148. sv6.Put(memberPath, memberPost);
  1149. sv6.Post(memberPath, memberPost);
  1150. auto memberDelete = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1151. auto networkID = req.matches[1].str();
  1152. auto memberID = req.matches[2].str();
  1153. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1154. uint64_t address = Utils::hexStrToU64(memberID.c_str());
  1155. json network, member;
  1156. if (!_db.get(nwid, network, address, member)) {
  1157. res.status = 404;
  1158. return;
  1159. }
  1160. if (!member.size()) {
  1161. res.status = 404;
  1162. return;
  1163. }
  1164. _db.eraseMember(nwid, address);
  1165. setContent(req, res, member.dump());
  1166. };
  1167. s.Delete(memberPath, memberDelete);
  1168. sv6.Delete(memberPath, memberDelete);
  1169. }
  1170. void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace &rt)
  1171. {
  1172. static volatile unsigned long idCounter = 0;
  1173. char id[128],tmp[128];
  1174. std::string k,v;
  1175. try {
  1176. // Convert Dictionary into JSON object
  1177. json d;
  1178. char *saveptr = (char *)0;
  1179. for(char *l=Utils::stok(rt.data,"\n",&saveptr);(l);l=Utils::stok((char *)0,"\n",&saveptr)) {
  1180. char *eq = strchr(l,'=');
  1181. if (eq > l) {
  1182. k.assign(l,(unsigned long)(eq - l));
  1183. v.clear();
  1184. ++eq;
  1185. while (*eq) {
  1186. if (*eq == '\\') {
  1187. ++eq;
  1188. if (*eq) {
  1189. switch(*eq) {
  1190. case 'r': v.push_back('\r'); break;
  1191. case 'n': v.push_back('\n'); break;
  1192. case '0': v.push_back((char)0); break;
  1193. case 'e': v.push_back('='); break;
  1194. default: v.push_back(*eq); break;
  1195. }
  1196. ++eq;
  1197. }
  1198. } else {
  1199. v.push_back(*(eq++));
  1200. }
  1201. }
  1202. if ((k.length() > 0)&&(v.length() > 0))
  1203. d[k] = v;
  1204. }
  1205. }
  1206. const int64_t now = OSUtils::now();
  1207. OSUtils::ztsnprintf(id,sizeof(id),"%.10llx-%.16llx-%.10llx-%.4x",_signingId.address().toInt(),now,rt.origin,(unsigned int)(idCounter++ & 0xffff));
  1208. d["id"] = id;
  1209. d["objtype"] = "trace";
  1210. d["ts"] = now;
  1211. d["nodeId"] = Utils::hex10(rt.origin,tmp);
  1212. _db.save(d,true);
  1213. } catch ( ... ) {
  1214. // drop invalid trace messages if an error occurs
  1215. }
  1216. }
  1217. void EmbeddedNetworkController::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
  1218. {
  1219. // Send an update to all members of the network that are online
  1220. const int64_t now = OSUtils::now();
  1221. std::lock_guard<std::mutex> l(_memberStatus_l);
  1222. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1223. if ((i->first.networkId == networkId)&&(i->second.online(now))&&(i->second.lastRequestMetaData))
  1224. request(networkId,InetAddress(),0,i->second.identity,i->second.lastRequestMetaData);
  1225. }
  1226. }
  1227. void EmbeddedNetworkController::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
  1228. {
  1229. // Push update to member if online
  1230. try {
  1231. std::lock_guard<std::mutex> l(_memberStatus_l);
  1232. _MemberStatus &ms = _memberStatus[_MemberStatusKey(networkId,memberId)];
  1233. if ((ms.online(OSUtils::now()))&&(ms.lastRequestMetaData))
  1234. request(networkId,InetAddress(),0,ms.identity,ms.lastRequestMetaData);
  1235. } catch ( ... ) {}
  1236. }
  1237. void EmbeddedNetworkController::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
  1238. {
  1239. const int64_t now = OSUtils::now();
  1240. Revocation rev((uint32_t)_node->prng(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM);
  1241. rev.sign(_signingId);
  1242. {
  1243. std::lock_guard<std::mutex> l(_memberStatus_l);
  1244. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1245. if ((i->first.networkId == networkId)&&(i->second.online(now)))
  1246. _node->ncSendRevocation(Address(i->first.nodeId),rev);
  1247. }
  1248. }
  1249. }
  1250. void EmbeddedNetworkController::_request(
  1251. uint64_t nwid,
  1252. const InetAddress &fromAddr,
  1253. uint64_t requestPacketId,
  1254. const Identity &identity,
  1255. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  1256. {
  1257. Metrics::network_config_request++;
  1258. auto tid = std::this_thread::get_id();
  1259. std::stringstream ss; ss << tid;
  1260. std::string threadID = ss.str();
  1261. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1262. auto b1 = _member_status_lookup.Add({{"thread", threadID}});
  1263. auto c1 = _member_status_lookup_count.Add({{"thread", threadID}});
  1264. c1++;
  1265. b1.start();
  1266. #endif
  1267. char nwids[24];
  1268. DB::NetworkSummaryInfo ns;
  1269. json network,member;
  1270. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender)) {
  1271. return;
  1272. }
  1273. const int64_t now = OSUtils::now();
  1274. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1275. b1.stop();
  1276. auto b2 = _node_is_online.Add({{"thread",threadID}});
  1277. auto c2 = _node_is_online_count.Add({{"thread",threadID}});
  1278. c2++;
  1279. b2.start();
  1280. #endif
  1281. char osArch[256];
  1282. metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_OS_ARCH, osArch, sizeof(osArch));
  1283. _db.nodeIsOnline(nwid,identity.address().toInt(),fromAddr, osArch);
  1284. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1285. b2.stop();
  1286. auto b3 = _get_and_init_member.Add({{"thread", threadID}});
  1287. auto c3 = _get_and_init_member_count.Add({{"thread",threadID}});
  1288. c3++;
  1289. b3.start();
  1290. #endif
  1291. Utils::hex(nwid,nwids);
  1292. _db.get(nwid,network,identity.address().toInt(),member,ns);
  1293. if ((!network.is_object())||(network.empty())) {
  1294. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND, nullptr, 0);
  1295. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1296. b3.stop();
  1297. #endif
  1298. return;
  1299. }
  1300. const bool newMember = ((!member.is_object())||(member.empty()));
  1301. DB::initMember(member);
  1302. _MemberStatusKey msk(nwid,identity.address().toInt());
  1303. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1304. b3.stop();
  1305. #endif
  1306. {
  1307. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1308. auto b4 = _have_identity.Add({{"thread",threadID}});
  1309. auto c4 = _have_identity_count.Add({{"thread",threadID}});
  1310. c4++;
  1311. b4.start();
  1312. #endif
  1313. const std::string haveIdStr(OSUtils::jsonString(member["identity"],""));
  1314. if (haveIdStr.length() > 0) {
  1315. // If we already know this member's identity perform a full compare. This prevents
  1316. // a "collision" from being able to auth onto our network in place of an already
  1317. // known member.
  1318. try {
  1319. if (Identity(haveIdStr.c_str()) != identity) {
  1320. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1321. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1322. b4.stop();
  1323. #endif
  1324. return;
  1325. }
  1326. } catch ( ... ) {
  1327. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1328. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1329. b4.stop();
  1330. #endif
  1331. return;
  1332. }
  1333. } else {
  1334. // If we do not yet know this member's identity, learn it.
  1335. char idtmp[1024];
  1336. member["identity"] = identity.toString(false,idtmp);
  1337. }
  1338. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1339. b4.stop();
  1340. #endif
  1341. }
  1342. // These are always the same, but make sure they are set
  1343. {
  1344. char tmpid[128];
  1345. const std::string addrs(identity.address().toString(tmpid));
  1346. member["id"] = addrs;
  1347. member["address"] = addrs;
  1348. member["nwid"] = nwids;
  1349. }
  1350. // Determine whether and how member is authorized
  1351. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1352. auto b5 = _determine_auth.Add({{"thread",threadID}});
  1353. auto c5 = _determine_auth_count.Add({{"thread",threadID}});
  1354. c5++;
  1355. b5.start();
  1356. #endif
  1357. bool authorized = false;
  1358. bool autoAuthorized = false;
  1359. json autoAuthCredentialType,autoAuthCredential;
  1360. if (OSUtils::jsonBool(member["authorized"],false)) {
  1361. authorized = true;
  1362. } else if (!OSUtils::jsonBool(network["private"],true)) {
  1363. authorized = true;
  1364. autoAuthorized = true;
  1365. autoAuthCredentialType = "public";
  1366. } else {
  1367. char presentedAuth[512];
  1368. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  1369. presentedAuth[511] = (char)0; // sanity check
  1370. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  1371. const char *const presentedToken = presentedAuth + 6;
  1372. json authTokens(network["authTokens"]);
  1373. json &tokenExpires = authTokens[presentedToken];
  1374. if (tokenExpires.is_number()) {
  1375. if ((tokenExpires == 0)||(tokenExpires > now)) {
  1376. authorized = true;
  1377. autoAuthorized = true;
  1378. autoAuthCredentialType = "token";
  1379. autoAuthCredential = presentedToken;
  1380. }
  1381. }
  1382. }
  1383. }
  1384. }
  1385. // If we auto-authorized, update member record
  1386. if ((autoAuthorized)&&(authorized)) {
  1387. member["authorized"] = true;
  1388. member["lastAuthorizedTime"] = now;
  1389. member["lastAuthorizedCredentialType"] = autoAuthCredentialType;
  1390. member["lastAuthorizedCredential"] = autoAuthCredential;
  1391. }
  1392. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1393. b5.stop();
  1394. #endif
  1395. // Should we check SSO Stuff?
  1396. // If network is configured with SSO, and the member is not marked exempt: yes
  1397. // Otherwise no, we use standard auth logic.
  1398. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1399. auto b6 = _sso_check.Add({{"thread",threadID}});
  1400. auto c6 = _sso_check_count.Add({{"thread",threadID}});
  1401. c6++;
  1402. b6.start();
  1403. #endif
  1404. AuthInfo info;
  1405. int64_t authenticationExpiryTime = -1;
  1406. bool networkSSOEnabled = OSUtils::jsonBool(network["ssoEnabled"], false);
  1407. bool memberSSOExempt = OSUtils::jsonBool(member["ssoExempt"], false);
  1408. if (networkSSOEnabled && !memberSSOExempt) {
  1409. authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1410. info = _db.getSSOAuthInfo(member, _ssoRedirectURL);
  1411. assert(info.enabled == networkSSOEnabled);
  1412. if (authenticationExpiryTime <= now) {
  1413. if (info.version == 0) {
  1414. Dictionary<4096> authInfo;
  1415. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, (uint64_t)0ULL);
  1416. authInfo.add(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, info.authenticationURL.c_str());
  1417. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1418. } else if (info.version == 1) {
  1419. Dictionary<8192> authInfo;
  1420. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, info.version);
  1421. authInfo.add(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, info.issuerURL.c_str());
  1422. authInfo.add(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, info.centralAuthURL.c_str());
  1423. authInfo.add(ZT_AUTHINFO_DICT_KEY_NONCE, info.ssoNonce.c_str());
  1424. authInfo.add(ZT_AUTHINFO_DICT_KEY_STATE, info.ssoState.c_str());
  1425. authInfo.add(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, info.ssoClientID.c_str());
  1426. authInfo.add(ZT_AUTHINFO_DICT_KEY_SSO_PROVIDER, info.ssoProvider.c_str());
  1427. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1428. }
  1429. DB::cleanMember(member);
  1430. _db.save(member,true);
  1431. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1432. b6.stop();
  1433. #endif
  1434. return;
  1435. }
  1436. }
  1437. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1438. b6.stop();
  1439. auto b7 = _auth_check.Add({{"thread",threadID}});
  1440. auto c7 = _auth_check_count.Add({{"thread",threadID}});
  1441. c7++;
  1442. b7.start();
  1443. #endif
  1444. if (authorized) {
  1445. // Update version info and meta-data if authorized and if this is a genuine request
  1446. if (requestPacketId) {
  1447. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1448. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1449. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1450. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  1451. member["vMajor"] = vMajor;
  1452. member["vMinor"] = vMinor;
  1453. member["vRev"] = vRev;
  1454. member["vProto"] = vProto;
  1455. {
  1456. std::lock_guard<std::mutex> l(_memberStatus_l);
  1457. _MemberStatus &ms = _memberStatus[msk];
  1458. ms.authenticationExpiryTime = authenticationExpiryTime;
  1459. ms.vMajor = (int)vMajor;
  1460. ms.vMinor = (int)vMinor;
  1461. ms.vRev = (int)vRev;
  1462. ms.vProto = (int)vProto;
  1463. ms.lastRequestMetaData = metaData;
  1464. ms.identity = identity;
  1465. }
  1466. if (authenticationExpiryTime > 0) {
  1467. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1468. _expiringSoon.insert(std::pair<int64_t, _MemberStatusKey>(authenticationExpiryTime, msk));
  1469. }
  1470. }
  1471. } else {
  1472. // If they are not authorized, STOP!
  1473. DB::cleanMember(member);
  1474. _db.save(member,true);
  1475. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1476. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1477. b7.stop();
  1478. #endif
  1479. return;
  1480. }
  1481. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1482. b7.stop();
  1483. #endif
  1484. // -------------------------------------------------------------------------
  1485. // If we made it this far, they are authorized (and authenticated).
  1486. // -------------------------------------------------------------------------
  1487. // Default timeout: 15 minutes. Maximum: two hours. Can be specified by an optional field in the network config
  1488. // if something longer than 15 minutes is desired. Minimum is 5 minutes since shorter than that would be flaky.
  1489. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1490. auto b8 = _json_schlep.Add({{"thread",threadID}});
  1491. auto c8 = _json_schlep_count.Add({{"thread", threadID}});
  1492. c8++;
  1493. b8.start();
  1494. #endif
  1495. int64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_DFL_MAX_DELTA;
  1496. if (network.contains("certificateTimeoutWindowSize")) {
  1497. credentialtmd = (int64_t)network["certificateTimeoutWindowSize"];
  1498. }
  1499. credentialtmd = std::max(std::min(credentialtmd, ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA), ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA);
  1500. std::unique_ptr<NetworkConfig> nc(new NetworkConfig());
  1501. nc->networkId = nwid;
  1502. nc->type = OSUtils::jsonBool(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1503. nc->timestamp = now;
  1504. nc->credentialTimeMaxDelta = credentialtmd;
  1505. nc->revision = OSUtils::jsonInt(network["revision"],0ULL);
  1506. nc->issuedTo = identity.address();
  1507. if (OSUtils::jsonBool(network["enableBroadcast"],true)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1508. Utils::scopy(nc->name,sizeof(nc->name),OSUtils::jsonString(network["name"],"").c_str());
  1509. 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);
  1510. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"],32ULL);
  1511. nc->ssoEnabled = networkSSOEnabled; //OSUtils::jsonBool(network["ssoEnabled"], false);
  1512. nc->ssoVersion = info.version;
  1513. if (info.version == 0) {
  1514. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1515. if (!info.authenticationURL.empty()) {
  1516. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1517. }
  1518. }
  1519. else if (info.version == 1) {
  1520. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1521. if (!info.authenticationURL.empty()) {
  1522. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1523. }
  1524. if (!info.centralAuthURL.empty()) {
  1525. Utils::scopy(nc->centralAuthURL, sizeof(nc->centralAuthURL), info.centralAuthURL.c_str());
  1526. }
  1527. if (!info.issuerURL.empty()) {
  1528. #ifdef ZT_DEBUG
  1529. fprintf(stderr, "copying issuerURL to nc: %s\n", info.issuerURL.c_str());
  1530. #endif
  1531. Utils::scopy(nc->issuerURL, sizeof(nc->issuerURL), info.issuerURL.c_str());
  1532. }
  1533. if (!info.ssoNonce.empty()) {
  1534. Utils::scopy(nc->ssoNonce, sizeof(nc->ssoNonce), info.ssoNonce.c_str());
  1535. }
  1536. if (!info.ssoState.empty()) {
  1537. Utils::scopy(nc->ssoState, sizeof(nc->ssoState), info.ssoState.c_str());
  1538. }
  1539. if (!info.ssoClientID.empty()) {
  1540. Utils::scopy(nc->ssoClientID, sizeof(nc->ssoClientID), info.ssoClientID.c_str());
  1541. }
  1542. }
  1543. std::string rtt(OSUtils::jsonString(member["remoteTraceTarget"],""));
  1544. if (rtt.length() == 10) {
  1545. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1546. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(member["remoteTraceLevel"],0ULL);
  1547. } else {
  1548. rtt = OSUtils::jsonString(network["remoteTraceTarget"],"");
  1549. if (rtt.length() == 10) {
  1550. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1551. } else {
  1552. nc->remoteTraceTarget.zero();
  1553. }
  1554. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(network["remoteTraceLevel"],0ULL);
  1555. }
  1556. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab) {
  1557. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1558. }
  1559. json &v4AssignMode = network["v4AssignMode"];
  1560. json &v6AssignMode = network["v6AssignMode"];
  1561. json &ipAssignmentPools = network["ipAssignmentPools"];
  1562. json &routes = network["routes"];
  1563. json &rules = network["rules"];
  1564. json &capabilities = network["capabilities"];
  1565. json &tags = network["tags"];
  1566. json &memberCapabilities = member["capabilities"];
  1567. json &memberTags = member["tags"];
  1568. json &dns = network["dns"];
  1569. //fprintf(stderr, "IP Assignment Pools for Network %s: %s\n", nwids, OSUtils::jsonDump(ipAssignmentPools, 2).c_str());
  1570. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1571. // Old versions with no rules engine support get an allow everything rule.
  1572. // Since rules are enforced bidirectionally, newer versions *will* still
  1573. // enforce rules on the inbound side.
  1574. nc->ruleCount = 1;
  1575. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1576. } else {
  1577. if (rules.is_array()) {
  1578. for(unsigned long i=0;i<rules.size();++i) {
  1579. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1580. break;
  1581. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1582. ++nc->ruleCount;
  1583. }
  1584. }
  1585. std::map< uint64_t,json * > capsById;
  1586. if (!memberCapabilities.is_array())
  1587. memberCapabilities = json::array();
  1588. if (capabilities.is_array()) {
  1589. for(unsigned long i=0;i<capabilities.size();++i) {
  1590. json &cap = capabilities[i];
  1591. if (cap.is_object()) {
  1592. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1593. capsById[id] = &cap;
  1594. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1595. bool have = false;
  1596. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1597. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1598. have = true;
  1599. break;
  1600. }
  1601. }
  1602. if (!have)
  1603. memberCapabilities.push_back(id);
  1604. }
  1605. }
  1606. }
  1607. }
  1608. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1609. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1610. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1611. if (ctmp != capsById.end()) {
  1612. json *cap = ctmp->second;
  1613. if ((cap)&&(cap->is_object())&&(!cap->empty())) {
  1614. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1615. unsigned int caprc = 0;
  1616. json &caprj = (*cap)["rules"];
  1617. if ((caprj.is_array())&&(!caprj.empty())) {
  1618. for(unsigned long j=0;j<caprj.size();++j) {
  1619. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1620. break;
  1621. if (_parseRule(caprj[j],capr[caprc]))
  1622. ++caprc;
  1623. }
  1624. }
  1625. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1626. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1627. ++nc->capabilityCount;
  1628. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1629. break;
  1630. }
  1631. }
  1632. }
  1633. std::map< uint32_t,uint32_t > memberTagsById;
  1634. if (memberTags.is_array()) {
  1635. for(unsigned long i=0;i<memberTags.size();++i) {
  1636. json &t = memberTags[i];
  1637. if ((t.is_array())&&(t.size() == 2))
  1638. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1639. }
  1640. }
  1641. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1642. for(unsigned long i=0;i<tags.size();++i) {
  1643. json &t = tags[i];
  1644. if (t.is_object()) {
  1645. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1646. json &dfl = t["default"];
  1647. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1648. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1649. json mt = json::array();
  1650. mt.push_back(id);
  1651. mt.push_back(dfl);
  1652. memberTags.push_back(mt); // add default to member tags if not present
  1653. }
  1654. }
  1655. }
  1656. }
  1657. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1658. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1659. break;
  1660. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1661. if (nc->tags[nc->tagCount].sign(_signingId))
  1662. ++nc->tagCount;
  1663. }
  1664. }
  1665. if (routes.is_array()) {
  1666. for(unsigned long i=0;i<routes.size();++i) {
  1667. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1668. break;
  1669. json &route = routes[i];
  1670. json &target = route["target"];
  1671. json &via = route["via"];
  1672. if (target.is_string()) {
  1673. const InetAddress t(target.get<std::string>().c_str());
  1674. InetAddress v;
  1675. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  1676. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1677. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1678. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1679. if (v.ss_family == t.ss_family)
  1680. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1681. ++nc->routeCount;
  1682. }
  1683. }
  1684. }
  1685. }
  1686. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1687. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1688. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1689. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1690. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1691. }
  1692. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1693. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1694. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1695. }
  1696. }
  1697. bool haveManagedIpv4AutoAssignment = false;
  1698. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1699. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1700. if (ipAssignments.is_array()) {
  1701. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1702. if (ipAssignments[i].is_string()) {
  1703. const std::string ips = ipAssignments[i];
  1704. InetAddress ip(ips.c_str());
  1705. int routedNetmaskBits = -1;
  1706. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1707. if (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1708. const int nb = (int)(reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits());
  1709. if (nb > routedNetmaskBits)
  1710. routedNetmaskBits = nb;
  1711. }
  1712. }
  1713. if (routedNetmaskBits >= 0) {
  1714. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1715. ip.setPort(routedNetmaskBits);
  1716. nc->staticIps[nc->staticIpCount++] = ip;
  1717. }
  1718. if (ip.ss_family == AF_INET)
  1719. haveManagedIpv4AutoAssignment = true;
  1720. else if (ip.ss_family == AF_INET6)
  1721. haveManagedIpv6AutoAssignment = true;
  1722. }
  1723. }
  1724. }
  1725. } else {
  1726. ipAssignments = json::array();
  1727. }
  1728. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1729. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1730. json &pool = ipAssignmentPools[p];
  1731. if (pool.is_object()) {
  1732. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1733. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1734. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1735. uint64_t s[2],e[2],x[2],xx[2];
  1736. memcpy(s,ipRangeStart.rawIpData(),16);
  1737. memcpy(e,ipRangeEnd.rawIpData(),16);
  1738. s[0] = Utils::ntoh(s[0]);
  1739. s[1] = Utils::ntoh(s[1]);
  1740. e[0] = Utils::ntoh(e[0]);
  1741. e[1] = Utils::ntoh(e[1]);
  1742. x[0] = s[0];
  1743. x[1] = s[1];
  1744. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1745. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1746. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1747. xx[0] = Utils::hton(x[0]);
  1748. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1749. } else {
  1750. // 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
  1751. Utils::getSecureRandom((void *)xx,16);
  1752. if ((e[0] > s[0]))
  1753. xx[0] %= (e[0] - s[0]);
  1754. else xx[0] = 0;
  1755. if ((e[1] > s[1]))
  1756. xx[1] %= (e[1] - s[1]);
  1757. else xx[1] = 0;
  1758. xx[0] = Utils::hton(x[0] + xx[0]);
  1759. xx[1] = Utils::hton(x[1] + xx[1]);
  1760. }
  1761. InetAddress ip6((const void *)xx,16,0);
  1762. // Check if this IP is within a local-to-Ethernet routed network
  1763. int routedNetmaskBits = 0;
  1764. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1765. 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)) )
  1766. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1767. }
  1768. // If it's routed, then try to claim and assign it and if successful end loop
  1769. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1770. char tmpip[64];
  1771. const std::string ipStr(ip6.toIpString(tmpip));
  1772. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1773. ipAssignments.push_back(ipStr);
  1774. member["ipAssignments"] = ipAssignments;
  1775. ip6.setPort((unsigned int)routedNetmaskBits);
  1776. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1777. nc->staticIps[nc->staticIpCount++] = ip6;
  1778. haveManagedIpv6AutoAssignment = true;
  1779. break;
  1780. }
  1781. }
  1782. }
  1783. }
  1784. }
  1785. }
  1786. }
  1787. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1788. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1789. json &pool = ipAssignmentPools[p];
  1790. if (pool.is_object()) {
  1791. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1792. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1793. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1794. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1795. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1796. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1797. continue;
  1798. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1799. // Start with the LSB of the member's address
  1800. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1801. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1802. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1803. ++ipTrialCounter;
  1804. if ((ip & 0x000000ff) == 0x000000ff) {
  1805. continue; // don't allow addresses that end in .255
  1806. }
  1807. // Check if this IP is within a local-to-Ethernet routed network
  1808. int routedNetmaskBits = -1;
  1809. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1810. if (nc->routes[rk].target.ss_family == AF_INET) {
  1811. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1812. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1813. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1814. routedNetmaskBits = targetBits;
  1815. break;
  1816. }
  1817. }
  1818. }
  1819. // If it's routed, then try to claim and assign it and if successful end loop
  1820. const InetAddress ip4(Utils::hton(ip),0);
  1821. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1822. char tmpip[64];
  1823. const std::string ipStr(ip4.toIpString(tmpip));
  1824. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1825. ipAssignments.push_back(ipStr);
  1826. member["ipAssignments"] = ipAssignments;
  1827. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1828. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1829. v4ip->sin_family = AF_INET;
  1830. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1831. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1832. }
  1833. haveManagedIpv4AutoAssignment = true;
  1834. break;
  1835. }
  1836. }
  1837. }
  1838. }
  1839. }
  1840. }
  1841. }
  1842. if(dns.is_object()) {
  1843. std::string domain = OSUtils::jsonString(dns["domain"],"");
  1844. memcpy(nc->dns.domain, domain.c_str(), domain.size());
  1845. json &addrArray = dns["servers"];
  1846. if (addrArray.is_array()) {
  1847. for(unsigned int j = 0; j < addrArray.size() && j < ZT_MAX_DNS_SERVERS; ++j) {
  1848. json &addr = addrArray[j];
  1849. nc->dns.server_addr[j] = InetAddress(OSUtils::jsonString(addr,"").c_str());
  1850. }
  1851. }
  1852. } else {
  1853. dns = json::object();
  1854. }
  1855. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1856. b8.stop();
  1857. #endif
  1858. // Issue a certificate of ownership for all static IPs
  1859. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1860. auto b9 = _issue_certificate.Add({{"thread",threadID}});
  1861. auto c9 = _issue_certificate_count.Add({{"thread",threadID}});
  1862. c9++;
  1863. b9.start();
  1864. #endif
  1865. if (nc->staticIpCount) {
  1866. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1867. for(unsigned int i=0;i<nc->staticIpCount;++i) {
  1868. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1869. }
  1870. nc->certificatesOfOwnership[0].sign(_signingId);
  1871. nc->certificateOfOwnershipCount = 1;
  1872. }
  1873. CertificateOfMembership com(now,credentialtmd,nwid,identity);
  1874. if (com.sign(_signingId)) {
  1875. nc->com = com;
  1876. } else {
  1877. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR, nullptr, 0);
  1878. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1879. b9.stop();
  1880. #endif
  1881. return;
  1882. }
  1883. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1884. b9.stop();
  1885. auto b10 = _save_member.Add({{"thread",threadID}});
  1886. auto c10 = _save_member_count.Add({{"thread",threadID}});
  1887. c10++;
  1888. b10.start();
  1889. #endif
  1890. DB::cleanMember(member);
  1891. _db.save(member,true);
  1892. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1893. b10.stop();
  1894. auto b11 = _send_netconf.Add({{"thread",threadID}});
  1895. auto c11 = _send_netconf_count.Add({{"thread",threadID}});
  1896. c11++;
  1897. b11.start();
  1898. #endif
  1899. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  1900. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1901. b11.stop();
  1902. #endif
  1903. }
  1904. void EmbeddedNetworkController::_startThreads()
  1905. {
  1906. std::lock_guard<std::mutex> l(_threads_l);
  1907. if (!_threads.empty()) {
  1908. return;
  1909. }
  1910. const long hwc = std::max((long)std::thread::hardware_concurrency(),(long)1);
  1911. for(long t=0;t<hwc;++t) {
  1912. _threads.emplace_back([this]() {
  1913. Metrics::network_config_request_threads++;
  1914. for(;;) {
  1915. _RQEntry *qe = (_RQEntry *)0;
  1916. Metrics::network_config_request_queue_size = _queue.size();
  1917. auto timedWaitResult = _queue.get(qe, 1000);
  1918. if (timedWaitResult == BlockingQueue<_RQEntry *>::STOP) {
  1919. break;
  1920. } else if (timedWaitResult == BlockingQueue<_RQEntry *>::OK) {
  1921. if (qe) {
  1922. try {
  1923. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1924. } catch (std::exception &e) {
  1925. fprintf(stderr,"ERROR: exception in controller request handling thread: %s" ZT_EOL_S,e.what());
  1926. } catch ( ... ) {
  1927. fprintf(stderr,"ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  1928. }
  1929. delete qe;
  1930. qe = nullptr;
  1931. }
  1932. }
  1933. }
  1934. Metrics::network_config_request_threads--;
  1935. });
  1936. }
  1937. }
  1938. void EmbeddedNetworkController::_ssoExpiryThread() {
  1939. while(_ssoExpiryRunning) {
  1940. std::vector<_MemberStatusKey> expired;
  1941. nlohmann::json network, member;
  1942. int64_t now = OSUtils::now();
  1943. {
  1944. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1945. for(auto s=_expiringSoon.begin();s!=_expiringSoon.end();) {
  1946. Metrics::sso_expiration_checks++;
  1947. const int64_t when = s->first;
  1948. if (when <= now) {
  1949. // The user may have re-authorized, so we must actually look it up and check.
  1950. network.clear();
  1951. member.clear();
  1952. if (_db.get(s->second.networkId, network, s->second.nodeId, member)) {
  1953. int64_t authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1954. if (authenticationExpiryTime <= now) {
  1955. expired.push_back(s->second);
  1956. }
  1957. }
  1958. s = _expiringSoon.erase(s);
  1959. } else {
  1960. // Don't bother going further into the future than necessary.
  1961. break;
  1962. }
  1963. }
  1964. }
  1965. for(auto e=expired.begin();e!=expired.end();++e) {
  1966. Metrics::sso_member_deauth++;
  1967. onNetworkMemberDeauthorize(nullptr, e->networkId, e->nodeId);
  1968. }
  1969. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  1970. }
  1971. }
  1972. } // namespace ZeroTier