EmbeddedNetworkController.cpp 57 KB

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