EmbeddedNetworkController.cpp 74 KB

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