EmbeddedNetworkController.cpp 74 KB

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