EmbeddedNetworkController.cpp 73 KB

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