EmbeddedNetworkController.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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. 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)
  448. {
  449. if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
  450. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  451. }
  452. const uint64_t now = OSUtils::now();
  453. // Check rate limit circuit breaker to prevent flooding
  454. {
  455. Mutex::Lock _l(_lastRequestTime_m);
  456. uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
  457. if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  458. return NetworkController::NETCONF_QUERY_IGNORE;
  459. lrt = now;
  460. }
  461. char nwids[24];
  462. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  463. json network;
  464. json member;
  465. {
  466. Mutex::Lock _l(_db_m);
  467. network = _db.get("network",nwids,0);
  468. member = _db.get("network",nwids,"member",identity.address().toString(),0);
  469. }
  470. if (!network.size())
  471. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  472. _initMember(member);
  473. {
  474. std::string haveIdStr(_jS(member["identity"],""));
  475. if (haveIdStr.length() > 0) {
  476. // If we already know this member's identity perform a full compare. This prevents
  477. // a "collision" from being able to auth onto our network in place of an already
  478. // known member.
  479. try {
  480. if (Identity(haveIdStr.c_str()) != identity)
  481. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  482. } catch ( ... ) {
  483. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  484. }
  485. } else {
  486. // If we do not yet know this member's identity, learn it.
  487. member["identity"] = identity.toString(false);
  488. }
  489. }
  490. // These are always the same, but make sure they are set
  491. member["id"] = identity.address().toString();
  492. member["address"] = member["id"];
  493. member["nwid"] = network["id"];
  494. // Determine whether and how member is authorized
  495. const char *authorizedBy = (const char *)0;
  496. if (_jB(member["authorized"],false)) {
  497. authorizedBy = "memberIsAuthorized";
  498. } else if (!_jB(network["private"],true)) {
  499. authorizedBy = "networkIsPublic";
  500. if (!member.count("authorized")) {
  501. member["authorized"] = true;
  502. json ah;
  503. ah["a"] = true;
  504. ah["by"] = authorizedBy;
  505. ah["ts"] = now;
  506. ah["ct"] = json();
  507. ah["c"] = json();
  508. member["authHistory"].push_back(ah);
  509. member["lastModified"] = now;
  510. json &revj = member["revision"];
  511. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  512. }
  513. } else {
  514. char presentedAuth[512];
  515. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  516. presentedAuth[511] = (char)0; // sanity check
  517. // Check for bearer token presented by member
  518. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  519. const char *const presentedToken = presentedAuth + 6;
  520. json &authTokens = network["authTokens"];
  521. if (authTokens.is_array()) {
  522. for(unsigned long i=0;i<authTokens.size();++i) {
  523. json &token = authTokens[i];
  524. if (token.is_object()) {
  525. const uint64_t expires = _jI(token["expires"],0ULL);
  526. const uint64_t maxUses = _jI(token["maxUsesPerMember"],0ULL);
  527. std::string tstr = _jS(token["token"],"");
  528. if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
  529. bool usable = (maxUses == 0);
  530. if (!usable) {
  531. uint64_t useCount = 0;
  532. json &ahist = member["authHistory"];
  533. if (ahist.is_array()) {
  534. for(unsigned long j=0;j<ahist.size();++j) {
  535. json &ah = ahist[j];
  536. if ((_jS(ah["ct"],"") == "token")&&(_jS(ah["c"],"") == tstr)&&(_jB(ah["a"],false)))
  537. ++useCount;
  538. }
  539. }
  540. usable = (useCount < maxUses);
  541. }
  542. if (usable) {
  543. authorizedBy = "token";
  544. member["authorized"] = true;
  545. json ah;
  546. ah["a"] = true;
  547. ah["by"] = authorizedBy;
  548. ah["ts"] = now;
  549. ah["ct"] = "token";
  550. ah["c"] = tstr;
  551. member["authHistory"].push_back(ah);
  552. member["lastModified"] = now;
  553. json &revj = member["revision"];
  554. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  555. }
  556. }
  557. }
  558. }
  559. }
  560. }
  561. }
  562. }
  563. // Log this request
  564. {
  565. json rlEntry = json::object();
  566. rlEntry["ts"] = now;
  567. rlEntry["authorized"] = (authorizedBy) ? true : false;
  568. rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
  569. rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  570. rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  571. rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  572. rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  573. if (fromAddr)
  574. rlEntry["fromAddr"] = fromAddr.toString();
  575. json recentLog = json::array();
  576. recentLog.push_back(rlEntry);
  577. json &oldLog = member["recentLog"];
  578. if (oldLog.is_array()) {
  579. for(unsigned long i=0;i<oldLog.size();++i) {
  580. recentLog.push_back(oldLog[i]);
  581. if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
  582. break;
  583. }
  584. }
  585. member["recentLog"] = recentLog;
  586. }
  587. // If they are not authorized, STOP!
  588. if (!authorizedBy) {
  589. Mutex::Lock _l(_db_m);
  590. _db.put("network",nwids,"member",identity.address().toString(),member);
  591. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  592. }
  593. // -------------------------------------------------------------------------
  594. // If we made it this far, they are authorized.
  595. // -------------------------------------------------------------------------
  596. _NetworkMemberInfo nmi;
  597. _getNetworkMemberInfo(now,nwid,nmi);
  598. // Compute credential TTL. This is the "moving window" for COM agreement and
  599. // the global TTL for Capability and Tag objects. (The same value is used
  600. // for both.) This is computed by reference to the last time we deauthorized
  601. // a member, since within the time period since this event any temporal
  602. // differences are not particularly relevant.
  603. uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  604. if (now > nmi.mostRecentDeauthTime)
  605. credentialtmd += (now - nmi.mostRecentDeauthTime);
  606. if (credentialtmd > ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA)
  607. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  608. nc.networkId = nwid;
  609. nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  610. nc.timestamp = now;
  611. nc.credentialTimeMaxDelta = credentialtmd;
  612. nc.revision = _jI(network["revision"],0ULL);
  613. nc.issuedTo = identity.address();
  614. if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  615. if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  616. Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
  617. nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
  618. for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab)
  619. nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  620. json &v4AssignMode = network["v4AssignMode"];
  621. json &v6AssignMode = network["v6AssignMode"];
  622. json &ipAssignmentPools = network["ipAssignmentPools"];
  623. json &routes = network["routes"];
  624. json &rules = network["rules"];
  625. json &capabilities = network["capabilities"];
  626. json &memberCapabilities = member["capabilities"];
  627. json &memberTags = member["tags"];
  628. if (rules.is_array()) {
  629. for(unsigned long i=0;i<rules.size();++i) {
  630. if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
  631. break;
  632. if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
  633. ++nc.ruleCount;
  634. }
  635. }
  636. if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
  637. std::map< uint64_t,json * > capsById;
  638. for(unsigned long i=0;i<capabilities.size();++i) {
  639. json &cap = capabilities[i];
  640. if (cap.is_object())
  641. capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
  642. }
  643. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  644. const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
  645. json *cap = capsById[capId];
  646. if ((cap->is_object())&&(cap->size() > 0)) {
  647. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  648. unsigned int caprc = 0;
  649. json &caprj = (*cap)["rules"];
  650. if ((caprj.is_array())&&(caprj.size() > 0)) {
  651. for(unsigned long j=0;j<caprj.size();++j) {
  652. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  653. break;
  654. if (_parseRule(caprj[j],capr[caprc]))
  655. ++caprc;
  656. }
  657. }
  658. nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  659. if (nc.capabilities[nc.capabilityCount].sign(signingId,identity.address()))
  660. ++nc.capabilityCount;
  661. if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  662. break;
  663. }
  664. }
  665. }
  666. if (memberTags.is_array()) {
  667. std::map< uint32_t,uint32_t > tagsById;
  668. for(unsigned long i=0;i<memberTags.size();++i) {
  669. json &t = memberTags[i];
  670. if ((t.is_array())&&(t.size() == 2))
  671. tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
  672. }
  673. for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
  674. if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
  675. break;
  676. nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  677. if (nc.tags[nc.tagCount].sign(signingId))
  678. ++nc.tagCount;
  679. }
  680. }
  681. if (routes.is_array()) {
  682. for(unsigned long i=0;i<routes.size();++i) {
  683. if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
  684. break;
  685. json &route = routes[i];
  686. json &target = route["target"];
  687. json &via = route["via"];
  688. if (target.is_string()) {
  689. const InetAddress t(target.get<std::string>());
  690. InetAddress v;
  691. if (via.is_string()) v.fromString(via.get<std::string>());
  692. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  693. ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
  694. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  695. if (v.ss_family == t.ss_family)
  696. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  697. ++nc.routeCount;
  698. }
  699. }
  700. }
  701. }
  702. const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
  703. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  704. if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  705. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  706. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  707. }
  708. if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  709. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  710. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  711. }
  712. }
  713. bool haveManagedIpv4AutoAssignment = false;
  714. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  715. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  716. if (ipAssignments.is_array()) {
  717. for(unsigned long i=0;i<ipAssignments.size();++i) {
  718. if (!ipAssignments[i].is_string())
  719. continue;
  720. std::string ips = ipAssignments[i];
  721. InetAddress ip(ips);
  722. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  723. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  724. // of user error / poor UX.
  725. int routedNetmaskBits = 0;
  726. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  727. if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
  728. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  729. }
  730. if (routedNetmaskBits > 0) {
  731. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  732. ip.setPort(routedNetmaskBits);
  733. nc.staticIps[nc.staticIpCount++] = ip;
  734. }
  735. if (ip.ss_family == AF_INET)
  736. haveManagedIpv4AutoAssignment = true;
  737. else if (ip.ss_family == AF_INET6)
  738. haveManagedIpv6AutoAssignment = true;
  739. }
  740. }
  741. } else {
  742. ipAssignments = json::array();
  743. }
  744. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  745. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  746. json &pool = ipAssignmentPools[p];
  747. if (pool.is_object()) {
  748. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  749. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  750. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  751. uint64_t s[2],e[2],x[2],xx[2];
  752. memcpy(s,ipRangeStart.rawIpData(),16);
  753. memcpy(e,ipRangeEnd.rawIpData(),16);
  754. s[0] = Utils::ntoh(s[0]);
  755. s[1] = Utils::ntoh(s[1]);
  756. e[0] = Utils::ntoh(e[0]);
  757. e[1] = Utils::ntoh(e[1]);
  758. x[0] = s[0];
  759. x[1] = s[1];
  760. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  761. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  762. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  763. xx[0] = Utils::hton(x[0]);
  764. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  765. } else {
  766. // 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
  767. Utils::getSecureRandom((void *)xx,16);
  768. if ((e[0] > s[0]))
  769. xx[0] %= (e[0] - s[0]);
  770. else xx[0] = 0;
  771. if ((e[1] > s[1]))
  772. xx[1] %= (e[1] - s[1]);
  773. else xx[1] = 0;
  774. xx[0] = Utils::hton(x[0] + xx[0]);
  775. xx[1] = Utils::hton(x[1] + xx[1]);
  776. }
  777. InetAddress ip6((const void *)xx,16,0);
  778. // Check if this IP is within a local-to-Ethernet routed network
  779. int routedNetmaskBits = 0;
  780. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  781. 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)) )
  782. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  783. }
  784. // If it's routed, then try to claim and assign it and if successful end loop
  785. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
  786. ipAssignments.push_back(ip6.toIpString());
  787. member["ipAssignments"] = ipAssignments;
  788. ip6.setPort((unsigned int)routedNetmaskBits);
  789. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  790. nc.staticIps[nc.staticIpCount++] = ip6;
  791. haveManagedIpv6AutoAssignment = true;
  792. break;
  793. }
  794. }
  795. }
  796. }
  797. }
  798. }
  799. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  800. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  801. json &pool = ipAssignmentPools[p];
  802. if (pool.is_object()) {
  803. InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
  804. InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
  805. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  806. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  807. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  808. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  809. continue;
  810. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  811. // Start with the LSB of the member's address
  812. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  813. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  814. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  815. ++ipTrialCounter;
  816. if ((ip & 0x000000ff) == 0x000000ff)
  817. continue; // don't allow addresses that end in .255
  818. // Check if this IP is within a local-to-Ethernet routed network
  819. int routedNetmaskBits = -1;
  820. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  821. if (nc.routes[rk].target.ss_family == AF_INET) {
  822. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
  823. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
  824. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  825. routedNetmaskBits = targetBits;
  826. break;
  827. }
  828. }
  829. }
  830. // If it's routed, then try to claim and assign it and if successful end loop
  831. const InetAddress ip4(Utils::hton(ip),0);
  832. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
  833. ipAssignments.push_back(ip4.toIpString());
  834. member["ipAssignments"] = ipAssignments;
  835. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  836. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
  837. v4ip->sin_family = AF_INET;
  838. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  839. v4ip->sin_addr.s_addr = Utils::hton(ip);
  840. }
  841. haveManagedIpv4AutoAssignment = true;
  842. break;
  843. }
  844. }
  845. }
  846. }
  847. }
  848. }
  849. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  850. if (com.sign(signingId)) {
  851. nc.com = com;
  852. } else {
  853. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  854. }
  855. {
  856. Mutex::Lock _l(_db_m);
  857. _db.put("network",nwids,"member",identity.address().toString(),member);
  858. }
  859. return NetworkController::NETCONF_QUERY_OK;
  860. }
  861. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  862. const std::vector<std::string> &path,
  863. const std::map<std::string,std::string> &urlArgs,
  864. const std::map<std::string,std::string> &headers,
  865. const std::string &body,
  866. std::string &responseBody,
  867. std::string &responseContentType)
  868. {
  869. if ((path.size() > 0)&&(path[0] == "network")) {
  870. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  871. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  872. char nwids[24];
  873. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  874. json network;
  875. {
  876. Mutex::Lock _l(_db_m);
  877. network = _db.get("network",nwids,0);
  878. }
  879. if (!network.size())
  880. return 404;
  881. if (path.size() >= 3) {
  882. if (path[2] == "member") {
  883. if (path.size() >= 4) {
  884. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  885. json member;
  886. {
  887. Mutex::Lock _l(_db_m);
  888. member = _db.get("network",nwids,"member",Address(address).toString(),0);
  889. }
  890. if (!member.size())
  891. return 404;
  892. _addMemberNonPersistedFields(member,OSUtils::now());
  893. responseBody = member.dump(2);
  894. responseContentType = "application/json";
  895. return 200;
  896. } else {
  897. Mutex::Lock _l(_db_m);
  898. responseBody = "{";
  899. std::string pfx(std::string("network/") + nwids + "member/");
  900. _db.filter(pfx,120000,[&responseBody](const std::string &n,const json &member) {
  901. if (member.size() > 0) {
  902. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  903. responseBody.append(_jS(member["id"],""));
  904. responseBody.append("\":");
  905. responseBody.append(_jS(member["revision"],"0"));
  906. }
  907. return true; // never delete
  908. });
  909. responseBody.push_back('}');
  910. responseContentType = "application/json";
  911. return 200;
  912. }
  913. } else if ((path[2] == "test")&&(path.size() >= 4)) {
  914. Mutex::Lock _l(_circuitTests_m);
  915. std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
  916. if ((cte != _circuitTests.end())&&(cte->second.test)) {
  917. responseBody = "[";
  918. responseBody.append(cte->second.jsonResults);
  919. responseBody.push_back(']');
  920. responseContentType = "application/json";
  921. return 200;
  922. } // else 404
  923. } // else 404
  924. } else {
  925. const uint64_t now = OSUtils::now();
  926. _NetworkMemberInfo nmi;
  927. _getNetworkMemberInfo(now,nwid,nmi);
  928. _addNetworkNonPersistedFields(network,now,nmi);
  929. responseBody = network.dump(2);
  930. responseContentType = "application/json";
  931. return 200;
  932. }
  933. } else if (path.size() == 1) {
  934. std::set<std::string> networkIds;
  935. {
  936. Mutex::Lock _l(_db_m);
  937. _db.filter("network/",120000,[&networkIds](const std::string &n,const json &obj) {
  938. if (n.length() == (16 + 8))
  939. networkIds.insert(n.substr(8));
  940. return true; // do not delete
  941. });
  942. }
  943. responseBody.push_back('[');
  944. for(std::set<std::string>::iterator i(networkIds.begin());i!=networkIds.end();++i) {
  945. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  946. responseBody.append(*i);
  947. responseBody.append("\"");
  948. }
  949. responseBody.push_back(']');
  950. responseContentType = "application/json";
  951. return 200;
  952. } // else 404
  953. } else {
  954. char tmp[4096];
  955. 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());
  956. responseBody = tmp;
  957. responseContentType = "application/json";
  958. return 200;
  959. }
  960. return 404;
  961. }
  962. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  963. const std::vector<std::string> &path,
  964. const std::map<std::string,std::string> &urlArgs,
  965. const std::map<std::string,std::string> &headers,
  966. const std::string &body,
  967. std::string &responseBody,
  968. std::string &responseContentType)
  969. {
  970. if (path.empty())
  971. return 404;
  972. json b;
  973. try {
  974. b = json::parse(body);
  975. if (!b.is_object()) {
  976. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  977. responseContentType = "application/json";
  978. return 400;
  979. }
  980. } catch ( ... ) {
  981. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  982. responseContentType = "application/json";
  983. return 400;
  984. }
  985. const uint64_t now = OSUtils::now();
  986. if (path[0] == "network") {
  987. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  988. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  989. char nwids[24];
  990. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  991. if (path.size() >= 3) {
  992. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  993. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  994. char addrs[24];
  995. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  996. json member;
  997. {
  998. Mutex::Lock _l(_db_m);
  999. member = _db.get("network",nwids,"member",Address(address).toString(),0);
  1000. }
  1001. _initMember(member);
  1002. try {
  1003. if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
  1004. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
  1005. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  1006. if (b.count("authorized")) {
  1007. const bool newAuth = _jB(b["authorized"],false);
  1008. if (newAuth != _jB(member["authorized"],false)) {
  1009. member["authorized"] = newAuth;
  1010. json ah;
  1011. ah["a"] = newAuth;
  1012. ah["by"] = "api";
  1013. ah["ts"] = now;
  1014. ah["ct"] = json();
  1015. ah["c"] = json();
  1016. member["authHistory"].push_back(ah);
  1017. }
  1018. }
  1019. if (b.count("ipAssignments")) {
  1020. json &ipa = b["ipAssignments"];
  1021. if (ipa.is_array()) {
  1022. json mipa(json::array());
  1023. for(unsigned long i=0;i<ipa.size();++i) {
  1024. std::string ips = ipa[i];
  1025. InetAddress ip(ips);
  1026. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1027. mipa.push_back(ip.toIpString());
  1028. }
  1029. }
  1030. member["ipAssignments"] = mipa;
  1031. }
  1032. }
  1033. if (b.count("tags")) {
  1034. json &tags = b["tags"];
  1035. if (tags.is_array()) {
  1036. std::map<uint64_t,uint64_t> mtags;
  1037. for(unsigned long i=0;i<tags.size();++i) {
  1038. json &tag = tags[i];
  1039. if ((tag.is_array())&&(tag.size() == 2))
  1040. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  1041. }
  1042. json mtagsa = json::array();
  1043. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1044. json ta = json::array();
  1045. ta.push_back(t->first);
  1046. ta.push_back(t->second);
  1047. mtagsa.push_back(ta);
  1048. }
  1049. member["tags"] = mtagsa;
  1050. }
  1051. }
  1052. if (b.count("capabilities")) {
  1053. json &capabilities = b["capabilities"];
  1054. if (capabilities.is_array()) {
  1055. json mcaps = json::array();
  1056. for(unsigned long i=0;i<capabilities.size();++i) {
  1057. mcaps.push_back(_jI(capabilities[i],0ULL));
  1058. }
  1059. std::sort(mcaps.begin(),mcaps.end());
  1060. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1061. member["capabilities"] = mcaps;
  1062. }
  1063. }
  1064. } catch ( ... ) {
  1065. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  1066. responseContentType = "application/json";
  1067. return 400;
  1068. }
  1069. member["id"] = addrs;
  1070. member["address"] = addrs; // legacy
  1071. member["nwid"] = nwids;
  1072. member["lastModified"] = now;
  1073. json &revj = member["revision"];
  1074. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  1075. {
  1076. Mutex::Lock _l(_db_m);
  1077. _db.put("network",nwids,"member",Address(address).toString(),member);
  1078. }
  1079. // Add non-persisted fields
  1080. member["clock"] = now;
  1081. responseBody = member.dump(2);
  1082. responseContentType = "application/json";
  1083. return 200;
  1084. } else if ((path.size() == 3)&&(path[2] == "test")) {
  1085. Mutex::Lock _l(_circuitTests_m);
  1086. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  1087. memset(test,0,sizeof(ZT_CircuitTest));
  1088. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  1089. test->credentialNetworkId = nwid;
  1090. test->ptr = (void *)this;
  1091. json hops = b["hops"];
  1092. if (hops.is_array()) {
  1093. for(unsigned long i=0;i<hops.size();++i) {
  1094. json &hops2 = hops[i];
  1095. if (hops2.is_array()) {
  1096. for(unsigned long j=0;j<hops2.size();++j) {
  1097. std::string s = hops2[j];
  1098. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1099. }
  1100. } else if (hops2.is_string()) {
  1101. std::string s = hops2;
  1102. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1103. }
  1104. }
  1105. }
  1106. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1107. if (!test->hopCount) {
  1108. ::free((void *)test);
  1109. responseBody = "{ \"message\": \"a test must contain at least one hop\" }";
  1110. responseContentType = "application/json";
  1111. return 400;
  1112. }
  1113. test->timestamp = OSUtils::now();
  1114. _CircuitTestEntry &te = _circuitTests[test->testId];
  1115. te.test = test;
  1116. te.jsonResults = "";
  1117. if (_node)
  1118. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1119. else return 500;
  1120. char json[1024];
  1121. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1122. responseBody = json;
  1123. responseContentType = "application/json";
  1124. return 200;
  1125. } // else 404
  1126. } else {
  1127. // POST to network ID
  1128. json network;
  1129. {
  1130. Mutex::Lock _l(_db_m);
  1131. // Magic ID ending with ______ picks a random unused network ID
  1132. if (path[1].substr(10) == "______") {
  1133. nwid = 0;
  1134. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1135. uint64_t nwidPostfix = 0;
  1136. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1137. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1138. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1139. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1140. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1141. if (_db.get("network",nwids,120000).size() <= 0) {
  1142. nwid = tryNwid;
  1143. break;
  1144. }
  1145. }
  1146. if (!nwid)
  1147. return 503;
  1148. }
  1149. network = _db.get("network",nwids,0);
  1150. }
  1151. _initNetwork(network);
  1152. try {
  1153. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1154. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1155. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1156. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1157. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1158. if (b.count("v4AssignMode")) {
  1159. json nv4m;
  1160. json &v4m = b["v4AssignMode"];
  1161. if (v4m.is_string()) { // backward compatibility
  1162. nv4m["zt"] = (_jS(v4m,"") == "zt");
  1163. } else if (v4m.is_object()) {
  1164. nv4m["zt"] = _jB(v4m["zt"],false);
  1165. } else nv4m["zt"] = false;
  1166. network["v4AssignMode"] = nv4m;
  1167. }
  1168. if (b.count("v6AssignMode")) {
  1169. json nv6m;
  1170. json &v6m = b["v6AssignMode"];
  1171. if (!nv6m.is_object()) nv6m = json::object();
  1172. if (v6m.is_string()) { // backward compatibility
  1173. std::vector<std::string> v6ms(Utils::split(_jS(v6m,"").c_str(),",","",""));
  1174. std::sort(v6ms.begin(),v6ms.end());
  1175. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  1176. nv6m["rfc4193"] = false;
  1177. nv6m["zt"] = false;
  1178. nv6m["6plane"] = false;
  1179. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  1180. if (*i == "rfc4193")
  1181. nv6m["rfc4193"] = true;
  1182. else if (*i == "zt")
  1183. nv6m["zt"] = true;
  1184. else if (*i == "6plane")
  1185. nv6m["6plane"] = true;
  1186. }
  1187. } else if (v6m.is_object()) {
  1188. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1189. if (v6m.count("zt")) nv6m["zt"] = _jB(v6m["zt"],false);
  1190. if (v6m.count("6plane")) nv6m["6plane"] = _jB(v6m["6plane"],false);
  1191. } else {
  1192. nv6m["rfc4193"] = false;
  1193. nv6m["zt"] = false;
  1194. nv6m["6plane"] = false;
  1195. }
  1196. network["v6AssignMode"] = nv6m;
  1197. }
  1198. if (b.count("routes")) {
  1199. json &rts = b["routes"];
  1200. if (rts.is_array()) {
  1201. json nrts = json::array();
  1202. for(unsigned long i=0;i<rts.size();++i) {
  1203. json &rt = rts[i];
  1204. if (rt.is_object()) {
  1205. json &target = rt["target"];
  1206. json &via = rt["via"];
  1207. if (target.is_string()) {
  1208. InetAddress t(target.get<std::string>());
  1209. InetAddress v;
  1210. if (via.is_string()) v.fromString(via.get<std::string>());
  1211. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  1212. json tmp;
  1213. tmp["target"] = t.toString();
  1214. if (v.ss_family == t.ss_family)
  1215. tmp["via"] = v.toIpString();
  1216. else tmp["via"] = json();
  1217. nrts.push_back(tmp);
  1218. }
  1219. }
  1220. }
  1221. }
  1222. network["routes"] = nrts;
  1223. }
  1224. }
  1225. if (b.count("ipAssignmentPools")) {
  1226. json &ipp = b["ipAssignmentPools"];
  1227. if (ipp.is_array()) {
  1228. json nipp = json::array();
  1229. for(unsigned long i=0;i<ipp.size();++i) {
  1230. json &ip = ipp[i];
  1231. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1232. InetAddress f(_jS(ip["ipRangeStart"],""));
  1233. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1234. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1235. json tmp = json::object();
  1236. tmp["ipRangeStart"] = f.toIpString();
  1237. tmp["ipRangeEnd"] = t.toIpString();
  1238. nipp.push_back(tmp);
  1239. }
  1240. }
  1241. }
  1242. network["ipAssignmentPools"] = nipp;
  1243. }
  1244. }
  1245. if (b.count("rules")) {
  1246. json &rules = b["rules"];
  1247. if (rules.is_array()) {
  1248. json nrules = json::array();
  1249. for(unsigned long i=0;i<rules.size();++i) {
  1250. json &rule = rules[i];
  1251. if (rule.is_object()) {
  1252. ZT_VirtualNetworkRule ztr;
  1253. if (_parseRule(rule,ztr))
  1254. nrules.push_back(_renderRule(ztr));
  1255. }
  1256. }
  1257. network["rules"] = nrules;
  1258. }
  1259. }
  1260. if (b.count("authTokens")) {
  1261. json &authTokens = b["authTokens"];
  1262. if (authTokens.is_array()) {
  1263. json nat = json::array();
  1264. for(unsigned long i=0;i<authTokens.size();++i) {
  1265. json &token = authTokens[i];
  1266. if (token.is_object()) {
  1267. std::string tstr = token["token"];
  1268. if (tstr.length() > 0) {
  1269. json t = json::object();
  1270. t["token"] = tstr;
  1271. t["expires"] = _jI(token["expires"],0ULL);
  1272. t["maxUsesPerMember"] = _jI(token["maxUsesPerMember"],0ULL);
  1273. nat.push_back(t);
  1274. }
  1275. }
  1276. }
  1277. network["authTokens"] = nat;
  1278. }
  1279. }
  1280. if (b.count("capabilities")) {
  1281. json &capabilities = b["capabilities"];
  1282. if (capabilities.is_array()) {
  1283. std::map< uint64_t,json > ncaps;
  1284. for(unsigned long i=0;i<capabilities.size();++i) {
  1285. json &cap = capabilities[i];
  1286. if (cap.is_object()) {
  1287. json ncap = json::object();
  1288. const uint64_t capId = _jI(cap["id"],0ULL);
  1289. ncap["id"] = capId;
  1290. json &rules = cap["rules"];
  1291. json nrules = json::array();
  1292. if (rules.is_array()) {
  1293. for(unsigned long i=0;i<rules.size();++i) {
  1294. json &rule = rules[i];
  1295. if (rule.is_object()) {
  1296. ZT_VirtualNetworkRule ztr;
  1297. if (_parseRule(rule,ztr))
  1298. nrules.push_back(_renderRule(ztr));
  1299. }
  1300. }
  1301. }
  1302. ncap["rules"] = nrules;
  1303. ncaps[capId] = ncap;
  1304. }
  1305. }
  1306. json ncapsa = json::array();
  1307. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1308. ncapsa.push_back(c->second);
  1309. network["capabilities"] = ncapsa;
  1310. }
  1311. }
  1312. } catch ( ... ) {
  1313. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  1314. responseContentType = "application/json";
  1315. return 400;
  1316. }
  1317. network["id"] = nwids;
  1318. network["nwid"] = nwids; // legacy
  1319. json &rev = network["revision"];
  1320. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1321. network["lastModified"] = now;
  1322. {
  1323. Mutex::Lock _l(_db_m);
  1324. _db.put("network",nwids,network);
  1325. }
  1326. _NetworkMemberInfo nmi;
  1327. _getNetworkMemberInfo(now,nwid,nmi);
  1328. _addNetworkNonPersistedFields(network,now,nmi);
  1329. responseBody = network.dump(2);
  1330. responseContentType = "application/json";
  1331. return 200;
  1332. } // else 404
  1333. } // else 404
  1334. } // else 404
  1335. return 404;
  1336. }
  1337. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1338. const std::vector<std::string> &path,
  1339. const std::map<std::string,std::string> &urlArgs,
  1340. const std::map<std::string,std::string> &headers,
  1341. const std::string &body,
  1342. std::string &responseBody,
  1343. std::string &responseContentType)
  1344. {
  1345. if (path.empty())
  1346. return 404;
  1347. if (path[0] == "network") {
  1348. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1349. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1350. char nwids[24];
  1351. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  1352. json network;
  1353. {
  1354. Mutex::Lock _l(_db_m);
  1355. network = _db.get("network",nwids,0);
  1356. }
  1357. if (!network.size())
  1358. return 404;
  1359. if (path.size() >= 3) {
  1360. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1361. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1362. Mutex::Lock _l(_db_m);
  1363. json member = _db.get("network",nwids,"member",Address(address).toString(),0);
  1364. _db.erase("network",nwids,"member",Address(address).toString());
  1365. if (!member.size())
  1366. return 404;
  1367. responseBody = member.dump(2);
  1368. responseContentType = "application/json";
  1369. return 200;
  1370. }
  1371. } else {
  1372. Mutex::Lock _l(_db_m);
  1373. std::string pfx("network/"); pfx.append(nwids);
  1374. _db.filter(pfx,120000,[](const std::string &n,const json &obj) {
  1375. return false; // delete
  1376. });
  1377. responseBody = network.dump(2);
  1378. responseContentType = "application/json";
  1379. return 200;
  1380. }
  1381. } // else 404
  1382. } // else 404
  1383. return 404;
  1384. }
  1385. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1386. {
  1387. char tmp[65535];
  1388. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1389. if (!test)
  1390. return;
  1391. if (!report)
  1392. return;
  1393. Mutex::Lock _l(self->_circuitTests_m);
  1394. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1395. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1396. self->_node->circuitTestEnd(test);
  1397. ::free((void *)test);
  1398. return;
  1399. }
  1400. Utils::snprintf(tmp,sizeof(tmp),
  1401. "%s{\n"
  1402. "\t\"timestamp\": %llu," ZT_EOL_S
  1403. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1404. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1405. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1406. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1407. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1408. "\t\"flags\": %llu," ZT_EOL_S
  1409. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1410. "\t\"errorCode\": %u," ZT_EOL_S
  1411. "\t\"vendor\": %d," ZT_EOL_S
  1412. "\t\"protocolVersion\": %u," ZT_EOL_S
  1413. "\t\"majorVersion\": %u," ZT_EOL_S
  1414. "\t\"minorVersion\": %u," ZT_EOL_S
  1415. "\t\"revision\": %u," ZT_EOL_S
  1416. "\t\"platform\": %d," ZT_EOL_S
  1417. "\t\"architecture\": %d," ZT_EOL_S
  1418. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1419. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1420. "}",
  1421. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1422. (unsigned long long)report->timestamp,
  1423. (unsigned long long)test->testId,
  1424. (unsigned long long)report->upstream,
  1425. (unsigned long long)report->current,
  1426. (unsigned long long)OSUtils::now(),
  1427. (unsigned long long)report->sourcePacketId,
  1428. (unsigned long long)report->flags,
  1429. report->sourcePacketHopCount,
  1430. report->errorCode,
  1431. (int)report->vendor,
  1432. report->protocolVersion,
  1433. report->majorVersion,
  1434. report->minorVersion,
  1435. report->revision,
  1436. (int)report->platform,
  1437. (int)report->architecture,
  1438. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1439. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1440. cte->second.jsonResults.append(tmp);
  1441. }
  1442. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1443. {
  1444. char pfx[256];
  1445. Utils::snprintf(pfx,sizeof(pfx),"network/%.16llx/member",nwid);
  1446. Mutex::Lock _l(_db_m);
  1447. _db.filter(pfx,120000,[&nmi,&now](const std::string &n,const json &member) {
  1448. try {
  1449. if (_jB(member["authorized"],false)) {
  1450. ++nmi.authorizedMemberCount;
  1451. if (member.count("recentLog")) {
  1452. const json &mlog = member["recentLog"];
  1453. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1454. const json &mlog1 = mlog[0];
  1455. if (mlog1.is_object()) {
  1456. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1457. ++nmi.activeMemberCount;
  1458. }
  1459. }
  1460. }
  1461. if (_jB(member["activeBridge"],false)) {
  1462. nmi.activeBridges.insert(_jS(member["id"],"0000000000"));
  1463. }
  1464. if (member.count("ipAssignments")) {
  1465. const json &mips = member["ipAssignments"];
  1466. if (mips.is_array()) {
  1467. for(unsigned long i=0;i<mips.size();++i) {
  1468. InetAddress mip(_jS(mips[i],""));
  1469. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1470. nmi.allocatedIps.insert(mip);
  1471. }
  1472. }
  1473. }
  1474. } else {
  1475. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(member["lastDeauthorizedTime"],0ULL));
  1476. }
  1477. } catch ( ... ) {}
  1478. return true;
  1479. });
  1480. }
  1481. } // namespace ZeroTier