EmbeddedNetworkController.cpp 58 KB

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