EmbeddedNetworkController.cpp 72 KB

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