EmbeddedNetworkController.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdint.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <time.h>
  23. #include <sys/time.h>
  24. #include <sys/types.h>
  25. #include <algorithm>
  26. #include <utility>
  27. #include <stdexcept>
  28. #include <set>
  29. #include <map>
  30. #include "../include/ZeroTierOne.h"
  31. #include "../node/Constants.hpp"
  32. #include "EmbeddedNetworkController.hpp"
  33. #include "../node/Node.hpp"
  34. #include "../node/Utils.hpp"
  35. #include "../node/CertificateOfMembership.hpp"
  36. #include "../node/NetworkConfig.hpp"
  37. #include "../node/Dictionary.hpp"
  38. #include "../node/InetAddress.hpp"
  39. #include "../node/MAC.hpp"
  40. #include "../node/Address.hpp"
  41. using json = nlohmann::json;
  42. // API version reported via JSON control plane
  43. #define ZT_NETCONF_CONTROLLER_API_VERSION 3
  44. // Number of requests to remember in member history
  45. #define ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH 24
  46. // Min duration between requests for an address/nwid combo to prevent floods
  47. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  48. // Nodes are considered active if they've queried in less than this long
  49. #define ZT_NETCONF_NODE_ACTIVE_THRESHOLD ((ZT_NETWORK_AUTOCONF_DELAY * 2) + 5000)
  50. namespace ZeroTier {
  51. // JSON blob I/O
  52. static json _readJson(const std::string &path)
  53. {
  54. std::string buf;
  55. if (OSUtils::readFile(path.c_str(),buf)) {
  56. try {
  57. return json::parse(buf);
  58. } catch ( ... ) {}
  59. }
  60. return json::object();
  61. }
  62. static bool _writeJson(const std::string &path,const json &obj)
  63. {
  64. return OSUtils::writeFile(path.c_str(),obj.dump(2));
  65. }
  66. // Get JSON values as unsigned integers, strings, or booleans, doing type conversion if possible
  67. static uint64_t _jI(const json &jv,const uint64_t dfl)
  68. {
  69. if (jv.is_number()) {
  70. return (uint64_t)jv;
  71. } else if (jv.is_string()) {
  72. std::string s = jv;
  73. return Utils::strToU64(s.c_str());
  74. } else if (jv.is_boolean()) {
  75. return ((bool)jv ? 1ULL : 0ULL);
  76. }
  77. return dfl;
  78. }
  79. static bool _jB(const json &jv,const bool dfl)
  80. {
  81. if (jv.is_boolean()) {
  82. return (bool)jv;
  83. } else if (jv.is_number()) {
  84. return ((uint64_t)jv > 0ULL);
  85. } else if (jv.is_string()) {
  86. std::string s = jv;
  87. if (s.length() > 0) {
  88. switch(s[0]) {
  89. case 't':
  90. case 'T':
  91. case '1':
  92. return true;
  93. }
  94. }
  95. return false;
  96. }
  97. return dfl;
  98. }
  99. static std::string _jS(const json &jv,const char *dfl)
  100. {
  101. if (jv.is_string()) {
  102. return jv;
  103. } else if (jv.is_number()) {
  104. char tmp[64];
  105. Utils::snprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  106. return tmp;
  107. } else if (jv.is_boolean()) {
  108. return ((bool)jv ? std::string("1") : std::string("0"));
  109. }
  110. return std::string((dfl) ? dfl : "");
  111. }
  112. static json _renderRule(ZT_VirtualNetworkRule &rule)
  113. {
  114. char tmp[128];
  115. json r = json::object();
  116. switch((rule.t) & 0x7f) {
  117. case ZT_NETWORK_RULE_ACTION_DROP:
  118. r["type"] = "ACTION_DROP";
  119. break;
  120. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  121. r["type"] = "ACTION_ACCEPT";
  122. break;
  123. case ZT_NETWORK_RULE_ACTION_TEE:
  124. r["type"] = "ACTION_TEE";
  125. r["address"] = Address(rule.v.fwd.address).toString();
  126. r["flags"] = (unsigned int)rule.v.fwd.flags;
  127. r["length"] = (unsigned int)rule.v.fwd.length;
  128. break;
  129. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  130. r["type"] = "ACTION_REDIRECT";
  131. r["address"] = Address(rule.v.fwd.address).toString();
  132. r["flags"] = (unsigned int)rule.v.fwd.flags;
  133. r["length"] = (unsigned int)rule.v.fwd.length;
  134. break;
  135. case ZT_NETWORK_RULE_ACTION_DEBUG_LOG:
  136. r["type"] = "ACTION_DEBUG_LOG";
  137. break;
  138. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  139. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  140. r["not"] = ((rule.t & 0x80) != 0);
  141. r["zt"] = Address(rule.v.zt).toString();
  142. break;
  143. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  144. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  145. r["not"] = ((rule.t & 0x80) != 0);
  146. r["zt"] = Address(rule.v.zt).toString();
  147. break;
  148. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  149. r["type"] = "MATCH_VLAN_ID";
  150. r["not"] = ((rule.t & 0x80) != 0);
  151. r["vlanId"] = (unsigned int)rule.v.vlanId;
  152. break;
  153. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  154. r["type"] = "MATCH_VLAN_PCP";
  155. r["not"] = ((rule.t & 0x80) != 0);
  156. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  157. break;
  158. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  159. r["type"] = "MATCH_VLAN_DEI";
  160. r["not"] = ((rule.t & 0x80) != 0);
  161. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  162. break;
  163. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  164. r["type"] = "MATCH_ETHERTYPE";
  165. r["not"] = ((rule.t & 0x80) != 0);
  166. r["etherType"] = (unsigned int)rule.v.etherType;
  167. break;
  168. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  169. r["type"] = "MATCH_MAC_SOURCE";
  170. r["not"] = ((rule.t & 0x80) != 0);
  171. Utils::snprintf(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]);
  172. r["mac"] = tmp;
  173. break;
  174. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  175. r["type"] = "MATCH_MAC_DEST";
  176. r["not"] = ((rule.t & 0x80) != 0);
  177. Utils::snprintf(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]);
  178. r["mac"] = tmp;
  179. break;
  180. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  181. r["type"] = "MATCH_IPV4_SOURCE";
  182. r["not"] = ((rule.t & 0x80) != 0);
  183. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  184. break;
  185. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  186. r["type"] = "MATCH_IPV4_DEST";
  187. r["not"] = ((rule.t & 0x80) != 0);
  188. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  189. break;
  190. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  191. r["type"] = "MATCH_IPV6_SOURCE";
  192. r["not"] = ((rule.t & 0x80) != 0);
  193. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  194. break;
  195. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  196. r["type"] = "MATCH_IPV6_DEST";
  197. r["not"] = ((rule.t & 0x80) != 0);
  198. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  199. break;
  200. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  201. r["type"] = "MATCH_IP_TOS";
  202. r["not"] = ((rule.t & 0x80) != 0);
  203. r["ipTos"] = (unsigned int)rule.v.ipTos;
  204. break;
  205. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  206. r["type"] = "MATCH_IP_PROTOCOL";
  207. r["not"] = ((rule.t & 0x80) != 0);
  208. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  209. break;
  210. case ZT_NETWORK_RULE_MATCH_ICMP:
  211. r["type"] = "MATCH_ICMP";
  212. r["not"] = ((rule.t & 0x80) != 0);
  213. r["type"] = (unsigned int)rule.v.icmp.type;
  214. if ((rule.v.icmp.flags & 0x01) != 0)
  215. r["code"] = (unsigned int)rule.v.icmp.code;
  216. else r["code"] = json();
  217. break;
  218. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  219. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  220. r["not"] = ((rule.t & 0x80) != 0);
  221. r["start"] = (unsigned int)rule.v.port[0];
  222. r["end"] = (unsigned int)rule.v.port[1];
  223. break;
  224. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  225. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  226. r["not"] = ((rule.t & 0x80) != 0);
  227. r["start"] = (unsigned int)rule.v.port[0];
  228. r["end"] = (unsigned int)rule.v.port[1];
  229. break;
  230. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  231. r["type"] = "MATCH_CHARACTERISTICS";
  232. r["not"] = ((rule.t & 0x80) != 0);
  233. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics[0]);
  234. r["mask"] = tmp;
  235. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics[1]);
  236. r["value"] = tmp;
  237. break;
  238. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  239. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  240. r["not"] = ((rule.t & 0x80) != 0);
  241. r["start"] = (unsigned int)rule.v.frameSize[0];
  242. r["end"] = (unsigned int)rule.v.frameSize[1];
  243. break;
  244. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  245. r["type"] = "MATCH_TAGS_DIFFERENCE";
  246. r["not"] = ((rule.t & 0x80) != 0);
  247. r["id"] = rule.v.tag.id;
  248. r["value"] = rule.v.tag.value;
  249. break;
  250. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  251. r["type"] = "MATCH_TAGS_BITWISE_AND";
  252. r["not"] = ((rule.t & 0x80) != 0);
  253. r["id"] = rule.v.tag.id;
  254. r["value"] = rule.v.tag.value;
  255. break;
  256. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  257. r["type"] = "MATCH_TAGS_BITWISE_OR";
  258. r["not"] = ((rule.t & 0x80) != 0);
  259. r["id"] = rule.v.tag.id;
  260. r["value"] = rule.v.tag.value;
  261. break;
  262. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  263. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  264. r["not"] = ((rule.t & 0x80) != 0);
  265. r["id"] = rule.v.tag.id;
  266. r["value"] = rule.v.tag.value;
  267. break;
  268. }
  269. return r;
  270. }
  271. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  272. {
  273. if (!r.is_object())
  274. return false;
  275. const std::string t(_jS(r["type"],""));
  276. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  277. if (_jB(r["not"],false))
  278. rule.t = 0x80;
  279. else rule.t = 0x00;
  280. if (t == "ACTION_DROP") {
  281. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  282. return true;
  283. } else if (t == "ACTION_ACCEPT") {
  284. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  285. return true;
  286. } else if (t == "ACTION_TEE") {
  287. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  288. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["address"],"0").c_str()) & 0xffffffffffULL;
  289. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  290. rule.v.fwd.length = (uint16_t)(_jI(r["length"],0ULL) & 0xffffULL);
  291. return true;
  292. } else if (t == "ACTION_REDIRECT") {
  293. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  294. rule.v.fwd.address = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  295. rule.v.fwd.flags = (uint32_t)(_jI(r["flags"],0ULL) & 0xffffffffULL);
  296. rule.v.fwd.length = (uint16_t)(_jI(r["length"],0ULL) & 0xffffULL);
  297. return true;
  298. } else if (t == "ACTION_DEBUG_LOG") {
  299. rule.t |= ZT_NETWORK_RULE_ACTION_DEBUG_LOG;
  300. return true;
  301. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  302. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  303. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  304. return true;
  305. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  306. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  307. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  308. return true;
  309. } else if (t == "MATCH_VLAN_ID") {
  310. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  311. rule.v.vlanId = (uint16_t)(_jI(r["vlanId"],0ULL) & 0xffffULL);
  312. return true;
  313. } else if (t == "MATCH_VLAN_PCP") {
  314. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  315. rule.v.vlanPcp = (uint8_t)(_jI(r["vlanPcp"],0ULL) & 0xffULL);
  316. return true;
  317. } else if (t == "MATCH_VLAN_DEI") {
  318. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  319. rule.v.vlanDei = (uint8_t)(_jI(r["vlanDei"],0ULL) & 0xffULL);
  320. return true;
  321. } else if (t == "MATCH_ETHERTYPE") {
  322. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  323. rule.v.etherType = (uint16_t)(_jI(r["etherType"],0ULL) & 0xffffULL);
  324. return true;
  325. } else if (t == "MATCH_MAC_SOURCE") {
  326. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  327. const std::string mac(_jS(r["mac"],"0"));
  328. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  329. return true;
  330. } else if (t == "MATCH_MAC_DEST") {
  331. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  332. const std::string mac(_jS(r["mac"],"0"));
  333. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  334. return true;
  335. } else if (t == "MATCH_IPV4_SOURCE") {
  336. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  337. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  338. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  339. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  340. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  341. return true;
  342. } else if (t == "MATCH_IPV4_DEST") {
  343. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  344. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  345. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  346. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  347. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  348. return true;
  349. } else if (t == "MATCH_IPV6_SOURCE") {
  350. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  351. InetAddress ip(_jS(r["ip"],"::0"));
  352. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  353. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  354. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  355. return true;
  356. } else if (t == "MATCH_IPV6_DEST") {
  357. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  358. InetAddress ip(_jS(r["ip"],"::0"));
  359. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  360. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  361. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  362. return true;
  363. } else if (t == "MATCH_IP_TOS") {
  364. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  365. rule.v.ipTos = (uint8_t)(_jI(r["ipTos"],0ULL) & 0xffULL);
  366. return true;
  367. } else if (t == "MATCH_IP_PROTOCOL") {
  368. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  369. rule.v.ipProtocol = (uint8_t)(_jI(r["ipProtocol"],0ULL) & 0xffULL);
  370. return true;
  371. } else if (t == "MATCH_ICMP") {
  372. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  373. rule.v.icmp.type = (uint8_t)(_jI(r["type"],0ULL) & 0xffULL);
  374. json &code = r["code"];
  375. if (code.is_null()) {
  376. rule.v.icmp.code = 0;
  377. rule.v.icmp.flags = 0x00;
  378. } else {
  379. rule.v.icmp.code = (uint8_t)(_jI(code,0ULL) & 0xffULL);
  380. rule.v.icmp.flags = 0x01;
  381. }
  382. return true;
  383. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  384. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  385. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  386. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  387. return true;
  388. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  389. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  390. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  391. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  392. return true;
  393. } else if (t == "MATCH_CHARACTERISTICS") {
  394. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  395. if (r.count("mask")) {
  396. auto v = r["mask"];
  397. if (v.is_number()) {
  398. rule.v.characteristics[0] = v;
  399. } else {
  400. std::string tmp = v;
  401. rule.v.characteristics[0] = Utils::hexStrToU64(tmp.c_str());
  402. }
  403. }
  404. if (r.count("value")) {
  405. auto v = r["value"];
  406. if (v.is_number()) {
  407. rule.v.characteristics[1] = v;
  408. } else {
  409. std::string tmp = v;
  410. rule.v.characteristics[1] = Utils::hexStrToU64(tmp.c_str());
  411. }
  412. }
  413. return true;
  414. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  415. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  416. rule.v.frameSize[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  417. rule.v.frameSize[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  418. return true;
  419. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  420. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  421. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  422. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  423. return true;
  424. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  425. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  426. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  427. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  428. return true;
  429. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  430. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  431. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  432. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  433. return true;
  434. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  435. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  436. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  437. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  438. return true;
  439. }
  440. return false;
  441. }
  442. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath) :
  443. _node(node),
  444. _path(dbPath),
  445. _daemonRun(true)
  446. {
  447. OSUtils::mkdir(dbPath);
  448. OSUtils::lockDownFile(dbPath,true); // networks might contain auth tokens, etc., so restrict directory permissions
  449. _daemon = Thread::start(this);
  450. }
  451. EmbeddedNetworkController::~EmbeddedNetworkController()
  452. {
  453. }
  454. void EmbeddedNetworkController::threadMain()
  455. throw()
  456. {
  457. uint64_t lastUpdatedNetworkMemberCache = 0;
  458. while (_daemonRun) {
  459. // Every 60 seconds we rescan the filesystem for network members and rebuild our cache
  460. if ((OSUtils::now() - lastUpdatedNetworkMemberCache) >= 60000) {
  461. const std::vector<std::string> networks(OSUtils::listSubdirectories((_path + ZT_PATH_SEPARATOR_S + "network").c_str()));
  462. for(auto n=networks.begin();n!=networks.end();++n) {
  463. if (n->length() == 16) {
  464. const std::vector<std::string> members(OSUtils::listSubdirectories((*n + ZT_PATH_SEPARATOR_S + "member").c_str()));
  465. std::map<Address,nlohmann::json> newCache;
  466. for(auto m=members.begin();m!=members.end();++m) {
  467. if (m->length() == ZT_ADDRESS_LENGTH_HEX) {
  468. const Address maddr(*m);
  469. try {
  470. const json mj(_readJson((_path + ZT_PATH_SEPARATOR_S + "network" + ZT_PATH_SEPARATOR_S + *n + ZT_PATH_SEPARATOR_S + "member" + ZT_PATH_SEPARATOR_S + *m + ZT_PATH_SEPARATOR_S + "config.json")));
  471. if ((mj.is_object())&&(mj.size() > 0)) {
  472. newCache[maddr] = mj;
  473. }
  474. } catch ( ... ) {}
  475. }
  476. }
  477. {
  478. Mutex::Lock _l(_networkMemberCache_m);
  479. _networkMemberCache[Utils::hexStrToU64(n->c_str())] = newCache;
  480. }
  481. }
  482. }
  483. lastUpdatedNetworkMemberCache = OSUtils::now();
  484. }
  485. { // Every 25ms we push up to 50 network refreshes, which amounts to a max of about 300-500kb/sec
  486. unsigned int count = 0;
  487. Mutex::Lock _l(_refreshQueue_m);
  488. while (_refreshQueue.size() > 0) {
  489. _Refresh &r = _refreshQueue.front();
  490. if (_node)
  491. _node->pushNetworkRefresh(r.dest,r.nwid,r.blacklistAddresses,r.blacklistThresholds,r.numBlacklistEntries);
  492. _refreshQueue.pop_front();
  493. if (++count >= 50)
  494. break;
  495. }
  496. }
  497. Thread::sleep(25);
  498. }
  499. }
  500. NetworkController::ResultCode EmbeddedNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData,NetworkConfig &nc)
  501. {
  502. if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
  503. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  504. }
  505. const uint64_t now = OSUtils::now();
  506. // Check rate limit circuit breaker to prevent flooding
  507. {
  508. Mutex::Lock _l(_lastRequestTime_m);
  509. uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
  510. if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  511. return NetworkController::NETCONF_QUERY_IGNORE;
  512. lrt = now;
  513. }
  514. json network(_readJson(_networkJP(nwid,false)));
  515. if (!network.size())
  516. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  517. const std::string memberJP(_memberJP(nwid,identity.address(),true));
  518. json member(_readJson(memberJP));
  519. _initMember(member);
  520. {
  521. std::string haveIdStr(_jS(member["identity"],""));
  522. if (haveIdStr.length() > 0) {
  523. // If we already know this member's identity perform a full compare. This prevents
  524. // a "collision" from being able to auth onto our network in place of an already
  525. // known member.
  526. try {
  527. if (Identity(haveIdStr.c_str()) != identity)
  528. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  529. } catch ( ... ) {
  530. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  531. }
  532. } else {
  533. // If we do not yet know this member's identity, learn it.
  534. member["identity"] = identity.toString(false);
  535. }
  536. }
  537. // These are always the same, but make sure they are set
  538. member["id"] = identity.address().toString();
  539. member["address"] = member["id"];
  540. member["nwid"] = network["id"];
  541. // Determine whether and how member is authorized
  542. const char *authorizedBy = (const char *)0;
  543. if (!_jB(network["private"],true)) {
  544. authorizedBy = "networkIsPublic";
  545. // If member already has an authorized field, leave it alone. That way its state is
  546. // preserved if the user toggles the network back to private. Otherwise set it to
  547. // true by default for new members of public nets.
  548. if (!member.count("authorized")) {
  549. member["authorized"] = true;
  550. member["lastAuthorizedTime"] = now;
  551. member["lastAuthorizedBy"] = authorizedBy;
  552. member["lastModified"] = now;
  553. auto revj = member["revision"];
  554. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  555. }
  556. } else if (_jB(member["authorized"],false)) {
  557. authorizedBy = "memberIsAuthorized";
  558. } else {
  559. char atok[256];
  560. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH_TOKEN,atok,sizeof(atok)) > 0) {
  561. atok[255] = (char)0; // not necessary but YDIFLO
  562. if (strlen(atok) > 0) { // extra sanity check since we never want to compare a null token on either side
  563. auto authTokens = network["authTokens"];
  564. if (authTokens.is_array()) {
  565. for(unsigned long i=0;i<authTokens.size();++i) {
  566. auto at = authTokens[i];
  567. if (at.is_object()) {
  568. const uint64_t expires = _jI(at["expires"],0ULL);
  569. std::string tok = _jS(at["token"],"");
  570. if ( ((expires == 0ULL)||(expires > now)) && (tok.length() > 0) && (tok == atok) ) {
  571. authorizedBy = "token";
  572. member["authorized"] = true; // tokens actually change member authorization state
  573. member["lastAuthorizedTime"] = now;
  574. member["lastAuthorizedBy"] = authorizedBy;
  575. member["lastModified"] = now;
  576. auto revj = member["revision"];
  577. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  578. break;
  579. }
  580. }
  581. }
  582. }
  583. }
  584. }
  585. }
  586. // Log this request
  587. {
  588. json rlEntry = json::object();
  589. rlEntry["ts"] = now;
  590. rlEntry["authorized"] = (authorizedBy) ? true : false;
  591. rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
  592. rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  593. rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  594. rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  595. rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  596. if (fromAddr)
  597. rlEntry["fromAddr"] = fromAddr.toString();
  598. json recentLog = json::array();
  599. recentLog.push_back(rlEntry);
  600. json &oldLog = member["recentLog"];
  601. if (oldLog.is_array()) {
  602. for(unsigned long i=0;i<oldLog.size();++i) {
  603. recentLog.push_back(oldLog[i]);
  604. if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
  605. break;
  606. }
  607. }
  608. member["recentLog"] = recentLog;
  609. }
  610. // If they are not authorized, STOP!
  611. if (!authorizedBy) {
  612. _writeJson(memberJP,member);
  613. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  614. }
  615. // -------------------------------------------------------------------------
  616. // If we made it this far, they are authorized.
  617. // -------------------------------------------------------------------------
  618. _NetworkMemberInfo nmi;
  619. _getNetworkMemberInfo(now,nwid,nmi);
  620. // Compute credential TTL. This is the "moving window" for COM agreement and
  621. // the global TTL for Capability and Tag objects. (The same value is used
  622. // for both.) This is computed by reference to the last time we deauthorized
  623. // a member, since within the time period since this event any temporal
  624. // differences are not particularly relevant.
  625. uint64_t credentialTtl = ZT_NETWORKCONFIG_DEFAULT_MIN_CREDENTIAL_TTL;
  626. if (now > nmi.mostRecentDeauthTime)
  627. credentialTtl += (now - nmi.mostRecentDeauthTime);
  628. if (credentialTtl > ZT_NETWORKCONFIG_DEFAULT_MAX_CREDENTIAL_TTL)
  629. credentialTtl = ZT_NETWORKCONFIG_DEFAULT_MAX_CREDENTIAL_TTL;
  630. nc.networkId = nwid;
  631. nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  632. nc.timestamp = now;
  633. nc.credentialTimeToLive = credentialTtl;
  634. nc.revision = _jI(network["revision"],0ULL);
  635. nc.issuedTo = identity.address();
  636. if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  637. if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  638. Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
  639. nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
  640. for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab)
  641. nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  642. json &v4AssignMode = network["v4AssignMode"];
  643. json &v6AssignMode = network["v6AssignMode"];
  644. json &ipAssignmentPools = network["ipAssignmentPools"];
  645. json &routes = network["routes"];
  646. json &rules = network["rules"];
  647. json &capabilities = network["capabilities"];
  648. json &memberCapabilities = member["capabilities"];
  649. json &memberTags = member["tags"];
  650. if (rules.is_array()) {
  651. for(unsigned long i=0;i<rules.size();++i) {
  652. if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
  653. break;
  654. if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
  655. ++nc.ruleCount;
  656. }
  657. }
  658. if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
  659. std::map< uint64_t,json * > capsById;
  660. for(unsigned long i=0;i<capabilities.size();++i) {
  661. json &cap = capabilities[i];
  662. if (cap.is_object())
  663. capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
  664. }
  665. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  666. const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
  667. json *cap = capsById[capId];
  668. if ((cap->is_object())&&(cap->size() > 0)) {
  669. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  670. unsigned int caprc = 0;
  671. json &caprj = (*cap)["rules"];
  672. if ((caprj.is_array())&&(caprj.size() > 0)) {
  673. for(unsigned long j=0;j<caprj.size();++j) {
  674. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  675. break;
  676. if (_parseRule(caprj[j],capr[caprc]))
  677. ++caprc;
  678. }
  679. }
  680. nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  681. if (nc.capabilities[nc.capabilityCount].sign(signingId,identity.address()))
  682. ++nc.capabilityCount;
  683. if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  684. break;
  685. }
  686. }
  687. }
  688. if (memberTags.is_array()) {
  689. std::map< uint32_t,uint32_t > tagsById;
  690. for(unsigned long i=0;i<memberTags.size();++i) {
  691. json &t = memberTags[i];
  692. if ((t.is_array())&&(t.size() == 2))
  693. tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
  694. }
  695. for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
  696. if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
  697. break;
  698. nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  699. if (nc.tags[nc.tagCount].sign(signingId))
  700. ++nc.tagCount;
  701. }
  702. }
  703. if (routes.is_array()) {
  704. for(unsigned long i=0;i<routes.size();++i) {
  705. if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
  706. break;
  707. json &route = routes[i];
  708. json &target = route["target"];
  709. json &via = route["via"];
  710. if (target.is_string()) {
  711. const InetAddress t(target.get<std::string>());
  712. InetAddress v;
  713. if (via.is_string()) v.fromString(via.get<std::string>());
  714. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  715. ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
  716. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  717. if (v.ss_family == t.ss_family)
  718. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  719. ++nc.routeCount;
  720. }
  721. }
  722. }
  723. }
  724. const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
  725. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  726. if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  727. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  728. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  729. }
  730. if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  731. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  732. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  733. }
  734. }
  735. bool haveManagedIpv4AutoAssignment = false;
  736. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  737. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  738. if (ipAssignments.is_array()) {
  739. for(unsigned long i=0;i<ipAssignments.size();++i) {
  740. if (!ipAssignments[i].is_string())
  741. continue;
  742. std::string ips = ipAssignments[i];
  743. InetAddress ip(ips);
  744. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  745. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  746. // of user error / poor UX.
  747. int routedNetmaskBits = 0;
  748. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  749. if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
  750. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  751. }
  752. if (routedNetmaskBits > 0) {
  753. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  754. ip.setPort(routedNetmaskBits);
  755. nc.staticIps[nc.staticIpCount++] = ip;
  756. }
  757. if (ip.ss_family == AF_INET)
  758. haveManagedIpv4AutoAssignment = true;
  759. else if (ip.ss_family == AF_INET6)
  760. haveManagedIpv6AutoAssignment = true;
  761. }
  762. }
  763. } else {
  764. ipAssignments = json::array();
  765. }
  766. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  767. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  768. json &pool = ipAssignmentPools[p];
  769. if (pool.is_object()) {
  770. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  771. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  772. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  773. uint64_t s[2],e[2],x[2],xx[2];
  774. memcpy(s,ipRangeStart.rawIpData(),16);
  775. memcpy(e,ipRangeEnd.rawIpData(),16);
  776. s[0] = Utils::ntoh(s[0]);
  777. s[1] = Utils::ntoh(s[1]);
  778. e[0] = Utils::ntoh(e[0]);
  779. e[1] = Utils::ntoh(e[1]);
  780. x[0] = s[0];
  781. x[1] = s[1];
  782. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  783. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  784. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  785. xx[0] = Utils::hton(x[0]);
  786. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  787. } else {
  788. // 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
  789. Utils::getSecureRandom((void *)xx,16);
  790. if ((e[0] > s[0]))
  791. xx[0] %= (e[0] - s[0]);
  792. else xx[0] = 0;
  793. if ((e[1] > s[1]))
  794. xx[1] %= (e[1] - s[1]);
  795. else xx[1] = 0;
  796. xx[0] = Utils::hton(x[0] + xx[0]);
  797. xx[1] = Utils::hton(x[1] + xx[1]);
  798. }
  799. InetAddress ip6((const void *)xx,16,0);
  800. // Check if this IP is within a local-to-Ethernet routed network
  801. int routedNetmaskBits = 0;
  802. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  803. 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)) )
  804. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  805. }
  806. // If it's routed, then try to claim and assign it and if successful end loop
  807. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
  808. ipAssignments.push_back(ip6.toIpString());
  809. member["ipAssignments"] = ipAssignments;
  810. ip6.setPort((unsigned int)routedNetmaskBits);
  811. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  812. nc.staticIps[nc.staticIpCount++] = ip6;
  813. haveManagedIpv6AutoAssignment = true;
  814. break;
  815. }
  816. }
  817. }
  818. }
  819. }
  820. }
  821. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  822. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  823. json &pool = ipAssignmentPools[p];
  824. if (pool.is_object()) {
  825. InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
  826. InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
  827. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  828. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  829. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  830. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  831. continue;
  832. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  833. // Start with the LSB of the member's address
  834. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  835. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  836. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  837. ++ipTrialCounter;
  838. if ((ip & 0x000000ff) == 0x000000ff)
  839. continue; // don't allow addresses that end in .255
  840. // Check if this IP is within a local-to-Ethernet routed network
  841. int routedNetmaskBits = -1;
  842. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  843. if (nc.routes[rk].target.ss_family == AF_INET) {
  844. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
  845. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
  846. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  847. routedNetmaskBits = targetBits;
  848. break;
  849. }
  850. }
  851. }
  852. // If it's routed, then try to claim and assign it and if successful end loop
  853. const InetAddress ip4(Utils::hton(ip),0);
  854. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
  855. ipAssignments.push_back(ip4.toIpString());
  856. member["ipAssignments"] = ipAssignments;
  857. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  858. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
  859. v4ip->sin_family = AF_INET;
  860. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  861. v4ip->sin_addr.s_addr = Utils::hton(ip);
  862. }
  863. haveManagedIpv4AutoAssignment = true;
  864. break;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. }
  871. if (_jB(network["private"],true)) {
  872. CertificateOfMembership com(now,credentialTtl,nwid,identity.address());
  873. if (com.sign(signingId)) {
  874. nc.com = com;
  875. } else {
  876. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  877. }
  878. }
  879. _writeJson(memberJP,member);
  880. return NetworkController::NETCONF_QUERY_OK;
  881. }
  882. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  883. const std::vector<std::string> &path,
  884. const std::map<std::string,std::string> &urlArgs,
  885. const std::map<std::string,std::string> &headers,
  886. const std::string &body,
  887. std::string &responseBody,
  888. std::string &responseContentType)
  889. {
  890. if ((path.size() > 0)&&(path[0] == "network")) {
  891. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  892. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  893. char nwids[24];
  894. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  895. json network(_readJson(_networkJP(nwid,false)));
  896. if (!network.size())
  897. return 404;
  898. if (path.size() >= 3) {
  899. if (path[2] == "member") {
  900. if (path.size() >= 4) {
  901. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  902. json member(_readJson(_memberJP(nwid,Address(address),false)));
  903. if (!member.size())
  904. return 404;
  905. char addrs[24];
  906. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",address);
  907. // Add non-persisted fields
  908. member["clock"] = OSUtils::now();
  909. responseBody = member.dump(2);
  910. responseContentType = "application/json";
  911. return 200;
  912. } else {
  913. responseBody = "{";
  914. std::vector<std::string> members(OSUtils::listSubdirectories((_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member").c_str()));
  915. for(std::vector<std::string>::iterator i(members.begin());i!=members.end();++i) {
  916. if (i->length() == ZT_ADDRESS_LENGTH_HEX) {
  917. json member(_readJson(_memberJP(nwid,Address(Utils::hexStrToU64(i->c_str())),false)));
  918. if (member.size()) {
  919. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  920. responseBody.append(*i);
  921. responseBody.append("\":");
  922. responseBody.append(_jS(member["revision"],"0"));
  923. }
  924. }
  925. }
  926. responseBody.push_back('}');
  927. responseContentType = "application/json";
  928. return 200;
  929. }
  930. } else if ((path[2] == "active")&&(path.size() == 3)) {
  931. responseBody = "{";
  932. std::vector<std::string> members(OSUtils::listSubdirectories((_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member").c_str()));
  933. const uint64_t threshold = OSUtils::now() - ZT_NETCONF_NODE_ACTIVE_THRESHOLD;
  934. for(std::vector<std::string>::iterator i(members.begin());i!=members.end();++i) {
  935. if (i->length() == ZT_ADDRESS_LENGTH_HEX) {
  936. json member(_readJson(_memberJP(nwid,Address(Utils::hexStrToU64(i->c_str())),false)));
  937. if (member.size()) {
  938. auto recentLog = member["recentLog"];
  939. if ((recentLog.is_array())&&(recentLog.size() > 0)) {
  940. auto mostRecentLog = recentLog[0];
  941. if ((mostRecentLog.is_object())&&(_jI(mostRecentLog["ts"],0ULL) >= threshold)) {
  942. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  943. responseBody.append(*i);
  944. responseBody.append("\":");
  945. responseBody.append(mostRecentLog.dump());
  946. }
  947. }
  948. }
  949. }
  950. }
  951. responseBody.push_back('}');
  952. responseContentType = "application/json";
  953. return 200;
  954. } else if ((path[2] == "test")&&(path.size() >= 4)) {
  955. Mutex::Lock _l(_circuitTests_m);
  956. std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
  957. if ((cte != _circuitTests.end())&&(cte->second.test)) {
  958. responseBody = "[";
  959. responseBody.append(cte->second.jsonResults);
  960. responseBody.push_back(']');
  961. responseContentType = "application/json";
  962. return 200;
  963. } // else 404
  964. } // else 404
  965. } else {
  966. const uint64_t now = OSUtils::now();
  967. _NetworkMemberInfo nmi;
  968. _getNetworkMemberInfo(now,nwid,nmi);
  969. _addNetworkNonPersistedFields(network,now,nmi);
  970. responseBody = network.dump(2);
  971. responseContentType = "application/json";
  972. return 200;
  973. }
  974. } else if (path.size() == 1) {
  975. responseBody = "[";
  976. std::vector<std::string> networks(OSUtils::listSubdirectories((_path + ZT_PATH_SEPARATOR_S + "network").c_str()));
  977. for(auto i(networks.begin());i!=networks.end();++i) {
  978. if (i->length() == 16) {
  979. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  980. responseBody.append(*i);
  981. responseBody.append("\"");
  982. }
  983. }
  984. responseBody.push_back(']');
  985. responseContentType = "application/json";
  986. return 200;
  987. } // else 404
  988. } else {
  989. char tmp[4096];
  990. Utils::snprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now());
  991. responseBody = tmp;
  992. responseContentType = "application/json";
  993. return 200;
  994. }
  995. return 404;
  996. }
  997. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  998. const std::vector<std::string> &path,
  999. const std::map<std::string,std::string> &urlArgs,
  1000. const std::map<std::string,std::string> &headers,
  1001. const std::string &body,
  1002. std::string &responseBody,
  1003. std::string &responseContentType)
  1004. {
  1005. if (path.empty())
  1006. return 404;
  1007. json b;
  1008. try {
  1009. b = json::parse(body);
  1010. if (!b.is_object()) {
  1011. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  1012. responseContentType = "application/json";
  1013. return 400;
  1014. }
  1015. } catch (std::exception &exc) {
  1016. responseBody = std::string("{ \"message\": \"body JSON is invalid: ") + exc.what() + "\" }";
  1017. responseContentType = "application/json";
  1018. return 400;
  1019. } catch ( ... ) {
  1020. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  1021. responseContentType = "application/json";
  1022. return 400;
  1023. }
  1024. const uint64_t now = OSUtils::now();
  1025. if (path[0] == "network") {
  1026. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1027. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1028. char nwids[24];
  1029. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  1030. if (path.size() >= 3) {
  1031. json network(_readJson(_networkJP(nwid,false)));
  1032. if (!network.size())
  1033. return 404;
  1034. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1035. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1036. char addrs[24];
  1037. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  1038. json member(_readJson(_memberJP(nwid,Address(address),true)));
  1039. _initMember(member);
  1040. try {
  1041. if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
  1042. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
  1043. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  1044. if (b.count("authorized")) {
  1045. const bool newAuth = _jB(b["authorized"],false);
  1046. const bool oldAuth = _jB(member["authorized"],false);
  1047. if (newAuth != oldAuth) {
  1048. if (newAuth) {
  1049. member["authorized"] = true;
  1050. member["lastAuthorizedTime"] = now;
  1051. member["lastAuthorizedBy"] = "user";
  1052. } else {
  1053. member["authorized"] = false;
  1054. member["lastDeauthorizedTime"] = now;
  1055. }
  1056. }
  1057. }
  1058. if (b.count("ipAssignments")) {
  1059. auto ipa = b["ipAssignments"];
  1060. if (ipa.is_array()) {
  1061. json mipa(json::array());
  1062. for(unsigned long i=0;i<ipa.size();++i) {
  1063. std::string ips = ipa[i];
  1064. InetAddress ip(ips);
  1065. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1066. mipa.push_back(ip.toIpString());
  1067. }
  1068. }
  1069. member["ipAssignments"] = mipa;
  1070. }
  1071. }
  1072. if (b.count("tags")) {
  1073. auto tags = b["tags"];
  1074. if (tags.is_array()) {
  1075. std::map<uint64_t,uint64_t> mtags;
  1076. for(unsigned long i=0;i<tags.size();++i) {
  1077. auto tag = tags[i];
  1078. if ((tag.is_array())&&(tag.size() == 2))
  1079. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  1080. }
  1081. json mtagsa = json::array();
  1082. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1083. json ta = json::array();
  1084. ta.push_back(t->first);
  1085. ta.push_back(t->second);
  1086. mtagsa.push_back(ta);
  1087. }
  1088. member["tags"] = mtagsa;
  1089. }
  1090. }
  1091. if (b.count("capabilities")) {
  1092. auto capabilities = b["capabilities"];
  1093. if (capabilities.is_array()) {
  1094. json mcaps = json::array();
  1095. for(unsigned long i=0;i<capabilities.size();++i) {
  1096. mcaps.push_back(_jI(capabilities[i],0ULL));
  1097. }
  1098. std::sort(mcaps.begin(),mcaps.end());
  1099. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1100. member["capabilities"] = mcaps;
  1101. }
  1102. }
  1103. } catch ( ... ) {
  1104. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  1105. responseContentType = "application/json";
  1106. return 400;
  1107. }
  1108. member["id"] = addrs;
  1109. member["address"] = addrs; // legacy
  1110. member["nwid"] = nwids;
  1111. member["lastModified"] = now;
  1112. auto revj = member["revision"];
  1113. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  1114. _writeJson(_memberJP(nwid,Address(address),true).c_str(),member);
  1115. {
  1116. Mutex::Lock _l(_networkMemberCache_m);
  1117. _networkMemberCache[nwid][Address(address)] = member;
  1118. }
  1119. {
  1120. Mutex::Lock _l(_refreshQueue_m);
  1121. _refreshQueue.push_back(_Refresh());
  1122. _Refresh &r = _refreshQueue.back();
  1123. r.dest = Address(address);
  1124. r.nwid = nwid;
  1125. r.numBlacklistEntries = 0;
  1126. }
  1127. // Add non-persisted fields
  1128. member["clock"] = now;
  1129. responseBody = member.dump(2);
  1130. responseContentType = "application/json";
  1131. return 200;
  1132. } else if ((path.size() == 3)&&(path[2] == "test")) {
  1133. Mutex::Lock _l(_circuitTests_m);
  1134. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  1135. memset(test,0,sizeof(ZT_CircuitTest));
  1136. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  1137. test->credentialNetworkId = nwid;
  1138. test->ptr = (void *)this;
  1139. json hops = b["hops"];
  1140. if (hops.is_array()) {
  1141. for(unsigned long i=0;i<hops.size();++i) {
  1142. auto hops2 = hops[i];
  1143. if (hops2.is_array()) {
  1144. for(unsigned long j=0;j<hops2.size();++j) {
  1145. std::string s = hops2[j];
  1146. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1147. }
  1148. } else if (hops2.is_string()) {
  1149. std::string s = hops2;
  1150. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1151. }
  1152. }
  1153. }
  1154. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1155. if (!test->hopCount) {
  1156. ::free((void *)test);
  1157. responseBody = "{ \"message\": \"a test must contain at least one hop\" }";
  1158. responseContentType = "application/json";
  1159. return 400;
  1160. }
  1161. test->timestamp = OSUtils::now();
  1162. _CircuitTestEntry &te = _circuitTests[test->testId];
  1163. te.test = test;
  1164. te.jsonResults = "";
  1165. if (_node)
  1166. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1167. else return 500;
  1168. char json[1024];
  1169. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1170. responseBody = json;
  1171. responseContentType = "application/json";
  1172. return 200;
  1173. } // else 404
  1174. } else {
  1175. // POST to network ID
  1176. // Magic ID ending with ______ picks a random unused network ID
  1177. if (path[1].substr(10) == "______") {
  1178. nwid = 0;
  1179. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1180. uint64_t nwidPostfix = 0;
  1181. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1182. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1183. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1184. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1185. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1186. if (!OSUtils::fileExists(_networkJP(tryNwid,false).c_str())) {
  1187. nwid = tryNwid;
  1188. break;
  1189. }
  1190. }
  1191. if (!nwid)
  1192. return 503;
  1193. }
  1194. json network(_readJson(_networkJP(nwid,true)));
  1195. _initNetwork(network);
  1196. try {
  1197. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1198. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1199. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1200. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1201. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1202. if (b.count("v4AssignMode")) {
  1203. json &nv4m = network["v4AssignMode"];
  1204. if (!nv4m.is_object()) nv4m = json::object();
  1205. if (b["v4AssignMode"].is_string()) { // backward compatibility
  1206. nv4m["zt"] = (_jS(b["v4AssignMode"],"") == "zt");
  1207. } else if (b["v4AssignMode"].is_object()) {
  1208. json &v4m = b["v4AssignMode"];
  1209. if (v4m.count("zt")) nv4m["zt"] = _jB(v4m["zt"],false);
  1210. }
  1211. if (!nv4m.count("zt")) nv4m["zt"] = false;
  1212. }
  1213. if (b.count("v6AssignMode")) {
  1214. json &nv6m = network["v6AssignMode"];
  1215. if (!nv6m.is_object()) nv6m = json::object();
  1216. if (b["v6AssignMode"].is_string()) { // backward compatibility
  1217. std::vector<std::string> v6m(Utils::split(_jS(b["v6AssignMode"],"").c_str(),",","",""));
  1218. std::sort(v6m.begin(),v6m.end());
  1219. v6m.erase(std::unique(v6m.begin(),v6m.end()),v6m.end());
  1220. nv6m["rfc4193"] = false;
  1221. nv6m["zt"] = false;
  1222. nv6m["6plane"] = false;
  1223. for(std::vector<std::string>::iterator i(v6m.begin());i!=v6m.end();++i) {
  1224. if (*i == "rfc4193")
  1225. nv6m["rfc4193"] = true;
  1226. else if (*i == "zt")
  1227. nv6m["zt"] = true;
  1228. else if (*i == "6plane")
  1229. nv6m["6plane"] = true;
  1230. }
  1231. } else if (b["v6AssignMode"].is_object()) {
  1232. json &v6m = b["v6AssignMode"];
  1233. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1234. if (v6m.count("zt")) nv6m["zt"] = _jB(v6m["zt"],false);
  1235. if (v6m.count("6plane")) nv6m["6plane"] = _jB(v6m["6plane"],false);
  1236. }
  1237. if (!nv6m.count("rfc4193")) nv6m["rfc4193"] = false;
  1238. if (!nv6m.count("zt")) nv6m["zt"] = false;
  1239. if (!nv6m.count("6plane")) nv6m["6plane"] = false;
  1240. }
  1241. if (b.count("routes")) {
  1242. json &rts = b["routes"];
  1243. if (rts.is_array()) {
  1244. json nrts = json::array();
  1245. for(unsigned long i=0;i<rts.size();++i) {
  1246. json &rt = rts[i];
  1247. if (rt.is_object()) {
  1248. json &target = rt["target"];
  1249. json &via = rt["via"];
  1250. if (target.is_string()) {
  1251. InetAddress t(target.get<std::string>());
  1252. InetAddress v;
  1253. if (via.is_string()) v.fromString(via.get<std::string>());
  1254. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  1255. json tmp;
  1256. tmp["target"] = t.toString();
  1257. if (v.ss_family == t.ss_family)
  1258. tmp["via"] = v.toIpString();
  1259. else tmp["via"] = json();
  1260. nrts.push_back(tmp);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. network["routes"] = nrts;
  1266. }
  1267. }
  1268. if (b.count("ipAssignmentPools")) {
  1269. json &ipp = b["ipAssignmentPools"];
  1270. if (ipp.is_array()) {
  1271. json nipp = json::array();
  1272. for(unsigned long i=0;i<ipp.size();++i) {
  1273. auto ip = ipp[i];
  1274. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1275. InetAddress f(_jS(ip["ipRangeStart"],""));
  1276. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1277. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1278. json tmp = json::object();
  1279. tmp["ipRangeStart"] = f.toIpString();
  1280. tmp["ipRangeEnd"] = t.toIpString();
  1281. nipp.push_back(tmp);
  1282. }
  1283. }
  1284. }
  1285. network["ipAssignmentPools"] = nipp;
  1286. }
  1287. }
  1288. if (b.count("rules")) {
  1289. json &rules = b["rules"];
  1290. if (rules.is_array()) {
  1291. json nrules = json::array();
  1292. for(unsigned long i=0;i<rules.size();++i) {
  1293. json &rule = rules[i];
  1294. if (rule.is_object()) {
  1295. ZT_VirtualNetworkRule ztr;
  1296. if (_parseRule(rule,ztr))
  1297. nrules.push_back(_renderRule(ztr));
  1298. }
  1299. }
  1300. network["rules"] = nrules;
  1301. }
  1302. }
  1303. if (b.count("authTokens")) {
  1304. json &authTokens = b["authTokens"];
  1305. if (authTokens.is_array()) {
  1306. json nat = json::array();
  1307. for(unsigned long i=0;i<authTokens.size();++i) {
  1308. auto token = authTokens[i];
  1309. if (token.is_object()) {
  1310. std::string tstr = token["token"];
  1311. if (tstr.length() > 0) {
  1312. json t = json::object();
  1313. t["token"] = tstr;
  1314. t["expires"] = _jI(token["expires"],0ULL);
  1315. nat.push_back(t);
  1316. }
  1317. }
  1318. }
  1319. network["authTokens"] = nat;
  1320. }
  1321. }
  1322. if (b.count("capabilities")) {
  1323. json &capabilities = b["capabilities"];
  1324. if (capabilities.is_array()) {
  1325. std::map< uint64_t,json > ncaps;
  1326. for(unsigned long i=0;i<capabilities.size();++i) {
  1327. json &cap = capabilities[i];
  1328. if (cap.is_object()) {
  1329. json ncap = json::object();
  1330. const uint64_t capId = _jI(cap["id"],0ULL);
  1331. ncap["id"] = capId;
  1332. json &rules = cap["rules"];
  1333. json nrules = json::array();
  1334. if (rules.is_array()) {
  1335. for(unsigned long i=0;i<rules.size();++i) {
  1336. json rule = rules[i];
  1337. if (rule.is_object()) {
  1338. ZT_VirtualNetworkRule ztr;
  1339. if (_parseRule(rule,ztr))
  1340. nrules.push_back(_renderRule(ztr));
  1341. }
  1342. }
  1343. }
  1344. ncap["rules"] = nrules;
  1345. ncaps[capId] = ncap;
  1346. }
  1347. }
  1348. json ncapsa = json::array();
  1349. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1350. ncapsa.push_back(c->second);
  1351. network["capabilities"] = ncapsa;
  1352. }
  1353. }
  1354. } catch ( ... ) {
  1355. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  1356. responseContentType = "application/json";
  1357. return 400;
  1358. }
  1359. network["id"] = nwids;
  1360. network["nwid"] = nwids; // legacy
  1361. auto rev = network["revision"];
  1362. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1363. network["lastModified"] = now;
  1364. _writeJson(_networkJP(nwid,true),network);
  1365. _NetworkMemberInfo nmi;
  1366. _getNetworkMemberInfo(now,nwid,nmi);
  1367. _addNetworkNonPersistedFields(network,now,nmi);
  1368. responseBody = network.dump(2);
  1369. responseContentType = "application/json";
  1370. return 200;
  1371. } // else 404
  1372. } // else 404
  1373. } // else 404
  1374. return 404;
  1375. }
  1376. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1377. const std::vector<std::string> &path,
  1378. const std::map<std::string,std::string> &urlArgs,
  1379. const std::map<std::string,std::string> &headers,
  1380. const std::string &body,
  1381. std::string &responseBody,
  1382. std::string &responseContentType)
  1383. {
  1384. if (path.empty())
  1385. return 404;
  1386. if (path[0] == "network") {
  1387. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1388. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1389. json network(_readJson(_networkJP(nwid,false)));
  1390. if (!network.size())
  1391. return 404;
  1392. if (path.size() >= 3) {
  1393. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1394. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1395. json member(_readJson(_memberJP(nwid,Address(address),false)));
  1396. if (!member.size())
  1397. return 404;
  1398. OSUtils::rmDashRf(_memberBP(nwid,Address(address),false).c_str());
  1399. responseBody = member.dump(2);
  1400. responseContentType = "application/json";
  1401. return 200;
  1402. }
  1403. } else {
  1404. OSUtils::rmDashRf(_networkBP(nwid,false).c_str());
  1405. {
  1406. Mutex::Lock _l(_networkMemberCache_m);
  1407. _networkMemberCache.erase(nwid);
  1408. }
  1409. responseBody = network.dump(2);
  1410. responseContentType = "application/json";
  1411. return 200;
  1412. }
  1413. } // else 404
  1414. } // else 404
  1415. return 404;
  1416. }
  1417. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1418. {
  1419. char tmp[65535];
  1420. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1421. if (!test)
  1422. return;
  1423. if (!report)
  1424. return;
  1425. Mutex::Lock _l(self->_circuitTests_m);
  1426. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1427. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1428. self->_node->circuitTestEnd(test);
  1429. ::free((void *)test);
  1430. return;
  1431. }
  1432. Utils::snprintf(tmp,sizeof(tmp),
  1433. "%s{\n"
  1434. "\t\"timestamp\": %llu," ZT_EOL_S
  1435. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1436. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1437. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1438. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1439. "\t\"remoteTimestamp\": %llu," ZT_EOL_S
  1440. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1441. "\t\"flags\": %llu," ZT_EOL_S
  1442. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1443. "\t\"errorCode\": %u," ZT_EOL_S
  1444. "\t\"vendor\": %d," ZT_EOL_S
  1445. "\t\"protocolVersion\": %u," ZT_EOL_S
  1446. "\t\"majorVersion\": %u," ZT_EOL_S
  1447. "\t\"minorVersion\": %u," ZT_EOL_S
  1448. "\t\"revision\": %u," ZT_EOL_S
  1449. "\t\"platform\": %d," ZT_EOL_S
  1450. "\t\"architecture\": %d," ZT_EOL_S
  1451. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1452. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1453. "}",
  1454. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1455. (unsigned long long)report->timestamp,
  1456. (unsigned long long)test->testId,
  1457. (unsigned long long)report->upstream,
  1458. (unsigned long long)report->current,
  1459. (unsigned long long)OSUtils::now(),
  1460. (unsigned long long)report->remoteTimestamp,
  1461. (unsigned long long)report->sourcePacketId,
  1462. (unsigned long long)report->flags,
  1463. report->sourcePacketHopCount,
  1464. report->errorCode,
  1465. (int)report->vendor,
  1466. report->protocolVersion,
  1467. report->majorVersion,
  1468. report->minorVersion,
  1469. report->revision,
  1470. (int)report->platform,
  1471. (int)report->architecture,
  1472. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1473. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1474. cte->second.jsonResults.append(tmp);
  1475. }
  1476. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1477. {
  1478. Mutex::Lock _mcl(_networkMemberCache_m);
  1479. std::map< Address,nlohmann::json > &memberCacheEntry = _networkMemberCache[nwid];
  1480. nmi.totalMemberCount = memberCacheEntry.size();
  1481. for(std::map< Address,nlohmann::json >::iterator nm(memberCacheEntry.begin());nm!=memberCacheEntry.end();++nm) {
  1482. if (_jB(nm->second["authorized"],false)) {
  1483. ++nmi.authorizedMemberCount;
  1484. if (nm->second.count("recentLog")) {
  1485. json &mlog = nm->second["recentLog"];
  1486. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1487. json &mlog1 = mlog[0];
  1488. if (mlog1.is_object()) {
  1489. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1490. ++nmi.activeMemberCount;
  1491. }
  1492. }
  1493. }
  1494. if (_jB(nm->second["activeBridge"],false)) {
  1495. nmi.activeBridges.insert(nm->first);
  1496. }
  1497. if (nm->second.count("ipAssignments")) {
  1498. json &mips = nm->second["ipAssignments"];
  1499. if (mips.is_array()) {
  1500. for(unsigned long i=0;i<mips.size();++i) {
  1501. InetAddress mip(_jS(mips[i],""));
  1502. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1503. nmi.allocatedIps.insert(mip);
  1504. }
  1505. }
  1506. }
  1507. } else {
  1508. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(nm->second["lastDeauthorizedTime"],0ULL));
  1509. }
  1510. }
  1511. }
  1512. } // namespace ZeroTier