2
0

EmbeddedNetworkController.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  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 "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 networkListPath2 = "/unstable/controller/network";
  813. std::string networkPath = "/controller/network/([0-9a-fA-F]{16})";
  814. std::string oldAndBustedNetworkCreatePath = "/controller/network/([0-9a-fA-F]{10})______";
  815. std::string memberListPath = "/controller/network/([0-9a-fA-F]{16})/member";
  816. std::string memberListPath2 = "/unstable/controller/network/([0-9a-fA-F]{16})/member";
  817. std::string memberPath = "/controller/network/([0-9a-fA-F]{16})/member/([0-9a-fA-F]{10})";
  818. auto controllerGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  819. char tmp[4096];
  820. const bool dbOk = _db.isReady();
  821. OSUtils::ztsnprintf(
  822. tmp,
  823. sizeof(tmp),
  824. "{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",
  825. ZT_NETCONF_CONTROLLER_API_VERSION,
  826. (unsigned long long)OSUtils::now(),
  827. dbOk ? "true" : "false");
  828. if (!dbOk) {
  829. res.status = 503;
  830. }
  831. setContent(req, res, tmp);
  832. };
  833. s.Get(controllerPath, controllerGet);
  834. sv6.Get(controllerPath, controllerGet);
  835. auto networkListGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  836. std::set<uint64_t> networkIds;
  837. _db.networks(networkIds);
  838. char tmp[64];
  839. auto out = json::array();
  840. for(std::set<uint64_t>::const_iterator i(networkIds.begin()); i != networkIds.end(); ++i) {
  841. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%.16llx", *i);
  842. out.push_back(tmp);
  843. }
  844. setContent(req, res, out.dump());
  845. };
  846. s.Get(networkListPath, networkListGet);
  847. sv6.Get(networkListPath, networkListGet);
  848. auto networkListGet2 = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  849. std::set<uint64_t> networkIds;
  850. _db.networks(networkIds);
  851. auto meta = json::object();
  852. auto data = json::array();
  853. uint64_t networkCount = 0;
  854. for(std::set<uint64_t>::const_iterator nwid(networkIds.begin()); nwid != networkIds.end(); ++nwid) {
  855. json network;
  856. if (!_db.get(*nwid, network)) {
  857. continue;
  858. }
  859. std::vector<json> memTmp;
  860. if (_db.get(*nwid, network, memTmp)) {
  861. if (!network.is_null()) {
  862. uint64_t authorizedCount = 0;
  863. uint64_t totalCount = memTmp.size();
  864. networkCount++;
  865. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  866. bool a = OSUtils::jsonBool((*m)["authorized"], 0);
  867. if (a) { authorizedCount++; }
  868. }
  869. auto nwMeta = json::object();
  870. nwMeta["totalMemberCount"] = totalCount;
  871. nwMeta["authorizedMemberCount"] = authorizedCount;
  872. network["meta"] = nwMeta;
  873. data.push_back(network);
  874. }
  875. }
  876. }
  877. meta["networkCount"] = networkCount;
  878. auto out = json::object();
  879. out["data"] = data;
  880. out["meta"] = meta;
  881. setContent(req, res, out.dump());
  882. };
  883. s.Get(networkListPath2, networkListGet2);
  884. sv6.Get(networkListPath2, networkListGet2);
  885. auto networkGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  886. auto networkID = req.matches[1];
  887. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  888. json network;
  889. if (!_db.get(nwid, network)) {
  890. res.status = 404;
  891. return;
  892. }
  893. setContent(req, res, network.dump());
  894. };
  895. s.Get(networkPath, networkGet);
  896. sv6.Get(networkPath, networkGet);
  897. auto createNewNetwork = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  898. // fprintf(stderr, "creating new network (new style)\n");
  899. uint64_t nwid = 0;
  900. uint64_t nwidPrefix = (Utils::hexStrToU64(_signingIdAddressString.c_str()) << 24) & 0xffffffffff000000ULL;
  901. uint64_t nwidPostfix = 0;
  902. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  903. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  904. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  905. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  906. if (!_db.hasNetwork(tryNwid)) {
  907. nwid = tryNwid;
  908. break;
  909. }
  910. }
  911. if (!nwid) {
  912. res.status = 503;
  913. return;
  914. }
  915. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  916. };
  917. s.Put(networkListPath, createNewNetwork);
  918. s.Post(networkListPath, createNewNetwork);
  919. sv6.Put(networkListPath, createNewNetwork);
  920. sv6.Post(networkListPath, createNewNetwork);
  921. auto createNewNetworkOldAndBusted = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  922. auto inID = req.matches[1].str();
  923. if (inID != _signingIdAddressString) {
  924. res.status = 400;
  925. return;
  926. }
  927. uint64_t nwid = 0;
  928. uint64_t nwidPrefix = (Utils::hexStrToU64(inID.c_str()) << 24) & 0xffffffffff000000ULL;
  929. uint64_t nwidPostfix = 0;
  930. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  931. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  932. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  933. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  934. if (!_db.hasNetwork(tryNwid)) {
  935. nwid = tryNwid;
  936. break;
  937. }
  938. }
  939. if (!nwid) {
  940. res.status = 503;
  941. return;
  942. }
  943. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  944. };
  945. s.Put(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  946. s.Post(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  947. sv6.Put(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  948. sv6.Post(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  949. auto networkPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  950. auto networkID = req.matches[1].str();
  951. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  952. res.status = 200;
  953. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  954. };
  955. s.Put(networkPath, networkPost);
  956. s.Post(networkPath, networkPost);
  957. sv6.Put(networkPath, networkPost);
  958. sv6.Post(networkPath, networkPost);
  959. auto networkDelete = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  960. auto networkID = req.matches[1].str();
  961. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  962. json network;
  963. if (!_db.get(nwid,network)) {
  964. res.status = 404;
  965. return;
  966. }
  967. _db.eraseNetwork(nwid);
  968. setContent(req, res, network.dump());
  969. };
  970. s.Delete(networkPath, networkDelete);
  971. sv6.Delete(networkPath, networkDelete);
  972. auto memberListGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  973. auto networkID = req.matches[1];
  974. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  975. json network;
  976. if (!_db.get(nwid, network)) {
  977. res.status = 404;
  978. return;
  979. }
  980. json out = json::object();
  981. std::vector<json> memTmp;
  982. if (_db.get(nwid, network, memTmp)) {
  983. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  984. int revision = OSUtils::jsonInt((*m)["revision"], 0);
  985. std::string id = OSUtils::jsonString((*m)["id"], "");
  986. if (id.length() == 10) {
  987. out[id] = revision;
  988. }
  989. }
  990. }
  991. setContent(req, res, out.dump());
  992. };
  993. s.Get(memberListPath, memberListGet);
  994. sv6.Get(memberListPath, memberListGet);
  995. auto memberListGet2 = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  996. auto networkID = req.matches[1];
  997. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  998. json network;
  999. if (!_db.get(nwid, network)) {
  1000. res.status = 404;
  1001. return;
  1002. }
  1003. auto out = nlohmann::json::object();
  1004. auto meta = nlohmann::json::object();
  1005. std::vector<json> memTmp;
  1006. if (_db.get(nwid, network, memTmp)) {
  1007. uint64_t authorizedCount = 0;
  1008. uint64_t totalCount = memTmp.size();
  1009. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  1010. bool a = OSUtils::jsonBool((*m)["authorized"], 0);
  1011. if (a) { authorizedCount++; }
  1012. }
  1013. meta["totalCount"] = totalCount;
  1014. meta["authorizedCount"] = authorizedCount;
  1015. out["data"] = memTmp;
  1016. out["meta"] = meta;
  1017. setContent(req, res, out.dump());
  1018. } else {
  1019. res.status = 404;
  1020. return;
  1021. }
  1022. };
  1023. s.Get(memberListPath2, memberListGet2);
  1024. sv6.Get(memberListPath2, memberListGet2);
  1025. auto memberGet = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1026. auto networkID = req.matches[1];
  1027. auto memberID = req.matches[2];
  1028. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  1029. uint64_t memid = Utils::hexStrToU64(memberID.str().c_str());
  1030. json network;
  1031. json member;
  1032. if (!_db.get(nwid, network, memid, member)) {
  1033. res.status = 404;
  1034. return;
  1035. }
  1036. setContent(req, res, member.dump());
  1037. };
  1038. s.Get(memberPath, memberGet);
  1039. sv6.Get(memberPath, memberGet);
  1040. auto memberPost = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1041. auto networkID = req.matches[1].str();
  1042. auto memberID = req.matches[2].str();
  1043. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1044. uint64_t memid = Utils::hexStrToU64(memberID.c_str());
  1045. if (!_db.hasNetwork(nwid)) {
  1046. res.status = 404;
  1047. return;
  1048. }
  1049. json network;
  1050. json member;
  1051. _db.get(nwid, network, memid, member);
  1052. DB::initMember(member);
  1053. json b = OSUtils::jsonParse(req.body);
  1054. if (b.count("activeBridge")) member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"], false);
  1055. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"], false);
  1056. if (b.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = (uint64_t)OSUtils::jsonInt(b["authenticationExpiryTime"], 0ULL);
  1057. if (b.count("authenticationURL")) member["authenticationURL"] = OSUtils::jsonString(b["authenticationURL"], "");
  1058. if (b.count("name")) member["name"] = OSUtils::jsonString(b["name"], "");
  1059. if (b.count("remoteTraceTarget")) {
  1060. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  1061. if (rtt.length() == 10) {
  1062. member["remoteTraceTarget"] = rtt;
  1063. } else {
  1064. member["remoteTraceTarget"] = json();
  1065. }
  1066. }
  1067. if (b.count("remoteTraceLevel")) member["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  1068. if (b.count("authorized")) {
  1069. const bool newAuth = OSUtils::jsonBool(b["authorized"],false);
  1070. if (newAuth != OSUtils::jsonBool(member["authorized"],false)) {
  1071. member["authorized"] = newAuth;
  1072. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = OSUtils::now();
  1073. if (newAuth) {
  1074. member["lastAuthorizedCredentialType"] = "api";
  1075. member["lastAuthorizedCredential"] = json();
  1076. }
  1077. }
  1078. }
  1079. if (b.count("ipAssignments")) {
  1080. json &ipa = b["ipAssignments"];
  1081. if (ipa.is_array()) {
  1082. json mipa(json::array());
  1083. for(unsigned long i=0;i<ipa.size();++i) {
  1084. std::string ips = ipa[i];
  1085. InetAddress ip(ips.c_str());
  1086. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1087. char tmpip[64];
  1088. mipa.push_back(ip.toIpString(tmpip));
  1089. if (mipa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1090. break;
  1091. }
  1092. }
  1093. member["ipAssignments"] = mipa;
  1094. }
  1095. }
  1096. if (b.count("tags")) {
  1097. json &tags = b["tags"];
  1098. if (tags.is_array()) {
  1099. std::map<uint64_t,uint64_t> mtags;
  1100. for(unsigned long i=0;i<tags.size();++i) {
  1101. json &tag = tags[i];
  1102. if ((tag.is_array())&&(tag.size() == 2))
  1103. mtags[OSUtils::jsonInt(tag[0],0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1],0ULL) & 0xffffffffULL;
  1104. }
  1105. json mtagsa = json::array();
  1106. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1107. json ta = json::array();
  1108. ta.push_back(t->first);
  1109. ta.push_back(t->second);
  1110. mtagsa.push_back(ta);
  1111. if (mtagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1112. break;
  1113. }
  1114. member["tags"] = mtagsa;
  1115. }
  1116. }
  1117. if (b.count("capabilities")) {
  1118. json &capabilities = b["capabilities"];
  1119. if (capabilities.is_array()) {
  1120. json mcaps = json::array();
  1121. for(unsigned long i=0;i<capabilities.size();++i) {
  1122. mcaps.push_back(OSUtils::jsonInt(capabilities[i],0ULL));
  1123. if (mcaps.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1124. break;
  1125. }
  1126. std::sort(mcaps.begin(),mcaps.end());
  1127. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1128. member["capabilities"] = mcaps;
  1129. }
  1130. }
  1131. member["id"] = memberID;
  1132. member["address"] = memberID;
  1133. member["nwid"] = networkID;
  1134. DB::cleanMember(member);
  1135. _db.save(member, true);
  1136. setContent(req, res, member.dump());
  1137. };
  1138. s.Put(memberPath, memberPost);
  1139. s.Post(memberPath, memberPost);
  1140. sv6.Put(memberPath, memberPost);
  1141. sv6.Post(memberPath, memberPost);
  1142. auto memberDelete = [&, setContent](const httplib::Request &req, httplib::Response &res) {
  1143. auto networkID = req.matches[1].str();
  1144. auto memberID = req.matches[2].str();
  1145. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1146. uint64_t address = Utils::hexStrToU64(memberID.c_str());
  1147. json network, member;
  1148. if (!_db.get(nwid, network, address, member)) {
  1149. res.status = 404;
  1150. return;
  1151. }
  1152. if (!member.size()) {
  1153. res.status = 404;
  1154. return;
  1155. }
  1156. _db.eraseMember(nwid, address);
  1157. setContent(req, res, member.dump());
  1158. };
  1159. s.Delete(memberPath, memberDelete);
  1160. sv6.Delete(memberPath, memberDelete);
  1161. }
  1162. void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace &rt)
  1163. {
  1164. static volatile unsigned long idCounter = 0;
  1165. char id[128],tmp[128];
  1166. std::string k,v;
  1167. try {
  1168. // Convert Dictionary into JSON object
  1169. json d;
  1170. char *saveptr = (char *)0;
  1171. for(char *l=Utils::stok(rt.data,"\n",&saveptr);(l);l=Utils::stok((char *)0,"\n",&saveptr)) {
  1172. char *eq = strchr(l,'=');
  1173. if (eq > l) {
  1174. k.assign(l,(unsigned long)(eq - l));
  1175. v.clear();
  1176. ++eq;
  1177. while (*eq) {
  1178. if (*eq == '\\') {
  1179. ++eq;
  1180. if (*eq) {
  1181. switch(*eq) {
  1182. case 'r': v.push_back('\r'); break;
  1183. case 'n': v.push_back('\n'); break;
  1184. case '0': v.push_back((char)0); break;
  1185. case 'e': v.push_back('='); break;
  1186. default: v.push_back(*eq); break;
  1187. }
  1188. ++eq;
  1189. }
  1190. } else {
  1191. v.push_back(*(eq++));
  1192. }
  1193. }
  1194. if ((k.length() > 0)&&(v.length() > 0))
  1195. d[k] = v;
  1196. }
  1197. }
  1198. const int64_t now = OSUtils::now();
  1199. OSUtils::ztsnprintf(id,sizeof(id),"%.10llx-%.16llx-%.10llx-%.4x",_signingId.address().toInt(),now,rt.origin,(unsigned int)(idCounter++ & 0xffff));
  1200. d["id"] = id;
  1201. d["objtype"] = "trace";
  1202. d["ts"] = now;
  1203. d["nodeId"] = Utils::hex10(rt.origin,tmp);
  1204. _db.save(d,true);
  1205. } catch ( ... ) {
  1206. // drop invalid trace messages if an error occurs
  1207. }
  1208. }
  1209. void EmbeddedNetworkController::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
  1210. {
  1211. // Send an update to all members of the network that are online
  1212. const int64_t now = OSUtils::now();
  1213. std::lock_guard<std::mutex> l(_memberStatus_l);
  1214. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1215. if ((i->first.networkId == networkId)&&(i->second.online(now))&&(i->second.lastRequestMetaData))
  1216. request(networkId,InetAddress(),0,i->second.identity,i->second.lastRequestMetaData);
  1217. }
  1218. }
  1219. void EmbeddedNetworkController::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
  1220. {
  1221. // Push update to member if online
  1222. try {
  1223. std::lock_guard<std::mutex> l(_memberStatus_l);
  1224. _MemberStatus &ms = _memberStatus[_MemberStatusKey(networkId,memberId)];
  1225. if ((ms.online(OSUtils::now()))&&(ms.lastRequestMetaData))
  1226. request(networkId,InetAddress(),0,ms.identity,ms.lastRequestMetaData);
  1227. } catch ( ... ) {}
  1228. }
  1229. void EmbeddedNetworkController::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
  1230. {
  1231. const int64_t now = OSUtils::now();
  1232. Revocation rev((uint32_t)_node->prng(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM);
  1233. rev.sign(_signingId);
  1234. {
  1235. std::lock_guard<std::mutex> l(_memberStatus_l);
  1236. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1237. if ((i->first.networkId == networkId)&&(i->second.online(now)))
  1238. _node->ncSendRevocation(Address(i->first.nodeId),rev);
  1239. }
  1240. }
  1241. }
  1242. void EmbeddedNetworkController::_request(
  1243. uint64_t nwid,
  1244. const InetAddress &fromAddr,
  1245. uint64_t requestPacketId,
  1246. const Identity &identity,
  1247. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  1248. {
  1249. Metrics::network_config_request++;
  1250. auto tid = std::this_thread::get_id();
  1251. std::stringstream ss; ss << tid;
  1252. std::string threadID = ss.str();
  1253. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1254. auto b1 = _member_status_lookup.Add({{"thread", threadID}});
  1255. auto c1 = _member_status_lookup_count.Add({{"thread", threadID}});
  1256. c1++;
  1257. b1.start();
  1258. #endif
  1259. char nwids[24];
  1260. DB::NetworkSummaryInfo ns;
  1261. json network,member;
  1262. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender)) {
  1263. return;
  1264. }
  1265. const int64_t now = OSUtils::now();
  1266. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1267. b1.stop();
  1268. auto b2 = _node_is_online.Add({{"thread",threadID}});
  1269. auto c2 = _node_is_online_count.Add({{"thread",threadID}});
  1270. c2++;
  1271. b2.start();
  1272. #endif
  1273. _db.nodeIsOnline(nwid,identity.address().toInt(),fromAddr);
  1274. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1275. b2.stop();
  1276. auto b3 = _get_and_init_member.Add({{"thread", threadID}});
  1277. auto c3 = _get_and_init_member_count.Add({{"thread",threadID}});
  1278. c3++;
  1279. b3.start();
  1280. #endif
  1281. Utils::hex(nwid,nwids);
  1282. _db.get(nwid,network,identity.address().toInt(),member,ns);
  1283. if ((!network.is_object())||(network.empty())) {
  1284. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND, nullptr, 0);
  1285. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1286. b3.stop();
  1287. #endif
  1288. return;
  1289. }
  1290. const bool newMember = ((!member.is_object())||(member.empty()));
  1291. DB::initMember(member);
  1292. _MemberStatusKey msk(nwid,identity.address().toInt());
  1293. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1294. b3.stop();
  1295. #endif
  1296. {
  1297. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1298. auto b4 = _have_identity.Add({{"thread",threadID}});
  1299. auto c4 = _have_identity_count.Add({{"thread",threadID}});
  1300. c4++;
  1301. b4.start();
  1302. #endif
  1303. const std::string haveIdStr(OSUtils::jsonString(member["identity"],""));
  1304. if (haveIdStr.length() > 0) {
  1305. // If we already know this member's identity perform a full compare. This prevents
  1306. // a "collision" from being able to auth onto our network in place of an already
  1307. // known member.
  1308. try {
  1309. if (Identity(haveIdStr.c_str()) != identity) {
  1310. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1311. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1312. b4.stop();
  1313. #endif
  1314. return;
  1315. }
  1316. } catch ( ... ) {
  1317. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1318. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1319. b4.stop();
  1320. #endif
  1321. return;
  1322. }
  1323. } else {
  1324. // If we do not yet know this member's identity, learn it.
  1325. char idtmp[1024];
  1326. member["identity"] = identity.toString(false,idtmp);
  1327. }
  1328. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1329. b4.stop();
  1330. #endif
  1331. }
  1332. // These are always the same, but make sure they are set
  1333. {
  1334. char tmpid[128];
  1335. const std::string addrs(identity.address().toString(tmpid));
  1336. member["id"] = addrs;
  1337. member["address"] = addrs;
  1338. member["nwid"] = nwids;
  1339. }
  1340. // Determine whether and how member is authorized
  1341. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1342. auto b5 = _determine_auth.Add({{"thread",threadID}});
  1343. auto c5 = _determine_auth_count.Add({{"thread",threadID}});
  1344. c5++;
  1345. b5.start();
  1346. #endif
  1347. bool authorized = false;
  1348. bool autoAuthorized = false;
  1349. json autoAuthCredentialType,autoAuthCredential;
  1350. if (OSUtils::jsonBool(member["authorized"],false)) {
  1351. authorized = true;
  1352. } else if (!OSUtils::jsonBool(network["private"],true)) {
  1353. authorized = true;
  1354. autoAuthorized = true;
  1355. autoAuthCredentialType = "public";
  1356. } else {
  1357. char presentedAuth[512];
  1358. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  1359. presentedAuth[511] = (char)0; // sanity check
  1360. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  1361. const char *const presentedToken = presentedAuth + 6;
  1362. json authTokens(network["authTokens"]);
  1363. json &tokenExpires = authTokens[presentedToken];
  1364. if (tokenExpires.is_number()) {
  1365. if ((tokenExpires == 0)||(tokenExpires > now)) {
  1366. authorized = true;
  1367. autoAuthorized = true;
  1368. autoAuthCredentialType = "token";
  1369. autoAuthCredential = presentedToken;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. }
  1375. // If we auto-authorized, update member record
  1376. if ((autoAuthorized)&&(authorized)) {
  1377. member["authorized"] = true;
  1378. member["lastAuthorizedTime"] = now;
  1379. member["lastAuthorizedCredentialType"] = autoAuthCredentialType;
  1380. member["lastAuthorizedCredential"] = autoAuthCredential;
  1381. }
  1382. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1383. b5.stop();
  1384. #endif
  1385. // Should we check SSO Stuff?
  1386. // If network is configured with SSO, and the member is not marked exempt: yes
  1387. // Otherwise no, we use standard auth logic.
  1388. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1389. auto b6 = _sso_check.Add({{"thread",threadID}});
  1390. auto c6 = _sso_check_count.Add({{"thread",threadID}});
  1391. c6++;
  1392. b6.start();
  1393. #endif
  1394. AuthInfo info;
  1395. int64_t authenticationExpiryTime = -1;
  1396. bool networkSSOEnabled = OSUtils::jsonBool(network["ssoEnabled"], false);
  1397. bool memberSSOExempt = OSUtils::jsonBool(member["ssoExempt"], false);
  1398. if (networkSSOEnabled && !memberSSOExempt) {
  1399. authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1400. info = _db.getSSOAuthInfo(member, _ssoRedirectURL);
  1401. assert(info.enabled == networkSSOEnabled);
  1402. if (authenticationExpiryTime <= now) {
  1403. if (info.version == 0) {
  1404. Dictionary<4096> authInfo;
  1405. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, (uint64_t)0ULL);
  1406. authInfo.add(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, info.authenticationURL.c_str());
  1407. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1408. } else if (info.version == 1) {
  1409. Dictionary<8192> authInfo;
  1410. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, info.version);
  1411. authInfo.add(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, info.issuerURL.c_str());
  1412. authInfo.add(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, info.centralAuthURL.c_str());
  1413. authInfo.add(ZT_AUTHINFO_DICT_KEY_NONCE, info.ssoNonce.c_str());
  1414. authInfo.add(ZT_AUTHINFO_DICT_KEY_STATE, info.ssoState.c_str());
  1415. authInfo.add(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, info.ssoClientID.c_str());
  1416. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1417. }
  1418. DB::cleanMember(member);
  1419. _db.save(member,true);
  1420. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1421. b6.stop();
  1422. #endif
  1423. return;
  1424. }
  1425. }
  1426. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1427. b6.stop();
  1428. auto b7 = _auth_check.Add({{"thread",threadID}});
  1429. auto c7 = _auth_check_count.Add({{"thread",threadID}});
  1430. c7++;
  1431. b7.start();
  1432. #endif
  1433. if (authorized) {
  1434. // Update version info and meta-data if authorized and if this is a genuine request
  1435. if (requestPacketId) {
  1436. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1437. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1438. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1439. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  1440. member["vMajor"] = vMajor;
  1441. member["vMinor"] = vMinor;
  1442. member["vRev"] = vRev;
  1443. member["vProto"] = vProto;
  1444. {
  1445. std::lock_guard<std::mutex> l(_memberStatus_l);
  1446. _MemberStatus &ms = _memberStatus[msk];
  1447. ms.authenticationExpiryTime = authenticationExpiryTime;
  1448. ms.vMajor = (int)vMajor;
  1449. ms.vMinor = (int)vMinor;
  1450. ms.vRev = (int)vRev;
  1451. ms.vProto = (int)vProto;
  1452. ms.lastRequestMetaData = metaData;
  1453. ms.identity = identity;
  1454. }
  1455. if (authenticationExpiryTime > 0) {
  1456. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1457. _expiringSoon.insert(std::pair<int64_t, _MemberStatusKey>(authenticationExpiryTime, msk));
  1458. }
  1459. }
  1460. } else {
  1461. // If they are not authorized, STOP!
  1462. DB::cleanMember(member);
  1463. _db.save(member,true);
  1464. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1465. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1466. b7.stop();
  1467. #endif
  1468. return;
  1469. }
  1470. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1471. b7.stop();
  1472. #endif
  1473. // -------------------------------------------------------------------------
  1474. // If we made it this far, they are authorized (and authenticated).
  1475. // -------------------------------------------------------------------------
  1476. // Default timeout: 15 minutes. Maximum: two hours. Can be specified by an optional field in the network config
  1477. // if something longer than 15 minutes is desired. Minimum is 5 minutes since shorter than that would be flaky.
  1478. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1479. auto b8 = _json_schlep.Add({{"thread",threadID}});
  1480. auto c8 = _json_schlep_count.Add({{"thread", threadID}});
  1481. c8++;
  1482. b8.start();
  1483. #endif
  1484. int64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_DFL_MAX_DELTA;
  1485. if (network.contains("certificateTimeoutWindowSize")) {
  1486. credentialtmd = (int64_t)network["certificateTimeoutWindowSize"];
  1487. }
  1488. credentialtmd = std::max(std::min(credentialtmd, ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA), ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA);
  1489. std::unique_ptr<NetworkConfig> nc(new NetworkConfig());
  1490. nc->networkId = nwid;
  1491. nc->type = OSUtils::jsonBool(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1492. nc->timestamp = now;
  1493. nc->credentialTimeMaxDelta = credentialtmd;
  1494. nc->revision = OSUtils::jsonInt(network["revision"],0ULL);
  1495. nc->issuedTo = identity.address();
  1496. if (OSUtils::jsonBool(network["enableBroadcast"],true)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1497. Utils::scopy(nc->name,sizeof(nc->name),OSUtils::jsonString(network["name"],"").c_str());
  1498. 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);
  1499. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"],32ULL);
  1500. nc->ssoEnabled = networkSSOEnabled; //OSUtils::jsonBool(network["ssoEnabled"], false);
  1501. nc->ssoVersion = info.version;
  1502. if (info.version == 0) {
  1503. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1504. if (!info.authenticationURL.empty()) {
  1505. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1506. }
  1507. }
  1508. else if (info.version == 1) {
  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. if (!info.centralAuthURL.empty()) {
  1514. Utils::scopy(nc->centralAuthURL, sizeof(nc->centralAuthURL), info.centralAuthURL.c_str());
  1515. }
  1516. if (!info.issuerURL.empty()) {
  1517. #ifdef ZT_DEBUG
  1518. fprintf(stderr, "copying issuerURL to nc: %s\n", info.issuerURL.c_str());
  1519. #endif
  1520. Utils::scopy(nc->issuerURL, sizeof(nc->issuerURL), info.issuerURL.c_str());
  1521. }
  1522. if (!info.ssoNonce.empty()) {
  1523. Utils::scopy(nc->ssoNonce, sizeof(nc->ssoNonce), info.ssoNonce.c_str());
  1524. }
  1525. if (!info.ssoState.empty()) {
  1526. Utils::scopy(nc->ssoState, sizeof(nc->ssoState), info.ssoState.c_str());
  1527. }
  1528. if (!info.ssoClientID.empty()) {
  1529. Utils::scopy(nc->ssoClientID, sizeof(nc->ssoClientID), info.ssoClientID.c_str());
  1530. }
  1531. }
  1532. std::string rtt(OSUtils::jsonString(member["remoteTraceTarget"],""));
  1533. if (rtt.length() == 10) {
  1534. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1535. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(member["remoteTraceLevel"],0ULL);
  1536. } else {
  1537. rtt = OSUtils::jsonString(network["remoteTraceTarget"],"");
  1538. if (rtt.length() == 10) {
  1539. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1540. } else {
  1541. nc->remoteTraceTarget.zero();
  1542. }
  1543. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(network["remoteTraceLevel"],0ULL);
  1544. }
  1545. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab) {
  1546. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1547. }
  1548. json &v4AssignMode = network["v4AssignMode"];
  1549. json &v6AssignMode = network["v6AssignMode"];
  1550. json &ipAssignmentPools = network["ipAssignmentPools"];
  1551. json &routes = network["routes"];
  1552. json &rules = network["rules"];
  1553. json &capabilities = network["capabilities"];
  1554. json &tags = network["tags"];
  1555. json &memberCapabilities = member["capabilities"];
  1556. json &memberTags = member["tags"];
  1557. json &dns = network["dns"];
  1558. //fprintf(stderr, "IP Assignment Pools for Network %s: %s\n", nwids, OSUtils::jsonDump(ipAssignmentPools, 2).c_str());
  1559. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1560. // Old versions with no rules engine support get an allow everything rule.
  1561. // Since rules are enforced bidirectionally, newer versions *will* still
  1562. // enforce rules on the inbound side.
  1563. nc->ruleCount = 1;
  1564. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1565. } else {
  1566. if (rules.is_array()) {
  1567. for(unsigned long i=0;i<rules.size();++i) {
  1568. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1569. break;
  1570. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1571. ++nc->ruleCount;
  1572. }
  1573. }
  1574. std::map< uint64_t,json * > capsById;
  1575. if (!memberCapabilities.is_array())
  1576. memberCapabilities = json::array();
  1577. if (capabilities.is_array()) {
  1578. for(unsigned long i=0;i<capabilities.size();++i) {
  1579. json &cap = capabilities[i];
  1580. if (cap.is_object()) {
  1581. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1582. capsById[id] = &cap;
  1583. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1584. bool have = false;
  1585. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1586. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1587. have = true;
  1588. break;
  1589. }
  1590. }
  1591. if (!have)
  1592. memberCapabilities.push_back(id);
  1593. }
  1594. }
  1595. }
  1596. }
  1597. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1598. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1599. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1600. if (ctmp != capsById.end()) {
  1601. json *cap = ctmp->second;
  1602. if ((cap)&&(cap->is_object())&&(!cap->empty())) {
  1603. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1604. unsigned int caprc = 0;
  1605. json &caprj = (*cap)["rules"];
  1606. if ((caprj.is_array())&&(!caprj.empty())) {
  1607. for(unsigned long j=0;j<caprj.size();++j) {
  1608. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1609. break;
  1610. if (_parseRule(caprj[j],capr[caprc]))
  1611. ++caprc;
  1612. }
  1613. }
  1614. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1615. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1616. ++nc->capabilityCount;
  1617. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1618. break;
  1619. }
  1620. }
  1621. }
  1622. std::map< uint32_t,uint32_t > memberTagsById;
  1623. if (memberTags.is_array()) {
  1624. for(unsigned long i=0;i<memberTags.size();++i) {
  1625. json &t = memberTags[i];
  1626. if ((t.is_array())&&(t.size() == 2))
  1627. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1628. }
  1629. }
  1630. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1631. for(unsigned long i=0;i<tags.size();++i) {
  1632. json &t = tags[i];
  1633. if (t.is_object()) {
  1634. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1635. json &dfl = t["default"];
  1636. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1637. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1638. json mt = json::array();
  1639. mt.push_back(id);
  1640. mt.push_back(dfl);
  1641. memberTags.push_back(mt); // add default to member tags if not present
  1642. }
  1643. }
  1644. }
  1645. }
  1646. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1647. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1648. break;
  1649. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1650. if (nc->tags[nc->tagCount].sign(_signingId))
  1651. ++nc->tagCount;
  1652. }
  1653. }
  1654. if (routes.is_array()) {
  1655. for(unsigned long i=0;i<routes.size();++i) {
  1656. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1657. break;
  1658. json &route = routes[i];
  1659. json &target = route["target"];
  1660. json &via = route["via"];
  1661. if (target.is_string()) {
  1662. const InetAddress t(target.get<std::string>().c_str());
  1663. InetAddress v;
  1664. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  1665. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1666. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1667. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1668. if (v.ss_family == t.ss_family)
  1669. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1670. ++nc->routeCount;
  1671. }
  1672. }
  1673. }
  1674. }
  1675. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1676. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1677. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1678. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1679. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1680. }
  1681. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1682. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1683. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1684. }
  1685. }
  1686. bool haveManagedIpv4AutoAssignment = false;
  1687. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1688. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1689. if (ipAssignments.is_array()) {
  1690. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1691. if (ipAssignments[i].is_string()) {
  1692. const std::string ips = ipAssignments[i];
  1693. InetAddress ip(ips.c_str());
  1694. int routedNetmaskBits = -1;
  1695. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1696. if (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1697. const int nb = (int)(reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits());
  1698. if (nb > routedNetmaskBits)
  1699. routedNetmaskBits = nb;
  1700. }
  1701. }
  1702. if (routedNetmaskBits >= 0) {
  1703. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1704. ip.setPort(routedNetmaskBits);
  1705. nc->staticIps[nc->staticIpCount++] = ip;
  1706. }
  1707. if (ip.ss_family == AF_INET)
  1708. haveManagedIpv4AutoAssignment = true;
  1709. else if (ip.ss_family == AF_INET6)
  1710. haveManagedIpv6AutoAssignment = true;
  1711. }
  1712. }
  1713. }
  1714. } else {
  1715. ipAssignments = json::array();
  1716. }
  1717. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1718. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1719. json &pool = ipAssignmentPools[p];
  1720. if (pool.is_object()) {
  1721. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1722. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1723. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1724. uint64_t s[2],e[2],x[2],xx[2];
  1725. memcpy(s,ipRangeStart.rawIpData(),16);
  1726. memcpy(e,ipRangeEnd.rawIpData(),16);
  1727. s[0] = Utils::ntoh(s[0]);
  1728. s[1] = Utils::ntoh(s[1]);
  1729. e[0] = Utils::ntoh(e[0]);
  1730. e[1] = Utils::ntoh(e[1]);
  1731. x[0] = s[0];
  1732. x[1] = s[1];
  1733. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1734. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1735. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1736. xx[0] = Utils::hton(x[0]);
  1737. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1738. } else {
  1739. // 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
  1740. Utils::getSecureRandom((void *)xx,16);
  1741. if ((e[0] > s[0]))
  1742. xx[0] %= (e[0] - s[0]);
  1743. else xx[0] = 0;
  1744. if ((e[1] > s[1]))
  1745. xx[1] %= (e[1] - s[1]);
  1746. else xx[1] = 0;
  1747. xx[0] = Utils::hton(x[0] + xx[0]);
  1748. xx[1] = Utils::hton(x[1] + xx[1]);
  1749. }
  1750. InetAddress ip6((const void *)xx,16,0);
  1751. // Check if this IP is within a local-to-Ethernet routed network
  1752. int routedNetmaskBits = 0;
  1753. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1754. 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)) )
  1755. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1756. }
  1757. // If it's routed, then try to claim and assign it and if successful end loop
  1758. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1759. char tmpip[64];
  1760. const std::string ipStr(ip6.toIpString(tmpip));
  1761. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1762. ipAssignments.push_back(ipStr);
  1763. member["ipAssignments"] = ipAssignments;
  1764. ip6.setPort((unsigned int)routedNetmaskBits);
  1765. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1766. nc->staticIps[nc->staticIpCount++] = ip6;
  1767. haveManagedIpv6AutoAssignment = true;
  1768. break;
  1769. }
  1770. }
  1771. }
  1772. }
  1773. }
  1774. }
  1775. }
  1776. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1777. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1778. json &pool = ipAssignmentPools[p];
  1779. if (pool.is_object()) {
  1780. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1781. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1782. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1783. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1784. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1785. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1786. continue;
  1787. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1788. // Start with the LSB of the member's address
  1789. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1790. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1791. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1792. ++ipTrialCounter;
  1793. if ((ip & 0x000000ff) == 0x000000ff) {
  1794. continue; // don't allow addresses that end in .255
  1795. }
  1796. // Check if this IP is within a local-to-Ethernet routed network
  1797. int routedNetmaskBits = -1;
  1798. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1799. if (nc->routes[rk].target.ss_family == AF_INET) {
  1800. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1801. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1802. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1803. routedNetmaskBits = targetBits;
  1804. break;
  1805. }
  1806. }
  1807. }
  1808. // If it's routed, then try to claim and assign it and if successful end loop
  1809. const InetAddress ip4(Utils::hton(ip),0);
  1810. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1811. char tmpip[64];
  1812. const std::string ipStr(ip4.toIpString(tmpip));
  1813. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1814. ipAssignments.push_back(ipStr);
  1815. member["ipAssignments"] = ipAssignments;
  1816. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1817. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1818. v4ip->sin_family = AF_INET;
  1819. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1820. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1821. }
  1822. haveManagedIpv4AutoAssignment = true;
  1823. break;
  1824. }
  1825. }
  1826. }
  1827. }
  1828. }
  1829. }
  1830. }
  1831. if(dns.is_object()) {
  1832. std::string domain = OSUtils::jsonString(dns["domain"],"");
  1833. memcpy(nc->dns.domain, domain.c_str(), domain.size());
  1834. json &addrArray = dns["servers"];
  1835. if (addrArray.is_array()) {
  1836. for(unsigned int j = 0; j < addrArray.size() && j < ZT_MAX_DNS_SERVERS; ++j) {
  1837. json &addr = addrArray[j];
  1838. nc->dns.server_addr[j] = InetAddress(OSUtils::jsonString(addr,"").c_str());
  1839. }
  1840. }
  1841. } else {
  1842. dns = json::object();
  1843. }
  1844. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1845. b8.stop();
  1846. #endif
  1847. // Issue a certificate of ownership for all static IPs
  1848. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1849. auto b9 = _issue_certificate.Add({{"thread",threadID}});
  1850. auto c9 = _issue_certificate_count.Add({{"thread",threadID}});
  1851. c9++;
  1852. b9.start();
  1853. #endif
  1854. if (nc->staticIpCount) {
  1855. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1856. for(unsigned int i=0;i<nc->staticIpCount;++i) {
  1857. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1858. }
  1859. nc->certificatesOfOwnership[0].sign(_signingId);
  1860. nc->certificateOfOwnershipCount = 1;
  1861. }
  1862. CertificateOfMembership com(now,credentialtmd,nwid,identity);
  1863. if (com.sign(_signingId)) {
  1864. nc->com = com;
  1865. } else {
  1866. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR, nullptr, 0);
  1867. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1868. b9.stop();
  1869. #endif
  1870. return;
  1871. }
  1872. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1873. b9.stop();
  1874. auto b10 = _save_member.Add({{"thread",threadID}});
  1875. auto c10 = _save_member_count.Add({{"thread",threadID}});
  1876. c10++;
  1877. b10.start();
  1878. #endif
  1879. DB::cleanMember(member);
  1880. _db.save(member,true);
  1881. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1882. b10.stop();
  1883. auto b11 = _send_netconf.Add({{"thread",threadID}});
  1884. auto c11 = _send_netconf_count.Add({{"thread",threadID}});
  1885. c11++;
  1886. b11.start();
  1887. #endif
  1888. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  1889. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1890. b11.stop();
  1891. #endif
  1892. }
  1893. void EmbeddedNetworkController::_startThreads()
  1894. {
  1895. std::lock_guard<std::mutex> l(_threads_l);
  1896. if (!_threads.empty()) {
  1897. return;
  1898. }
  1899. const long hwc = std::max((long)std::thread::hardware_concurrency(),(long)1);
  1900. for(long t=0;t<hwc;++t) {
  1901. _threads.emplace_back([this]() {
  1902. Metrics::network_config_request_threads++;
  1903. for(;;) {
  1904. _RQEntry *qe = (_RQEntry *)0;
  1905. Metrics::network_config_request_queue_size = _queue.size();
  1906. auto timedWaitResult = _queue.get(qe, 1000);
  1907. if (timedWaitResult == BlockingQueue<_RQEntry *>::STOP) {
  1908. break;
  1909. } else if (timedWaitResult == BlockingQueue<_RQEntry *>::OK) {
  1910. if (qe) {
  1911. try {
  1912. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1913. } catch (std::exception &e) {
  1914. fprintf(stderr,"ERROR: exception in controller request handling thread: %s" ZT_EOL_S,e.what());
  1915. } catch ( ... ) {
  1916. fprintf(stderr,"ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  1917. }
  1918. delete qe;
  1919. qe = nullptr;
  1920. }
  1921. }
  1922. }
  1923. Metrics::network_config_request_threads--;
  1924. });
  1925. }
  1926. }
  1927. void EmbeddedNetworkController::_ssoExpiryThread() {
  1928. while(_ssoExpiryRunning) {
  1929. std::vector<_MemberStatusKey> expired;
  1930. nlohmann::json network, member;
  1931. int64_t now = OSUtils::now();
  1932. {
  1933. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1934. for(auto s=_expiringSoon.begin();s!=_expiringSoon.end();) {
  1935. Metrics::sso_expiration_checks++;
  1936. const int64_t when = s->first;
  1937. if (when <= now) {
  1938. // The user may have re-authorized, so we must actually look it up and check.
  1939. network.clear();
  1940. member.clear();
  1941. if (_db.get(s->second.networkId, network, s->second.nodeId, member)) {
  1942. int64_t authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1943. if (authenticationExpiryTime <= now) {
  1944. expired.push_back(s->second);
  1945. }
  1946. }
  1947. s = _expiringSoon.erase(s);
  1948. } else {
  1949. // Don't bother going further into the future than necessary.
  1950. break;
  1951. }
  1952. }
  1953. }
  1954. for(auto e=expired.begin();e!=expired.end();++e) {
  1955. Metrics::sso_member_deauth++;
  1956. onNetworkMemberDeauthorize(nullptr, e->networkId, e->nodeId);
  1957. }
  1958. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  1959. }
  1960. }
  1961. } // namespace ZeroTier