2
0

EmbeddedNetworkController.cpp 59 KB

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