2
0

EmbeddedNetworkController.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  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: 2023-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. #ifndef _WIN32
  19. #include <sys/time.h>
  20. #endif
  21. #include <sys/types.h>
  22. #include <algorithm>
  23. #include <utility>
  24. #include <stdexcept>
  25. #include <map>
  26. #include <thread>
  27. #include <memory>
  28. #include "../node/Constants.hpp"
  29. #include "../node/Node.hpp"
  30. #include "../node/CertificateOfMembership.hpp"
  31. #include "../node/NetworkConfig.hpp"
  32. #include "../node/Dictionary.hpp"
  33. #include "../node/MAC.hpp"
  34. #include "../include/ZeroTierOne.h"
  35. #include "EmbeddedNetworkController.hpp"
  36. #include "LFDB.hpp"
  37. #include "FileDB.hpp"
  38. #ifdef ZT_CONTROLLER_USE_LIBPQ
  39. #include "PostgreSQL.hpp"
  40. #endif
  41. using json = nlohmann::json;
  42. // API version reported via JSON control plane
  43. #define ZT_NETCONF_CONTROLLER_API_VERSION 4
  44. // Min duration between requests for an address/nwid combo to prevent floods
  45. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  46. // Global maximum size of arrays in JSON objects
  47. #define ZT_CONTROLLER_MAX_ARRAY_SIZE 16384
  48. namespace ZeroTier {
  49. namespace {
  50. static json _renderRule(ZT_VirtualNetworkRule &rule)
  51. {
  52. char tmp[128];
  53. json r = json::object();
  54. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  55. switch(rt) {
  56. case ZT_NETWORK_RULE_ACTION_DROP:
  57. r["type"] = "ACTION_DROP";
  58. break;
  59. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  60. r["type"] = "ACTION_ACCEPT";
  61. break;
  62. case ZT_NETWORK_RULE_ACTION_TEE:
  63. r["type"] = "ACTION_TEE";
  64. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  65. r["flags"] = (unsigned int)rule.v.fwd.flags;
  66. r["length"] = (unsigned int)rule.v.fwd.length;
  67. break;
  68. case ZT_NETWORK_RULE_ACTION_WATCH:
  69. r["type"] = "ACTION_WATCH";
  70. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  71. r["flags"] = (unsigned int)rule.v.fwd.flags;
  72. r["length"] = (unsigned int)rule.v.fwd.length;
  73. break;
  74. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  75. r["type"] = "ACTION_REDIRECT";
  76. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  77. r["flags"] = (unsigned int)rule.v.fwd.flags;
  78. break;
  79. case ZT_NETWORK_RULE_ACTION_BREAK:
  80. r["type"] = "ACTION_BREAK";
  81. break;
  82. default:
  83. break;
  84. }
  85. if (r.size() == 0) {
  86. switch(rt) {
  87. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  88. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  89. r["zt"] = Address(rule.v.zt).toString(tmp);
  90. break;
  91. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  92. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  93. r["zt"] = Address(rule.v.zt).toString(tmp);
  94. break;
  95. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  96. r["type"] = "MATCH_VLAN_ID";
  97. r["vlanId"] = (unsigned int)rule.v.vlanId;
  98. break;
  99. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  100. r["type"] = "MATCH_VLAN_PCP";
  101. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  102. break;
  103. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  104. r["type"] = "MATCH_VLAN_DEI";
  105. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  106. break;
  107. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  108. r["type"] = "MATCH_MAC_SOURCE";
  109. 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]);
  110. r["mac"] = tmp;
  111. break;
  112. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  113. r["type"] = "MATCH_MAC_DEST";
  114. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  115. r["mac"] = tmp;
  116. break;
  117. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  118. r["type"] = "MATCH_IPV4_SOURCE";
  119. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  120. break;
  121. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  122. r["type"] = "MATCH_IPV4_DEST";
  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_IPV6_SOURCE:
  126. r["type"] = "MATCH_IPV6_SOURCE";
  127. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  128. break;
  129. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  130. r["type"] = "MATCH_IPV6_DEST";
  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_IP_TOS:
  134. r["type"] = "MATCH_IP_TOS";
  135. r["mask"] = (unsigned int)rule.v.ipTos.mask;
  136. r["start"] = (unsigned int)rule.v.ipTos.value[0];
  137. r["end"] = (unsigned int)rule.v.ipTos.value[1];
  138. break;
  139. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  140. r["type"] = "MATCH_IP_PROTOCOL";
  141. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  142. break;
  143. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  144. r["type"] = "MATCH_ETHERTYPE";
  145. r["etherType"] = (unsigned int)rule.v.etherType;
  146. break;
  147. case ZT_NETWORK_RULE_MATCH_ICMP:
  148. r["type"] = "MATCH_ICMP";
  149. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  150. if ((rule.v.icmp.flags & 0x01) != 0)
  151. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  152. else r["icmpCode"] = json();
  153. break;
  154. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  155. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  156. r["start"] = (unsigned int)rule.v.port[0];
  157. r["end"] = (unsigned int)rule.v.port[1];
  158. break;
  159. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  160. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  161. r["start"] = (unsigned int)rule.v.port[0];
  162. r["end"] = (unsigned int)rule.v.port[1];
  163. break;
  164. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  165. r["type"] = "MATCH_CHARACTERISTICS";
  166. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics);
  167. r["mask"] = tmp;
  168. break;
  169. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  170. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  171. r["start"] = (unsigned int)rule.v.frameSize[0];
  172. r["end"] = (unsigned int)rule.v.frameSize[1];
  173. break;
  174. case ZT_NETWORK_RULE_MATCH_RANDOM:
  175. r["type"] = "MATCH_RANDOM";
  176. r["probability"] = (unsigned long)rule.v.randomProbability;
  177. break;
  178. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  179. r["type"] = "MATCH_TAGS_DIFFERENCE";
  180. r["id"] = rule.v.tag.id;
  181. r["value"] = rule.v.tag.value;
  182. break;
  183. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  184. r["type"] = "MATCH_TAGS_BITWISE_AND";
  185. r["id"] = rule.v.tag.id;
  186. r["value"] = rule.v.tag.value;
  187. break;
  188. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  189. r["type"] = "MATCH_TAGS_BITWISE_OR";
  190. r["id"] = rule.v.tag.id;
  191. r["value"] = rule.v.tag.value;
  192. break;
  193. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  194. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  195. r["id"] = rule.v.tag.id;
  196. r["value"] = rule.v.tag.value;
  197. break;
  198. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  199. r["type"] = "MATCH_TAGS_EQUAL";
  200. r["id"] = rule.v.tag.id;
  201. r["value"] = rule.v.tag.value;
  202. break;
  203. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  204. r["type"] = "MATCH_TAG_SENDER";
  205. r["id"] = rule.v.tag.id;
  206. r["value"] = rule.v.tag.value;
  207. break;
  208. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER:
  209. r["type"] = "MATCH_TAG_RECEIVER";
  210. r["id"] = rule.v.tag.id;
  211. r["value"] = rule.v.tag.value;
  212. break;
  213. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE:
  214. r["type"] = "INTEGER_RANGE";
  215. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start);
  216. r["start"] = tmp;
  217. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start + (uint64_t)rule.v.intRange.end);
  218. r["end"] = tmp;
  219. r["idx"] = rule.v.intRange.idx;
  220. r["little"] = ((rule.v.intRange.format & 0x80) != 0);
  221. r["bits"] = (rule.v.intRange.format & 63) + 1;
  222. break;
  223. default:
  224. break;
  225. }
  226. if (r.size() > 0) {
  227. r["not"] = ((rule.t & 0x80) != 0);
  228. r["or"] = ((rule.t & 0x40) != 0);
  229. }
  230. }
  231. return r;
  232. }
  233. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  234. {
  235. if (!r.is_object())
  236. return false;
  237. const std::string t(OSUtils::jsonString(r["type"],""));
  238. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  239. if (OSUtils::jsonBool(r["not"],false))
  240. rule.t = 0x80;
  241. else rule.t = 0x00;
  242. if (OSUtils::jsonBool(r["or"],false))
  243. rule.t |= 0x40;
  244. bool tag = false;
  245. if (t == "ACTION_DROP") {
  246. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  247. return true;
  248. } else if (t == "ACTION_ACCEPT") {
  249. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  250. return true;
  251. } else if (t == "ACTION_TEE") {
  252. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  253. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  254. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  255. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  256. return true;
  257. } else if (t == "ACTION_WATCH") {
  258. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  259. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  260. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  261. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  262. return true;
  263. } else if (t == "ACTION_REDIRECT") {
  264. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  265. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  266. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  267. return true;
  268. } else if (t == "ACTION_BREAK") {
  269. rule.t |= ZT_NETWORK_RULE_ACTION_BREAK;
  270. return true;
  271. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  272. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  273. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  274. return true;
  275. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  276. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  277. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  278. return true;
  279. } else if (t == "MATCH_VLAN_ID") {
  280. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  281. rule.v.vlanId = (uint16_t)(OSUtils::jsonInt(r["vlanId"],0ULL) & 0xffffULL);
  282. return true;
  283. } else if (t == "MATCH_VLAN_PCP") {
  284. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  285. rule.v.vlanPcp = (uint8_t)(OSUtils::jsonInt(r["vlanPcp"],0ULL) & 0xffULL);
  286. return true;
  287. } else if (t == "MATCH_VLAN_DEI") {
  288. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  289. rule.v.vlanDei = (uint8_t)(OSUtils::jsonInt(r["vlanDei"],0ULL) & 0xffULL);
  290. return true;
  291. } else if (t == "MATCH_MAC_SOURCE") {
  292. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  293. const std::string mac(OSUtils::jsonString(r["mac"],"0"));
  294. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  295. return true;
  296. } else if (t == "MATCH_MAC_DEST") {
  297. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  298. const std::string mac(OSUtils::jsonString(r["mac"],"0"));
  299. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  300. return true;
  301. } else if (t == "MATCH_IPV4_SOURCE") {
  302. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  303. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  304. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  305. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  306. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  307. return true;
  308. } else if (t == "MATCH_IPV4_DEST") {
  309. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  310. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  311. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  312. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  313. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  314. return true;
  315. } else if (t == "MATCH_IPV6_SOURCE") {
  316. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  317. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  318. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  319. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  320. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  321. return true;
  322. } else if (t == "MATCH_IPV6_DEST") {
  323. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  324. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  325. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  326. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  327. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  328. return true;
  329. } else if (t == "MATCH_IP_TOS") {
  330. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  331. rule.v.ipTos.mask = (uint8_t)(OSUtils::jsonInt(r["mask"],0ULL) & 0xffULL);
  332. rule.v.ipTos.value[0] = (uint8_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffULL);
  333. rule.v.ipTos.value[1] = (uint8_t)(OSUtils::jsonInt(r["end"],0ULL) & 0xffULL);
  334. return true;
  335. } else if (t == "MATCH_IP_PROTOCOL") {
  336. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  337. rule.v.ipProtocol = (uint8_t)(OSUtils::jsonInt(r["ipProtocol"],0ULL) & 0xffULL);
  338. return true;
  339. } else if (t == "MATCH_ETHERTYPE") {
  340. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  341. rule.v.etherType = (uint16_t)(OSUtils::jsonInt(r["etherType"],0ULL) & 0xffffULL);
  342. return true;
  343. } else if (t == "MATCH_ICMP") {
  344. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  345. rule.v.icmp.type = (uint8_t)(OSUtils::jsonInt(r["icmpType"],0ULL) & 0xffULL);
  346. json &code = r["icmpCode"];
  347. if (code.is_null()) {
  348. rule.v.icmp.code = 0;
  349. rule.v.icmp.flags = 0x00;
  350. } else {
  351. rule.v.icmp.code = (uint8_t)(OSUtils::jsonInt(code,0ULL) & 0xffULL);
  352. rule.v.icmp.flags = 0x01;
  353. }
  354. return true;
  355. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  356. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  357. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  358. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  359. return true;
  360. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  361. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  362. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  363. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  364. return true;
  365. } else if (t == "MATCH_CHARACTERISTICS") {
  366. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  367. if (r.count("mask")) {
  368. json &v = r["mask"];
  369. if (v.is_number()) {
  370. rule.v.characteristics = v;
  371. } else {
  372. std::string tmp = v;
  373. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  374. }
  375. }
  376. return true;
  377. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  378. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  379. rule.v.frameSize[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  380. rule.v.frameSize[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  381. return true;
  382. } else if (t == "MATCH_RANDOM") {
  383. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  384. rule.v.randomProbability = (uint32_t)(OSUtils::jsonInt(r["probability"],0ULL) & 0xffffffffULL);
  385. return true;
  386. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  387. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  388. tag = true;
  389. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  390. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  391. tag = true;
  392. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  393. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  394. tag = true;
  395. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  396. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  397. tag = true;
  398. } else if (t == "MATCH_TAGS_EQUAL") {
  399. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  400. tag = true;
  401. } else if (t == "MATCH_TAG_SENDER") {
  402. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_SENDER;
  403. tag = true;
  404. } else if (t == "MATCH_TAG_RECEIVER") {
  405. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_RECEIVER;
  406. tag = true;
  407. } else if (t == "INTEGER_RANGE") {
  408. json &s = r["start"];
  409. if (s.is_string()) {
  410. std::string tmp = s;
  411. rule.v.intRange.start = Utils::hexStrToU64(tmp.c_str());
  412. } else {
  413. rule.v.intRange.start = OSUtils::jsonInt(s,0ULL);
  414. }
  415. json &e = r["end"];
  416. if (e.is_string()) {
  417. std::string tmp = e;
  418. rule.v.intRange.end = (uint32_t)(Utils::hexStrToU64(tmp.c_str()) - rule.v.intRange.start);
  419. } else {
  420. rule.v.intRange.end = (uint32_t)(OSUtils::jsonInt(e,0ULL) - rule.v.intRange.start);
  421. }
  422. rule.v.intRange.idx = (uint16_t)OSUtils::jsonInt(r["idx"],0ULL);
  423. rule.v.intRange.format = (OSUtils::jsonBool(r["little"],false)) ? 0x80 : 0x00;
  424. rule.v.intRange.format |= (uint8_t)((OSUtils::jsonInt(r["bits"],1ULL) - 1) & 63);
  425. }
  426. if (tag) {
  427. rule.v.tag.id = (uint32_t)(OSUtils::jsonInt(r["id"],0ULL) & 0xffffffffULL);
  428. rule.v.tag.value = (uint32_t)(OSUtils::jsonInt(r["value"],0ULL) & 0xffffffffULL);
  429. return true;
  430. }
  431. return false;
  432. }
  433. } // anonymous namespace
  434. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *ztPath,const char *dbPath, int listenPort, MQConfig *mqc) :
  435. _startTime(OSUtils::now()),
  436. _listenPort(listenPort),
  437. _node(node),
  438. _ztPath(ztPath),
  439. _path(dbPath),
  440. _sender((NetworkController::Sender *)0),
  441. _db(this),
  442. _mqc(mqc)
  443. {
  444. }
  445. EmbeddedNetworkController::~EmbeddedNetworkController()
  446. {
  447. std::lock_guard<std::mutex> l(_threads_l);
  448. _queue.stop();
  449. for(auto t=_threads.begin();t!=_threads.end();++t)
  450. t->join();
  451. }
  452. void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
  453. {
  454. char tmp[64];
  455. _signingId = signingId;
  456. _sender = sender;
  457. _signingIdAddressString = signingId.address().toString(tmp);
  458. #ifdef ZT_CONTROLLER_USE_LIBPQ
  459. if ((_path.length() > 9)&&(_path.substr(0,9) == "postgres:")) {
  460. _db.addDB(std::shared_ptr<DB>(new PostgreSQL(_signingId,_path.substr(9).c_str(), _listenPort, _mqc)));
  461. } else {
  462. #endif
  463. _db.addDB(std::shared_ptr<DB>(new FileDB(_path.c_str())));
  464. #ifdef ZT_CONTROLLER_USE_LIBPQ
  465. }
  466. #endif
  467. std::string lfJSON;
  468. OSUtils::readFile((_ztPath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lfJSON);
  469. if (lfJSON.length() > 0) {
  470. nlohmann::json lfConfig(OSUtils::jsonParse(lfJSON));
  471. nlohmann::json &settings = lfConfig["settings"];
  472. if (settings.is_object()) {
  473. nlohmann::json &controllerDb = settings["controllerDb"];
  474. if (controllerDb.is_object()) {
  475. std::string type = controllerDb["type"];
  476. if (type == "lf") {
  477. std::string lfOwner = controllerDb["owner"];
  478. std::string lfHost = controllerDb["host"];
  479. int lfPort = controllerDb["port"];
  480. bool storeOnlineState = controllerDb["storeOnlineState"];
  481. if ((lfOwner.length())&&(lfHost.length())&&(lfPort > 0)&&(lfPort < 65536)) {
  482. std::size_t pubHdrLoc = lfOwner.find("Public: ");
  483. if ((pubHdrLoc > 0)&&((pubHdrLoc + 8) < lfOwner.length())) {
  484. std::string lfOwnerPublic = lfOwner.substr(pubHdrLoc + 8);
  485. std::size_t pubHdrEnd = lfOwnerPublic.find_first_of("\n\r\t ");
  486. if (pubHdrEnd != std::string::npos) {
  487. lfOwnerPublic = lfOwnerPublic.substr(0,pubHdrEnd);
  488. _db.addDB(std::shared_ptr<DB>(new LFDB(_signingId,_path.c_str(),lfOwner.c_str(),lfOwnerPublic.c_str(),lfHost.c_str(),lfPort,storeOnlineState)));
  489. }
  490. }
  491. }
  492. }
  493. }
  494. }
  495. }
  496. _db.waitForReady();
  497. }
  498. void EmbeddedNetworkController::request(
  499. uint64_t nwid,
  500. const InetAddress &fromAddr,
  501. uint64_t requestPacketId,
  502. const Identity &identity,
  503. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  504. {
  505. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  506. return;
  507. _startThreads();
  508. _RQEntry *qe = new _RQEntry;
  509. qe->nwid = nwid;
  510. qe->requestPacketId = requestPacketId;
  511. qe->fromAddr = fromAddr;
  512. qe->identity = identity;
  513. qe->metaData = metaData;
  514. qe->type = _RQEntry::RQENTRY_TYPE_REQUEST;
  515. _queue.post(qe);
  516. }
  517. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  518. const std::vector<std::string> &path,
  519. const std::string &body,
  520. std::string &responseBody,
  521. std::string &responseContentType)
  522. {
  523. if ((path.size() > 0)&&(path[0] == "network")) {
  524. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  525. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  526. json network;
  527. if (!_db.get(nwid,network))
  528. return 404;
  529. if (path.size() >= 3) {
  530. if (path[2] == "member") {
  531. if (path.size() >= 4) {
  532. // Get member
  533. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  534. json member;
  535. if (!_db.get(nwid,network,address,member))
  536. return 404;
  537. responseBody = OSUtils::jsonDump(member);
  538. responseContentType = "application/json";
  539. } else {
  540. // List members and their revisions
  541. responseBody = "{";
  542. std::vector<json> members;
  543. if (_db.get(nwid,network,members)) {
  544. responseBody.reserve((members.size() + 2) * 32);
  545. std::string mid;
  546. for(auto member=members.begin();member!=members.end();++member) {
  547. mid = (*member)["id"];
  548. char tmp[128];
  549. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s\"%s\":%llu",(responseBody.length() > 1) ? "," : "",mid.c_str(),(unsigned long long)OSUtils::jsonInt((*member)["revision"],0));
  550. responseBody.append(tmp);
  551. }
  552. }
  553. responseBody.push_back('}');
  554. responseContentType = "application/json";
  555. }
  556. return 200;
  557. } // else 404
  558. } else {
  559. // Get network
  560. responseBody = OSUtils::jsonDump(network);
  561. responseContentType = "application/json";
  562. return 200;
  563. }
  564. } else if (path.size() == 1) {
  565. // List networks
  566. std::set<uint64_t> networkIds;
  567. _db.networks(networkIds);
  568. char tmp[64];
  569. responseBody = "[";
  570. responseBody.reserve((networkIds.size() + 1) * 24);
  571. for(std::set<uint64_t>::const_iterator i(networkIds.begin());i!=networkIds.end();++i) {
  572. if (responseBody.length() > 1)
  573. responseBody.push_back(',');
  574. OSUtils::ztsnprintf(tmp,sizeof(tmp),"\"%.16llx\"",(unsigned long long)*i);
  575. responseBody.append(tmp);
  576. }
  577. responseBody.push_back(']');
  578. responseContentType = "application/json";
  579. return 200;
  580. } // else 404
  581. } else {
  582. // Controller status
  583. char tmp[4096];
  584. const bool dbOk = _db.isReady();
  585. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now(),dbOk ? "true" : "false");
  586. responseBody = tmp;
  587. responseContentType = "application/json";
  588. return dbOk ? 200 : 503;
  589. }
  590. return 404;
  591. }
  592. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  593. const std::vector<std::string> &path,
  594. const std::string &body,
  595. std::string &responseBody,
  596. std::string &responseContentType)
  597. {
  598. if (path.empty())
  599. return 404;
  600. json b;
  601. try {
  602. b = OSUtils::jsonParse(body);
  603. if (!b.is_object()) {
  604. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  605. responseContentType = "application/json";
  606. return 400;
  607. }
  608. } catch ( ... ) {
  609. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  610. responseContentType = "application/json";
  611. return 400;
  612. }
  613. const int64_t now = OSUtils::now();
  614. if (path[0] == "network") {
  615. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  616. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  617. char nwids[24];
  618. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  619. if (path.size() >= 3) {
  620. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  621. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  622. char addrs[24];
  623. OSUtils::ztsnprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  624. json member,network;
  625. _db.get(nwid,network,address,member);
  626. DB::initMember(member);
  627. try {
  628. if (b.count("activeBridge")) member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"],false);
  629. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"],false);
  630. if (b.count("remoteTraceTarget")) {
  631. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  632. if (rtt.length() == 10) {
  633. member["remoteTraceTarget"] = rtt;
  634. } else {
  635. member["remoteTraceTarget"] = json();
  636. }
  637. }
  638. if (b.count("remoteTraceLevel")) member["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  639. if (b.count("authorized")) {
  640. const bool newAuth = OSUtils::jsonBool(b["authorized"],false);
  641. if (newAuth != OSUtils::jsonBool(member["authorized"],false)) {
  642. member["authorized"] = newAuth;
  643. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = now;
  644. if (newAuth) {
  645. member["lastAuthorizedCredentialType"] = "api";
  646. member["lastAuthorizedCredential"] = json();
  647. }
  648. }
  649. }
  650. if (b.count("ipAssignments")) {
  651. json &ipa = b["ipAssignments"];
  652. if (ipa.is_array()) {
  653. json mipa(json::array());
  654. for(unsigned long i=0;i<ipa.size();++i) {
  655. std::string ips = ipa[i];
  656. InetAddress ip(ips.c_str());
  657. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  658. char tmpip[64];
  659. mipa.push_back(ip.toIpString(tmpip));
  660. if (mipa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  661. break;
  662. }
  663. }
  664. member["ipAssignments"] = mipa;
  665. }
  666. }
  667. if (b.count("tags")) {
  668. json &tags = b["tags"];
  669. if (tags.is_array()) {
  670. std::map<uint64_t,uint64_t> mtags;
  671. for(unsigned long i=0;i<tags.size();++i) {
  672. json &tag = tags[i];
  673. if ((tag.is_array())&&(tag.size() == 2))
  674. mtags[OSUtils::jsonInt(tag[0],0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1],0ULL) & 0xffffffffULL;
  675. }
  676. json mtagsa = json::array();
  677. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  678. json ta = json::array();
  679. ta.push_back(t->first);
  680. ta.push_back(t->second);
  681. mtagsa.push_back(ta);
  682. if (mtagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  683. break;
  684. }
  685. member["tags"] = mtagsa;
  686. }
  687. }
  688. if (b.count("capabilities")) {
  689. json &capabilities = b["capabilities"];
  690. if (capabilities.is_array()) {
  691. json mcaps = json::array();
  692. for(unsigned long i=0;i<capabilities.size();++i) {
  693. mcaps.push_back(OSUtils::jsonInt(capabilities[i],0ULL));
  694. if (mcaps.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  695. break;
  696. }
  697. std::sort(mcaps.begin(),mcaps.end());
  698. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  699. member["capabilities"] = mcaps;
  700. }
  701. }
  702. } catch ( ... ) {
  703. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  704. responseContentType = "application/json";
  705. return 400;
  706. }
  707. member["id"] = addrs;
  708. member["address"] = addrs; // legacy
  709. member["nwid"] = nwids;
  710. DB::cleanMember(member);
  711. _db.save(member,true);
  712. responseBody = OSUtils::jsonDump(member);
  713. responseContentType = "application/json";
  714. return 200;
  715. } // else 404
  716. } else {
  717. // POST to network ID
  718. // Magic ID ending with ______ picks a random unused network ID
  719. if (path[1].substr(10) == "______") {
  720. nwid = 0;
  721. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  722. uint64_t nwidPostfix = 0;
  723. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  724. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  725. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  726. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  727. if (!_db.hasNetwork(tryNwid)) {
  728. nwid = tryNwid;
  729. break;
  730. }
  731. }
  732. if (!nwid)
  733. return 503;
  734. }
  735. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  736. json network;
  737. _db.get(nwid,network);
  738. DB::initNetwork(network);
  739. try {
  740. if (b.count("name")) network["name"] = OSUtils::jsonString(b["name"],"");
  741. if (b.count("private")) network["private"] = OSUtils::jsonBool(b["private"],true);
  742. if (b.count("enableBroadcast")) network["enableBroadcast"] = OSUtils::jsonBool(b["enableBroadcast"],false);
  743. if (b.count("multicastLimit")) network["multicastLimit"] = OSUtils::jsonInt(b["multicastLimit"],32ULL);
  744. 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);
  745. if (b.count("remoteTraceTarget")) {
  746. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  747. if (rtt.length() == 10) {
  748. network["remoteTraceTarget"] = rtt;
  749. } else {
  750. network["remoteTraceTarget"] = json();
  751. }
  752. }
  753. if (b.count("remoteTraceLevel")) network["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  754. if (b.count("v4AssignMode")) {
  755. json nv4m;
  756. json &v4m = b["v4AssignMode"];
  757. if (v4m.is_string()) { // backward compatibility
  758. nv4m["zt"] = (OSUtils::jsonString(v4m,"") == "zt");
  759. } else if (v4m.is_object()) {
  760. nv4m["zt"] = OSUtils::jsonBool(v4m["zt"],false);
  761. } else nv4m["zt"] = false;
  762. network["v4AssignMode"] = nv4m;
  763. }
  764. if (b.count("v6AssignMode")) {
  765. json nv6m;
  766. json &v6m = b["v6AssignMode"];
  767. if (!nv6m.is_object()) nv6m = json::object();
  768. if (v6m.is_string()) { // backward compatibility
  769. std::vector<std::string> v6ms(OSUtils::split(OSUtils::jsonString(v6m,"").c_str(),",","",""));
  770. std::sort(v6ms.begin(),v6ms.end());
  771. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  772. nv6m["rfc4193"] = false;
  773. nv6m["zt"] = false;
  774. nv6m["6plane"] = false;
  775. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  776. if (*i == "rfc4193")
  777. nv6m["rfc4193"] = true;
  778. else if (*i == "zt")
  779. nv6m["zt"] = true;
  780. else if (*i == "6plane")
  781. nv6m["6plane"] = true;
  782. }
  783. } else if (v6m.is_object()) {
  784. if (v6m.count("rfc4193")) nv6m["rfc4193"] = OSUtils::jsonBool(v6m["rfc4193"],false);
  785. if (v6m.count("zt")) nv6m["zt"] = OSUtils::jsonBool(v6m["zt"],false);
  786. if (v6m.count("6plane")) nv6m["6plane"] = OSUtils::jsonBool(v6m["6plane"],false);
  787. } else {
  788. nv6m["rfc4193"] = false;
  789. nv6m["zt"] = false;
  790. nv6m["6plane"] = false;
  791. }
  792. network["v6AssignMode"] = nv6m;
  793. }
  794. if (b.count("routes")) {
  795. json &rts = b["routes"];
  796. if (rts.is_array()) {
  797. json nrts = json::array();
  798. for(unsigned long i=0;i<rts.size();++i) {
  799. json &rt = rts[i];
  800. if (rt.is_object()) {
  801. json &target = rt["target"];
  802. json &via = rt["via"];
  803. if (target.is_string()) {
  804. InetAddress t(target.get<std::string>().c_str());
  805. InetAddress v;
  806. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  807. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  808. json tmp;
  809. char tmp2[64];
  810. tmp["target"] = t.toString(tmp2);
  811. if (v.ss_family == t.ss_family)
  812. tmp["via"] = v.toIpString(tmp2);
  813. else tmp["via"] = json();
  814. nrts.push_back(tmp);
  815. if (nrts.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  816. break;
  817. }
  818. }
  819. }
  820. }
  821. network["routes"] = nrts;
  822. }
  823. }
  824. if (b.count("ipAssignmentPools")) {
  825. json &ipp = b["ipAssignmentPools"];
  826. if (ipp.is_array()) {
  827. json nipp = json::array();
  828. for(unsigned long i=0;i<ipp.size();++i) {
  829. json &ip = ipp[i];
  830. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  831. InetAddress f(OSUtils::jsonString(ip["ipRangeStart"],"").c_str());
  832. InetAddress t(OSUtils::jsonString(ip["ipRangeEnd"],"").c_str());
  833. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  834. json tmp = json::object();
  835. char tmp2[64];
  836. tmp["ipRangeStart"] = f.toIpString(tmp2);
  837. tmp["ipRangeEnd"] = t.toIpString(tmp2);
  838. nipp.push_back(tmp);
  839. if (nipp.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  840. break;
  841. }
  842. }
  843. }
  844. network["ipAssignmentPools"] = nipp;
  845. }
  846. }
  847. if (b.count("rules")) {
  848. json &rules = b["rules"];
  849. if (rules.is_array()) {
  850. json nrules = json::array();
  851. for(unsigned long i=0;i<rules.size();++i) {
  852. json &rule = rules[i];
  853. if (rule.is_object()) {
  854. ZT_VirtualNetworkRule ztr;
  855. if (_parseRule(rule,ztr)) {
  856. nrules.push_back(_renderRule(ztr));
  857. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  858. break;
  859. }
  860. }
  861. }
  862. network["rules"] = nrules;
  863. }
  864. }
  865. if (b.count("authTokens")) {
  866. json &authTokens = b["authTokens"];
  867. if (authTokens.is_object()) {
  868. json nat;
  869. for(json::iterator t(authTokens.begin());t!=authTokens.end();++t) {
  870. if ((t.value().is_number())&&(t.value() >= 0))
  871. nat[t.key()] = t.value();
  872. }
  873. network["authTokens"] = nat;
  874. } else {
  875. network["authTokens"] = {{}};
  876. }
  877. }
  878. if (b.count("capabilities")) {
  879. json &capabilities = b["capabilities"];
  880. if (capabilities.is_array()) {
  881. std::map< uint64_t,json > ncaps;
  882. for(unsigned long i=0;i<capabilities.size();++i) {
  883. json &cap = capabilities[i];
  884. if (cap.is_object()) {
  885. json ncap = json::object();
  886. const uint64_t capId = OSUtils::jsonInt(cap["id"],0ULL);
  887. ncap["id"] = capId;
  888. ncap["default"] = OSUtils::jsonBool(cap["default"],false);
  889. json &rules = cap["rules"];
  890. json nrules = json::array();
  891. if (rules.is_array()) {
  892. for(unsigned long i=0;i<rules.size();++i) {
  893. json &rule = rules[i];
  894. if (rule.is_object()) {
  895. ZT_VirtualNetworkRule ztr;
  896. if (_parseRule(rule,ztr)) {
  897. nrules.push_back(_renderRule(ztr));
  898. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  899. break;
  900. }
  901. }
  902. }
  903. }
  904. ncap["rules"] = nrules;
  905. ncaps[capId] = ncap;
  906. }
  907. }
  908. json ncapsa = json::array();
  909. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c) {
  910. ncapsa.push_back(c->second);
  911. if (ncapsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  912. break;
  913. }
  914. network["capabilities"] = ncapsa;
  915. }
  916. }
  917. if (b.count("tags")) {
  918. json &tags = b["tags"];
  919. if (tags.is_array()) {
  920. std::map< uint64_t,json > ntags;
  921. for(unsigned long i=0;i<tags.size();++i) {
  922. json &tag = tags[i];
  923. if (tag.is_object()) {
  924. json ntag = json::object();
  925. const uint64_t tagId = OSUtils::jsonInt(tag["id"],0ULL);
  926. ntag["id"] = tagId;
  927. json &dfl = tag["default"];
  928. if (dfl.is_null())
  929. ntag["default"] = dfl;
  930. else ntag["default"] = OSUtils::jsonInt(dfl,0ULL);
  931. ntags[tagId] = ntag;
  932. }
  933. }
  934. json ntagsa = json::array();
  935. for(std::map< uint64_t,json >::iterator t(ntags.begin());t!=ntags.end();++t) {
  936. ntagsa.push_back(t->second);
  937. if (ntagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  938. break;
  939. }
  940. network["tags"] = ntagsa;
  941. }
  942. }
  943. } catch ( ... ) {
  944. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  945. responseContentType = "application/json";
  946. return 400;
  947. }
  948. network["id"] = nwids;
  949. network["nwid"] = nwids; // legacy
  950. DB::cleanNetwork(network);
  951. _db.save(network,true);
  952. responseBody = OSUtils::jsonDump(network);
  953. responseContentType = "application/json";
  954. return 200;
  955. } // else 404
  956. } // else 404
  957. }
  958. return 404;
  959. }
  960. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  961. const std::vector<std::string> &path,
  962. const std::string &body,
  963. std::string &responseBody,
  964. std::string &responseContentType)
  965. {
  966. if (path.empty())
  967. return 404;
  968. if (path[0] == "network") {
  969. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  970. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  971. if (path.size() >= 3) {
  972. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  973. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  974. json network,member;
  975. _db.get(nwid,network,address,member);
  976. _db.eraseMember(nwid, address);
  977. {
  978. std::lock_guard<std::mutex> l(_memberStatus_l);
  979. _memberStatus.erase(_MemberStatusKey(nwid,address));
  980. }
  981. if (!member.size())
  982. return 404;
  983. responseBody = OSUtils::jsonDump(member);
  984. responseContentType = "application/json";
  985. return 200;
  986. }
  987. } else {
  988. json network;
  989. _db.get(nwid,network);
  990. _db.eraseNetwork(nwid);
  991. {
  992. std::lock_guard<std::mutex> l(_memberStatus_l);
  993. for(auto i=_memberStatus.begin();i!=_memberStatus.end();) {
  994. if (i->first.networkId == nwid)
  995. _memberStatus.erase(i++);
  996. else ++i;
  997. }
  998. }
  999. if (!network.size())
  1000. return 404;
  1001. responseBody = OSUtils::jsonDump(network);
  1002. responseContentType = "application/json";
  1003. return 200;
  1004. }
  1005. } // else 404
  1006. } // else 404
  1007. return 404;
  1008. }
  1009. void EmbeddedNetworkController::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
  1010. {
  1011. // Send an update to all members of the network that are online
  1012. const int64_t now = OSUtils::now();
  1013. std::lock_guard<std::mutex> l(_memberStatus_l);
  1014. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1015. if ((i->first.networkId == networkId)&&(i->second.online(now))&&(i->second.lastRequestMetaData))
  1016. request(networkId,InetAddress(),0,i->second.identity,i->second.lastRequestMetaData);
  1017. }
  1018. }
  1019. void EmbeddedNetworkController::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
  1020. {
  1021. // Push update to member if online
  1022. try {
  1023. std::lock_guard<std::mutex> l(_memberStatus_l);
  1024. _MemberStatus &ms = _memberStatus[_MemberStatusKey(networkId,memberId)];
  1025. if ((ms.online(OSUtils::now()))&&(ms.lastRequestMetaData))
  1026. request(networkId,InetAddress(),0,ms.identity,ms.lastRequestMetaData);
  1027. } catch ( ... ) {}
  1028. }
  1029. void EmbeddedNetworkController::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
  1030. {
  1031. const int64_t now = OSUtils::now();
  1032. Revocation rev((uint32_t)Utils::random(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM);
  1033. rev.sign(_signingId);
  1034. {
  1035. std::lock_guard<std::mutex> l(_memberStatus_l);
  1036. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1037. if ((i->first.networkId == networkId)&&(i->second.online(now)))
  1038. _node->ncSendRevocation(Address(i->first.nodeId),rev);
  1039. }
  1040. }
  1041. }
  1042. void EmbeddedNetworkController::_request(
  1043. uint64_t nwid,
  1044. const InetAddress &fromAddr,
  1045. uint64_t requestPacketId,
  1046. const Identity &identity,
  1047. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  1048. {
  1049. char nwids[24];
  1050. DB::NetworkSummaryInfo ns;
  1051. json network,member;
  1052. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  1053. return;
  1054. const int64_t now = OSUtils::now();
  1055. if (requestPacketId) {
  1056. std::lock_guard<std::mutex> l(_memberStatus_l);
  1057. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1058. if ((now - ms.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  1059. return;
  1060. ms.lastRequestTime = now;
  1061. }
  1062. _db.nodeIsOnline(nwid,identity.address().toInt(),fromAddr);
  1063. Utils::hex(nwid,nwids);
  1064. _db.get(nwid,network,identity.address().toInt(),member,ns);
  1065. if ((!network.is_object())||(network.size() == 0)) {
  1066. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND);
  1067. return;
  1068. }
  1069. const bool newMember = ((!member.is_object())||(member.size() == 0));
  1070. DB::initMember(member);
  1071. {
  1072. const std::string haveIdStr(OSUtils::jsonString(member["identity"],""));
  1073. if (haveIdStr.length() > 0) {
  1074. // If we already know this member's identity perform a full compare. This prevents
  1075. // a "collision" from being able to auth onto our network in place of an already
  1076. // known member.
  1077. try {
  1078. if (Identity(haveIdStr.c_str()) != identity) {
  1079. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1080. return;
  1081. }
  1082. } catch ( ... ) {
  1083. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1084. return;
  1085. }
  1086. } else {
  1087. // If we do not yet know this member's identity, learn it.
  1088. char idtmp[1024];
  1089. member["identity"] = identity.toString(false,idtmp);
  1090. }
  1091. }
  1092. // These are always the same, but make sure they are set
  1093. {
  1094. char tmpid[128];
  1095. const std::string addrs(identity.address().toString(tmpid));
  1096. member["id"] = addrs;
  1097. member["address"] = addrs;
  1098. member["nwid"] = nwids;
  1099. }
  1100. // Determine whether and how member is authorized
  1101. bool authorized = false;
  1102. bool autoAuthorized = false;
  1103. json autoAuthCredentialType,autoAuthCredential;
  1104. if (OSUtils::jsonBool(member["authorized"],false)) {
  1105. authorized = true;
  1106. } else if (!OSUtils::jsonBool(network["private"],true)) {
  1107. authorized = true;
  1108. autoAuthorized = true;
  1109. autoAuthCredentialType = "public";
  1110. } else {
  1111. char presentedAuth[512];
  1112. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  1113. presentedAuth[511] = (char)0; // sanity check
  1114. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  1115. const char *const presentedToken = presentedAuth + 6;
  1116. json authTokens(network["authTokens"]);
  1117. json &tokenExpires = authTokens[presentedToken];
  1118. if (tokenExpires.is_number()) {
  1119. if ((tokenExpires == 0)||(tokenExpires > now)) {
  1120. authorized = true;
  1121. autoAuthorized = true;
  1122. autoAuthCredentialType = "token";
  1123. autoAuthCredential = presentedToken;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. }
  1129. // If we auto-authorized, update member record
  1130. if ((autoAuthorized)&&(authorized)) {
  1131. member["authorized"] = true;
  1132. member["lastAuthorizedTime"] = now;
  1133. member["lastAuthorizedCredentialType"] = autoAuthCredentialType;
  1134. member["lastAuthorizedCredential"] = autoAuthCredential;
  1135. }
  1136. if (authorized) {
  1137. // Update version info and meta-data if authorized and if this is a genuine request
  1138. if (requestPacketId) {
  1139. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1140. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1141. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1142. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  1143. member["vMajor"] = vMajor;
  1144. member["vMinor"] = vMinor;
  1145. member["vRev"] = vRev;
  1146. member["vProto"] = vProto;
  1147. {
  1148. std::lock_guard<std::mutex> l(_memberStatus_l);
  1149. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1150. ms.vMajor = (int)vMajor;
  1151. ms.vMinor = (int)vMinor;
  1152. ms.vRev = (int)vRev;
  1153. ms.vProto = (int)vProto;
  1154. ms.lastRequestMetaData = metaData;
  1155. ms.identity = identity;
  1156. }
  1157. }
  1158. } else {
  1159. // If they are not authorized, STOP!
  1160. DB::cleanMember(member);
  1161. _db.save(member,true);
  1162. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  1163. return;
  1164. }
  1165. // -------------------------------------------------------------------------
  1166. // If we made it this far, they are authorized.
  1167. // -------------------------------------------------------------------------
  1168. int64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  1169. if (now > ns.mostRecentDeauthTime) {
  1170. // If we recently de-authorized a member, shrink credential TTL/max delta to
  1171. // be below the threshold required to exclude it. Cap this to a min/max to
  1172. // prevent jitter or absurdly large values.
  1173. const uint64_t deauthWindow = now - ns.mostRecentDeauthTime;
  1174. if (deauthWindow < ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA) {
  1175. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  1176. } else if (deauthWindow < (ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA + 5000ULL)) {
  1177. credentialtmd = deauthWindow - 5000ULL;
  1178. }
  1179. }
  1180. std::unique_ptr<NetworkConfig> nc(new NetworkConfig());
  1181. nc->networkId = nwid;
  1182. nc->type = OSUtils::jsonBool(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1183. nc->timestamp = now;
  1184. nc->credentialTimeMaxDelta = credentialtmd;
  1185. nc->revision = OSUtils::jsonInt(network["revision"],0ULL);
  1186. nc->issuedTo = identity.address();
  1187. if (OSUtils::jsonBool(network["enableBroadcast"],true)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1188. Utils::scopy(nc->name,sizeof(nc->name),OSUtils::jsonString(network["name"],"").c_str());
  1189. 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);
  1190. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"],32ULL);
  1191. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab)
  1192. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1193. json &v4AssignMode = network["v4AssignMode"];
  1194. json &v6AssignMode = network["v6AssignMode"];
  1195. json &ipAssignmentPools = network["ipAssignmentPools"];
  1196. json &routes = network["routes"];
  1197. json &rules = network["rules"];
  1198. json &capabilities = network["capabilities"];
  1199. json &tags = network["tags"];
  1200. json &memberCapabilities = member["capabilities"];
  1201. json &memberTags = member["tags"];
  1202. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1203. // Old versions with no rules engine support get an allow everything rule.
  1204. // Since rules are enforced bidirectionally, newer versions *will* still
  1205. // enforce rules on the inbound side.
  1206. nc->ruleCount = 1;
  1207. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1208. } else {
  1209. if (rules.is_array()) {
  1210. for(unsigned long i=0;i<rules.size();++i) {
  1211. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1212. break;
  1213. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1214. ++nc->ruleCount;
  1215. }
  1216. }
  1217. std::map< uint64_t,json * > capsById;
  1218. if (!memberCapabilities.is_array())
  1219. memberCapabilities = json::array();
  1220. if (capabilities.is_array()) {
  1221. for(unsigned long i=0;i<capabilities.size();++i) {
  1222. json &cap = capabilities[i];
  1223. if (cap.is_object()) {
  1224. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1225. capsById[id] = &cap;
  1226. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1227. bool have = false;
  1228. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1229. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1230. have = true;
  1231. break;
  1232. }
  1233. }
  1234. if (!have)
  1235. memberCapabilities.push_back(id);
  1236. }
  1237. }
  1238. }
  1239. }
  1240. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1241. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1242. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1243. if (ctmp != capsById.end()) {
  1244. json *cap = ctmp->second;
  1245. if ((cap)&&(cap->is_object())&&(cap->size() > 0)) {
  1246. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1247. unsigned int caprc = 0;
  1248. json &caprj = (*cap)["rules"];
  1249. if ((caprj.is_array())&&(caprj.size() > 0)) {
  1250. for(unsigned long j=0;j<caprj.size();++j) {
  1251. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1252. break;
  1253. if (_parseRule(caprj[j],capr[caprc]))
  1254. ++caprc;
  1255. }
  1256. }
  1257. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1258. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1259. ++nc->capabilityCount;
  1260. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1261. break;
  1262. }
  1263. }
  1264. }
  1265. std::map< uint32_t,uint32_t > memberTagsById;
  1266. if (memberTags.is_array()) {
  1267. for(unsigned long i=0;i<memberTags.size();++i) {
  1268. json &t = memberTags[i];
  1269. if ((t.is_array())&&(t.size() == 2))
  1270. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1271. }
  1272. }
  1273. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1274. for(unsigned long i=0;i<tags.size();++i) {
  1275. json &t = tags[i];
  1276. if (t.is_object()) {
  1277. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1278. json &dfl = t["default"];
  1279. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1280. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1281. json mt = json::array();
  1282. mt.push_back(id);
  1283. mt.push_back(dfl);
  1284. memberTags.push_back(mt); // add default to member tags if not present
  1285. }
  1286. }
  1287. }
  1288. }
  1289. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1290. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1291. break;
  1292. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1293. if (nc->tags[nc->tagCount].sign(_signingId))
  1294. ++nc->tagCount;
  1295. }
  1296. }
  1297. if (routes.is_array()) {
  1298. for(unsigned long i=0;i<routes.size();++i) {
  1299. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1300. break;
  1301. json &route = routes[i];
  1302. json &target = route["target"];
  1303. json &via = route["via"];
  1304. if (target.is_string()) {
  1305. const InetAddress t(target.get<std::string>().c_str());
  1306. InetAddress v;
  1307. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  1308. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1309. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1310. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1311. if (v.ss_family == t.ss_family)
  1312. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1313. ++nc->routeCount;
  1314. }
  1315. }
  1316. }
  1317. }
  1318. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1319. // Set IPv6 static IPs based on NDP emulated schemes if enabled.
  1320. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1321. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1322. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1323. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1324. }
  1325. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1326. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1327. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1328. }
  1329. }
  1330. bool haveManagedIpv4AutoAssignment = false;
  1331. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1332. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1333. if (ipAssignments.is_array()) {
  1334. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1335. if (ipAssignments[i].is_string()) {
  1336. const std::string ips = ipAssignments[i];
  1337. InetAddress ip(ips.c_str());
  1338. int routedNetmaskBits = -1;
  1339. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1340. if (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1341. const int nb = (int)(reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits());
  1342. if (nb > routedNetmaskBits)
  1343. routedNetmaskBits = nb;
  1344. }
  1345. }
  1346. if (routedNetmaskBits >= 0) {
  1347. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1348. ip.setPort(routedNetmaskBits);
  1349. nc->staticIps[nc->staticIpCount++] = ip;
  1350. }
  1351. if (ip.ss_family == AF_INET)
  1352. haveManagedIpv4AutoAssignment = true;
  1353. else if (ip.ss_family == AF_INET6)
  1354. haveManagedIpv6AutoAssignment = true;
  1355. }
  1356. }
  1357. }
  1358. } else {
  1359. ipAssignments = json::array();
  1360. }
  1361. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1362. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1363. json &pool = ipAssignmentPools[p];
  1364. if (pool.is_object()) {
  1365. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1366. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1367. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1368. uint64_t s[2],e[2],x[2],xx[2];
  1369. memcpy(s,ipRangeStart.rawIpData(),16);
  1370. memcpy(e,ipRangeEnd.rawIpData(),16);
  1371. s[0] = Utils::ntoh(s[0]);
  1372. s[1] = Utils::ntoh(s[1]);
  1373. e[0] = Utils::ntoh(e[0]);
  1374. e[1] = Utils::ntoh(e[1]);
  1375. x[0] = s[0];
  1376. x[1] = s[1];
  1377. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1378. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1379. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1380. xx[0] = Utils::hton(x[0]);
  1381. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1382. } else {
  1383. // 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
  1384. Utils::getSecureRandom((void *)xx,16);
  1385. if ((e[0] > s[0]))
  1386. xx[0] %= (e[0] - s[0]);
  1387. else xx[0] = 0;
  1388. if ((e[1] > s[1]))
  1389. xx[1] %= (e[1] - s[1]);
  1390. else xx[1] = 0;
  1391. xx[0] = Utils::hton(x[0] + xx[0]);
  1392. xx[1] = Utils::hton(x[1] + xx[1]);
  1393. }
  1394. InetAddress ip6((const void *)xx,16,0);
  1395. // Check if this IP is within a local-to-Ethernet routed network
  1396. int routedNetmaskBits = 0;
  1397. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1398. 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)) )
  1399. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1400. }
  1401. // If it's routed, then try to claim and assign it and if successful end loop
  1402. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1403. char tmpip[64];
  1404. const std::string ipStr(ip6.toIpString(tmpip));
  1405. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1406. ipAssignments.push_back(ipStr);
  1407. member["ipAssignments"] = ipAssignments;
  1408. ip6.setPort((unsigned int)routedNetmaskBits);
  1409. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1410. nc->staticIps[nc->staticIpCount++] = ip6;
  1411. haveManagedIpv6AutoAssignment = true;
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. }
  1417. }
  1418. }
  1419. }
  1420. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1421. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1422. json &pool = ipAssignmentPools[p];
  1423. if (pool.is_object()) {
  1424. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1425. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1426. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1427. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1428. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1429. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1430. continue;
  1431. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1432. // Start with the LSB of the member's address
  1433. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1434. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1435. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1436. ++ipTrialCounter;
  1437. if ((ip & 0x000000ff) == 0x000000ff) {
  1438. continue; // don't allow addresses that end in .255
  1439. }
  1440. // Check if this IP is within a local-to-Ethernet routed network
  1441. int routedNetmaskBits = -1;
  1442. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1443. if (nc->routes[rk].target.ss_family == AF_INET) {
  1444. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1445. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1446. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1447. routedNetmaskBits = targetBits;
  1448. break;
  1449. }
  1450. }
  1451. }
  1452. // If it's routed, then try to claim and assign it and if successful end loop
  1453. const InetAddress ip4(Utils::hton(ip),0);
  1454. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1455. char tmpip[64];
  1456. const std::string ipStr(ip4.toIpString(tmpip));
  1457. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1458. ipAssignments.push_back(ipStr);
  1459. member["ipAssignments"] = ipAssignments;
  1460. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1461. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1462. v4ip->sin_family = AF_INET;
  1463. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1464. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1465. }
  1466. haveManagedIpv4AutoAssignment = true;
  1467. break;
  1468. }
  1469. }
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. // Issue a certificate of ownership for all static IPs
  1476. if (nc->staticIpCount) {
  1477. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1478. for(unsigned int i=0;i<nc->staticIpCount;++i)
  1479. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1480. nc->certificatesOfOwnership[0].sign(_signingId);
  1481. nc->certificateOfOwnershipCount = 1;
  1482. }
  1483. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  1484. if (com.sign(_signingId)) {
  1485. nc->com = com;
  1486. } else {
  1487. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR);
  1488. return;
  1489. }
  1490. DB::cleanMember(member);
  1491. _db.save(member,true);
  1492. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),false);
  1493. }
  1494. void EmbeddedNetworkController::_startThreads()
  1495. {
  1496. std::lock_guard<std::mutex> l(_threads_l);
  1497. if (!_threads.empty())
  1498. return;
  1499. const long hwc = std::max((long)std::thread::hardware_concurrency(),(long)1);
  1500. for(long t=0;t<hwc;++t) {
  1501. _threads.emplace_back([this]() {
  1502. for(;;) {
  1503. _RQEntry *qe = (_RQEntry *)0;
  1504. if (!_queue.get(qe))
  1505. break;
  1506. try {
  1507. if (qe) {
  1508. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1509. delete qe;
  1510. }
  1511. } catch (std::exception &e) {
  1512. fprintf(stderr,"ERROR: exception in controller request handling thread: %s" ZT_EOL_S,e.what());
  1513. } catch ( ... ) {
  1514. fprintf(stderr,"ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  1515. }
  1516. }
  1517. });
  1518. }
  1519. }
  1520. } // namespace ZeroTier