2
0

EmbeddedNetworkController.cpp 59 KB

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