EmbeddedNetworkController.cpp 59 KB

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