EmbeddedNetworkController.cpp 73 KB

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