1
0

EmbeddedNetworkController.cpp 75 KB

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