EmbeddedNetworkController.cpp 74 KB

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