2
0

EmbeddedNetworkController.cpp 73 KB

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