EmbeddedNetworkController.cpp 85 KB

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