EmbeddedNetworkController.cpp 63 KB

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