EmbeddedNetworkController.cpp 76 KB

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