EmbeddedNetworkController.cpp 59 KB

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