EmbeddedNetworkController.cpp 62 KB

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