EmbeddedNetworkController.cpp 75 KB

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