EmbeddedNetworkController.cpp 56 KB

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