EmbeddedNetworkController.cpp 58 KB

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