EmbeddedNetworkController.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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. void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
  448. {
  449. this->_sender = sender;
  450. this->_signingId = signingId;
  451. }
  452. void EmbeddedNetworkController::request(
  453. uint64_t nwid,
  454. const InetAddress &fromAddr,
  455. uint64_t requestPacketId,
  456. const Identity &identity,
  457. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  458. {
  459. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  460. return;
  461. const uint64_t now = OSUtils::now();
  462. // Check rate limit circuit breaker to prevent flooding
  463. {
  464. Mutex::Lock _l(_lastRequestTime_m);
  465. uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
  466. if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  467. return;
  468. lrt = now;
  469. }
  470. char nwids[24];
  471. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  472. json network;
  473. json member;
  474. {
  475. Mutex::Lock _l(_db_m);
  476. network = _db.get("network",nwids,0);
  477. member = _db.get("network",nwids,"member",identity.address().toString(),0);
  478. }
  479. if (!network.size()) {
  480. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND);
  481. return;
  482. }
  483. json origMember(member); // for detecting modification later
  484. _initMember(member);
  485. {
  486. std::string haveIdStr(_jS(member["identity"],""));
  487. if (haveIdStr.length() > 0) {
  488. // If we already know this member's identity perform a full compare. This prevents
  489. // a "collision" from being able to auth onto our network in place of an already
  490. // known member.
  491. try {
  492. if (Identity(haveIdStr.c_str()) != identity) {
  493. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  494. return;
  495. }
  496. } catch ( ... ) {
  497. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  498. return;
  499. }
  500. } else {
  501. // If we do not yet know this member's identity, learn it.
  502. member["identity"] = identity.toString(false);
  503. }
  504. }
  505. // These are always the same, but make sure they are set
  506. member["id"] = identity.address().toString();
  507. member["address"] = member["id"];
  508. member["nwid"] = nwids;
  509. // Determine whether and how member is authorized
  510. const char *authorizedBy = (const char *)0;
  511. if (_jB(member["authorized"],false)) {
  512. authorizedBy = "memberIsAuthorized";
  513. } else if (!_jB(network["private"],true)) {
  514. authorizedBy = "networkIsPublic";
  515. if (!member.count("authorized")) {
  516. member["authorized"] = true;
  517. json ah;
  518. ah["a"] = true;
  519. ah["by"] = authorizedBy;
  520. ah["ts"] = now;
  521. ah["ct"] = json();
  522. ah["c"] = json();
  523. member["authHistory"].push_back(ah);
  524. member["lastModified"] = now;
  525. json &revj = member["revision"];
  526. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  527. }
  528. } else {
  529. char presentedAuth[512];
  530. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  531. presentedAuth[511] = (char)0; // sanity check
  532. // Check for bearer token presented by member
  533. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  534. const char *const presentedToken = presentedAuth + 6;
  535. json &authTokens = network["authTokens"];
  536. if (authTokens.is_array()) {
  537. for(unsigned long i=0;i<authTokens.size();++i) {
  538. json &token = authTokens[i];
  539. if (token.is_object()) {
  540. const uint64_t expires = _jI(token["expires"],0ULL);
  541. const uint64_t maxUses = _jI(token["maxUsesPerMember"],0ULL);
  542. std::string tstr = _jS(token["token"],"");
  543. if (((expires == 0ULL)||(expires > now))&&(tstr == presentedToken)) {
  544. bool usable = (maxUses == 0);
  545. if (!usable) {
  546. uint64_t useCount = 0;
  547. json &ahist = member["authHistory"];
  548. if (ahist.is_array()) {
  549. for(unsigned long j=0;j<ahist.size();++j) {
  550. json &ah = ahist[j];
  551. if ((_jS(ah["ct"],"") == "token")&&(_jS(ah["c"],"") == tstr)&&(_jB(ah["a"],false)))
  552. ++useCount;
  553. }
  554. }
  555. usable = (useCount < maxUses);
  556. }
  557. if (usable) {
  558. authorizedBy = "token";
  559. member["authorized"] = true;
  560. json ah;
  561. ah["a"] = true;
  562. ah["by"] = authorizedBy;
  563. ah["ts"] = now;
  564. ah["ct"] = "token";
  565. ah["c"] = tstr;
  566. member["authHistory"].push_back(ah);
  567. member["lastModified"] = now;
  568. json &revj = member["revision"];
  569. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  570. }
  571. }
  572. }
  573. }
  574. }
  575. }
  576. }
  577. }
  578. // Log this request
  579. if (requestPacketId) { // only log if this is a request, not for generated pushes
  580. json rlEntry = json::object();
  581. rlEntry["ts"] = now;
  582. rlEntry["authorized"] = (authorizedBy) ? true : false;
  583. rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
  584. rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  585. rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  586. rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  587. rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  588. if (fromAddr)
  589. rlEntry["fromAddr"] = fromAddr.toString();
  590. json recentLog = json::array();
  591. recentLog.push_back(rlEntry);
  592. json &oldLog = member["recentLog"];
  593. if (oldLog.is_array()) {
  594. for(unsigned long i=0;i<oldLog.size();++i) {
  595. recentLog.push_back(oldLog[i]);
  596. if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
  597. break;
  598. }
  599. }
  600. member["recentLog"] = recentLog;
  601. // Also only do this on real requests
  602. member["lastRequestMetaData"] = metaData.data();
  603. }
  604. // If they are not authorized, STOP!
  605. if (!authorizedBy) {
  606. if (origMember != member) {
  607. member["lastModified"] = now;
  608. Mutex::Lock _l(_db_m);
  609. _db.put("network",nwids,"member",identity.address().toString(),member);
  610. }
  611. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
  612. return;
  613. }
  614. // -------------------------------------------------------------------------
  615. // If we made it this far, they are authorized.
  616. // -------------------------------------------------------------------------
  617. NetworkConfig nc;
  618. _NetworkMemberInfo nmi;
  619. _getNetworkMemberInfo(now,nwid,nmi);
  620. // Compute credential TTL. This is the "moving window" for COM agreement and
  621. // the global TTL for Capability and Tag objects. (The same value is used
  622. // for both.) This is computed by reference to the last time we deauthorized
  623. // a member, since within the time period since this event any temporal
  624. // differences are not particularly relevant.
  625. uint64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA;
  626. if (now > nmi.mostRecentDeauthTime)
  627. credentialtmd += (now - nmi.mostRecentDeauthTime);
  628. if (credentialtmd > ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA)
  629. credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA;
  630. nc.networkId = nwid;
  631. nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  632. nc.timestamp = now;
  633. nc.credentialTimeMaxDelta = credentialtmd;
  634. nc.revision = _jI(network["revision"],0ULL);
  635. nc.issuedTo = identity.address();
  636. if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  637. if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  638. Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
  639. nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
  640. for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab) {
  641. nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  642. }
  643. json &v4AssignMode = network["v4AssignMode"];
  644. json &v6AssignMode = network["v6AssignMode"];
  645. json &ipAssignmentPools = network["ipAssignmentPools"];
  646. json &routes = network["routes"];
  647. json &rules = network["rules"];
  648. json &capabilities = network["capabilities"];
  649. json &memberCapabilities = member["capabilities"];
  650. json &memberTags = member["tags"];
  651. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  652. // Old versions with no rules engine support get an allow everything rule.
  653. // Since rules are enforced bidirectionally, newer versions *will* still
  654. // enforce rules on the inbound side.
  655. nc.ruleCount = 1;
  656. nc.rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  657. } else {
  658. if (rules.is_array()) {
  659. for(unsigned long i=0;i<rules.size();++i) {
  660. if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
  661. break;
  662. if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
  663. ++nc.ruleCount;
  664. }
  665. }
  666. }
  667. if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
  668. std::map< uint64_t,json * > capsById;
  669. for(unsigned long i=0;i<capabilities.size();++i) {
  670. json &cap = capabilities[i];
  671. if (cap.is_object())
  672. capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = &cap;
  673. }
  674. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  675. const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
  676. json *cap = capsById[capId];
  677. if ((cap->is_object())&&(cap->size() > 0)) {
  678. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  679. unsigned int caprc = 0;
  680. json &caprj = (*cap)["rules"];
  681. if ((caprj.is_array())&&(caprj.size() > 0)) {
  682. for(unsigned long j=0;j<caprj.size();++j) {
  683. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  684. break;
  685. if (_parseRule(caprj[j],capr[caprc]))
  686. ++caprc;
  687. }
  688. }
  689. nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  690. if (nc.capabilities[nc.capabilityCount].sign(_signingId,identity.address()))
  691. ++nc.capabilityCount;
  692. if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  693. break;
  694. }
  695. }
  696. }
  697. if (memberTags.is_array()) {
  698. std::map< uint32_t,uint32_t > tagsById;
  699. for(unsigned long i=0;i<memberTags.size();++i) {
  700. json &t = memberTags[i];
  701. if ((t.is_array())&&(t.size() == 2))
  702. tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
  703. }
  704. for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
  705. if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
  706. break;
  707. nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  708. if (nc.tags[nc.tagCount].sign(_signingId))
  709. ++nc.tagCount;
  710. }
  711. }
  712. if (routes.is_array()) {
  713. for(unsigned long i=0;i<routes.size();++i) {
  714. if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
  715. break;
  716. json &route = routes[i];
  717. json &target = route["target"];
  718. json &via = route["via"];
  719. if (target.is_string()) {
  720. const InetAddress t(target.get<std::string>());
  721. InetAddress v;
  722. if (via.is_string()) v.fromString(via.get<std::string>());
  723. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  724. ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
  725. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  726. if (v.ss_family == t.ss_family)
  727. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  728. ++nc.routeCount;
  729. }
  730. }
  731. }
  732. }
  733. const bool noAutoAssignIps = _jB(member["noAutoAssignIps"],false);
  734. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  735. if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  736. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  737. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  738. }
  739. if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  740. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  741. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  742. }
  743. }
  744. bool haveManagedIpv4AutoAssignment = false;
  745. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  746. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  747. if (ipAssignments.is_array()) {
  748. for(unsigned long i=0;i<ipAssignments.size();++i) {
  749. if (!ipAssignments[i].is_string())
  750. continue;
  751. std::string ips = ipAssignments[i];
  752. InetAddress ip(ips);
  753. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  754. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  755. // of user error / poor UX.
  756. int routedNetmaskBits = 0;
  757. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  758. if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
  759. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  760. }
  761. if (routedNetmaskBits > 0) {
  762. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  763. ip.setPort(routedNetmaskBits);
  764. nc.staticIps[nc.staticIpCount++] = ip;
  765. }
  766. if (ip.ss_family == AF_INET)
  767. haveManagedIpv4AutoAssignment = true;
  768. else if (ip.ss_family == AF_INET6)
  769. haveManagedIpv6AutoAssignment = true;
  770. }
  771. }
  772. } else {
  773. ipAssignments = json::array();
  774. }
  775. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  776. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  777. json &pool = ipAssignmentPools[p];
  778. if (pool.is_object()) {
  779. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  780. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  781. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  782. uint64_t s[2],e[2],x[2],xx[2];
  783. memcpy(s,ipRangeStart.rawIpData(),16);
  784. memcpy(e,ipRangeEnd.rawIpData(),16);
  785. s[0] = Utils::ntoh(s[0]);
  786. s[1] = Utils::ntoh(s[1]);
  787. e[0] = Utils::ntoh(e[0]);
  788. e[1] = Utils::ntoh(e[1]);
  789. x[0] = s[0];
  790. x[1] = s[1];
  791. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  792. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  793. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  794. xx[0] = Utils::hton(x[0]);
  795. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  796. } else {
  797. // 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
  798. Utils::getSecureRandom((void *)xx,16);
  799. if ((e[0] > s[0]))
  800. xx[0] %= (e[0] - s[0]);
  801. else xx[0] = 0;
  802. if ((e[1] > s[1]))
  803. xx[1] %= (e[1] - s[1]);
  804. else xx[1] = 0;
  805. xx[0] = Utils::hton(x[0] + xx[0]);
  806. xx[1] = Utils::hton(x[1] + xx[1]);
  807. }
  808. InetAddress ip6((const void *)xx,16,0);
  809. // Check if this IP is within a local-to-Ethernet routed network
  810. int routedNetmaskBits = 0;
  811. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  812. 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)) )
  813. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  814. }
  815. // If it's routed, then try to claim and assign it and if successful end loop
  816. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
  817. ipAssignments.push_back(ip6.toIpString());
  818. member["ipAssignments"] = ipAssignments;
  819. ip6.setPort((unsigned int)routedNetmaskBits);
  820. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  821. nc.staticIps[nc.staticIpCount++] = ip6;
  822. haveManagedIpv6AutoAssignment = true;
  823. break;
  824. }
  825. }
  826. }
  827. }
  828. }
  829. }
  830. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  831. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  832. json &pool = ipAssignmentPools[p];
  833. if (pool.is_object()) {
  834. InetAddress ipRangeStartIA(_jS(pool["ipRangeStart"],""));
  835. InetAddress ipRangeEndIA(_jS(pool["ipRangeEnd"],""));
  836. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  837. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  838. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  839. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  840. continue;
  841. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  842. // Start with the LSB of the member's address
  843. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  844. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  845. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  846. ++ipTrialCounter;
  847. if ((ip & 0x000000ff) == 0x000000ff)
  848. continue; // don't allow addresses that end in .255
  849. // Check if this IP is within a local-to-Ethernet routed network
  850. int routedNetmaskBits = -1;
  851. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  852. if (nc.routes[rk].target.ss_family == AF_INET) {
  853. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
  854. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
  855. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  856. routedNetmaskBits = targetBits;
  857. break;
  858. }
  859. }
  860. }
  861. // If it's routed, then try to claim and assign it and if successful end loop
  862. const InetAddress ip4(Utils::hton(ip),0);
  863. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
  864. ipAssignments.push_back(ip4.toIpString());
  865. member["ipAssignments"] = ipAssignments;
  866. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  867. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
  868. v4ip->sin_family = AF_INET;
  869. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  870. v4ip->sin_addr.s_addr = Utils::hton(ip);
  871. }
  872. haveManagedIpv4AutoAssignment = true;
  873. break;
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. CertificateOfMembership com(now,credentialtmd,nwid,identity.address());
  881. if (com.sign(_signingId)) {
  882. nc.com = com;
  883. } else {
  884. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR);
  885. return;
  886. }
  887. if (member != origMember) {
  888. member["lastModified"] = now;
  889. Mutex::Lock _l(_db_m);
  890. _db.put("network",nwids,"member",identity.address().toString(),member);
  891. }
  892. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),nc,metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  893. }
  894. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  895. const std::vector<std::string> &path,
  896. const std::map<std::string,std::string> &urlArgs,
  897. const std::map<std::string,std::string> &headers,
  898. const std::string &body,
  899. std::string &responseBody,
  900. std::string &responseContentType)
  901. {
  902. if ((path.size() > 0)&&(path[0] == "network")) {
  903. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  904. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  905. char nwids[24];
  906. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  907. json network;
  908. {
  909. Mutex::Lock _l(_db_m);
  910. network = _db.get("network",nwids,0);
  911. }
  912. if (!network.size())
  913. return 404;
  914. if (path.size() >= 3) {
  915. if (path[2] == "member") {
  916. if (path.size() >= 4) {
  917. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  918. json member;
  919. {
  920. Mutex::Lock _l(_db_m);
  921. member = _db.get("network",nwids,"member",Address(address).toString(),0);
  922. }
  923. if (!member.size())
  924. return 404;
  925. _addMemberNonPersistedFields(member,OSUtils::now());
  926. responseBody = member.dump(2);
  927. responseContentType = "application/json";
  928. return 200;
  929. } else {
  930. Mutex::Lock _l(_db_m);
  931. responseBody = "{";
  932. std::string pfx(std::string("network/") + nwids + "member/");
  933. _db.filter(pfx,120000,[&responseBody](const std::string &n,const json &member) {
  934. if (member.size() > 0) {
  935. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  936. responseBody.append(_jS(member["id"],""));
  937. responseBody.append("\":");
  938. responseBody.append(_jS(member["revision"],"0"));
  939. }
  940. return true; // never delete
  941. });
  942. responseBody.push_back('}');
  943. responseContentType = "application/json";
  944. return 200;
  945. }
  946. } else if ((path[2] == "test")&&(path.size() >= 4)) {
  947. Mutex::Lock _l(_circuitTests_m);
  948. std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
  949. if ((cte != _circuitTests.end())&&(cte->second.test)) {
  950. responseBody = "[";
  951. responseBody.append(cte->second.jsonResults);
  952. responseBody.push_back(']');
  953. responseContentType = "application/json";
  954. return 200;
  955. } // else 404
  956. } // else 404
  957. } else {
  958. const uint64_t now = OSUtils::now();
  959. _NetworkMemberInfo nmi;
  960. _getNetworkMemberInfo(now,nwid,nmi);
  961. _addNetworkNonPersistedFields(network,now,nmi);
  962. responseBody = network.dump(2);
  963. responseContentType = "application/json";
  964. return 200;
  965. }
  966. } else if (path.size() == 1) {
  967. std::set<std::string> networkIds;
  968. {
  969. Mutex::Lock _l(_db_m);
  970. _db.filter("network/",120000,[&networkIds](const std::string &n,const json &obj) {
  971. if (n.length() == (16 + 8))
  972. networkIds.insert(n.substr(8));
  973. return true; // do not delete
  974. });
  975. }
  976. responseBody.push_back('[');
  977. for(std::set<std::string>::iterator i(networkIds.begin());i!=networkIds.end();++i) {
  978. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  979. responseBody.append(*i);
  980. responseBody.append("\"");
  981. }
  982. responseBody.push_back(']');
  983. responseContentType = "application/json";
  984. return 200;
  985. } // else 404
  986. } else {
  987. char tmp[4096];
  988. Utils::snprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now());
  989. responseBody = tmp;
  990. responseContentType = "application/json";
  991. return 200;
  992. }
  993. return 404;
  994. }
  995. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  996. const std::vector<std::string> &path,
  997. const std::map<std::string,std::string> &urlArgs,
  998. const std::map<std::string,std::string> &headers,
  999. const std::string &body,
  1000. std::string &responseBody,
  1001. std::string &responseContentType)
  1002. {
  1003. if (path.empty())
  1004. return 404;
  1005. json b;
  1006. try {
  1007. b = json::parse(body);
  1008. if (!b.is_object()) {
  1009. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  1010. responseContentType = "application/json";
  1011. return 400;
  1012. }
  1013. } catch ( ... ) {
  1014. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  1015. responseContentType = "application/json";
  1016. return 400;
  1017. }
  1018. const uint64_t now = OSUtils::now();
  1019. if (path[0] == "network") {
  1020. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1021. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1022. char nwids[24];
  1023. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  1024. if (path.size() >= 3) {
  1025. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1026. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1027. char addrs[24];
  1028. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  1029. json member;
  1030. {
  1031. Mutex::Lock _l(_db_m);
  1032. member = _db.get("network",nwids,"member",Address(address).toString(),0);
  1033. }
  1034. _initMember(member);
  1035. try {
  1036. if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
  1037. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
  1038. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  1039. if (b.count("authorized")) {
  1040. const bool newAuth = _jB(b["authorized"],false);
  1041. if (newAuth != _jB(member["authorized"],false)) {
  1042. member["authorized"] = newAuth;
  1043. json ah;
  1044. ah["a"] = newAuth;
  1045. ah["by"] = "api";
  1046. ah["ts"] = now;
  1047. ah["ct"] = json();
  1048. ah["c"] = json();
  1049. member["authHistory"].push_back(ah);
  1050. }
  1051. }
  1052. if (b.count("ipAssignments")) {
  1053. json &ipa = b["ipAssignments"];
  1054. if (ipa.is_array()) {
  1055. json mipa(json::array());
  1056. for(unsigned long i=0;i<ipa.size();++i) {
  1057. std::string ips = ipa[i];
  1058. InetAddress ip(ips);
  1059. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  1060. mipa.push_back(ip.toIpString());
  1061. }
  1062. }
  1063. member["ipAssignments"] = mipa;
  1064. }
  1065. }
  1066. if (b.count("tags")) {
  1067. json &tags = b["tags"];
  1068. if (tags.is_array()) {
  1069. std::map<uint64_t,uint64_t> mtags;
  1070. for(unsigned long i=0;i<tags.size();++i) {
  1071. json &tag = tags[i];
  1072. if ((tag.is_array())&&(tag.size() == 2))
  1073. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  1074. }
  1075. json mtagsa = json::array();
  1076. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  1077. json ta = json::array();
  1078. ta.push_back(t->first);
  1079. ta.push_back(t->second);
  1080. mtagsa.push_back(ta);
  1081. }
  1082. member["tags"] = mtagsa;
  1083. }
  1084. }
  1085. if (b.count("capabilities")) {
  1086. json &capabilities = b["capabilities"];
  1087. if (capabilities.is_array()) {
  1088. json mcaps = json::array();
  1089. for(unsigned long i=0;i<capabilities.size();++i) {
  1090. mcaps.push_back(_jI(capabilities[i],0ULL));
  1091. }
  1092. std::sort(mcaps.begin(),mcaps.end());
  1093. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  1094. member["capabilities"] = mcaps;
  1095. }
  1096. }
  1097. } catch ( ... ) {
  1098. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  1099. responseContentType = "application/json";
  1100. return 400;
  1101. }
  1102. member["id"] = addrs;
  1103. member["address"] = addrs; // legacy
  1104. member["nwid"] = nwids;
  1105. member["lastModified"] = now;
  1106. json &revj = member["revision"];
  1107. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  1108. {
  1109. Mutex::Lock _l(_db_m);
  1110. _db.put("network",nwids,"member",Address(address).toString(),member);
  1111. }
  1112. // Add non-persisted fields
  1113. member["clock"] = now;
  1114. responseBody = member.dump(2);
  1115. responseContentType = "application/json";
  1116. return 200;
  1117. } else if ((path.size() == 3)&&(path[2] == "test")) {
  1118. Mutex::Lock _l(_circuitTests_m);
  1119. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  1120. memset(test,0,sizeof(ZT_CircuitTest));
  1121. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  1122. test->credentialNetworkId = nwid;
  1123. test->ptr = (void *)this;
  1124. json hops = b["hops"];
  1125. if (hops.is_array()) {
  1126. for(unsigned long i=0;i<hops.size();++i) {
  1127. json &hops2 = hops[i];
  1128. if (hops2.is_array()) {
  1129. for(unsigned long j=0;j<hops2.size();++j) {
  1130. std::string s = hops2[j];
  1131. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1132. }
  1133. } else if (hops2.is_string()) {
  1134. std::string s = hops2;
  1135. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1136. }
  1137. }
  1138. }
  1139. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1140. if (!test->hopCount) {
  1141. ::free((void *)test);
  1142. responseBody = "{ \"message\": \"a test must contain at least one hop\" }";
  1143. responseContentType = "application/json";
  1144. return 400;
  1145. }
  1146. test->timestamp = OSUtils::now();
  1147. _CircuitTestEntry &te = _circuitTests[test->testId];
  1148. te.test = test;
  1149. te.jsonResults = "";
  1150. if (_node)
  1151. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1152. else return 500;
  1153. char json[1024];
  1154. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1155. responseBody = json;
  1156. responseContentType = "application/json";
  1157. return 200;
  1158. } // else 404
  1159. } else {
  1160. // POST to network ID
  1161. json network;
  1162. {
  1163. Mutex::Lock _l(_db_m);
  1164. // Magic ID ending with ______ picks a random unused network ID
  1165. if (path[1].substr(10) == "______") {
  1166. nwid = 0;
  1167. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1168. uint64_t nwidPostfix = 0;
  1169. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1170. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1171. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1172. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1173. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1174. if (_db.get("network",nwids,120000).size() <= 0) {
  1175. nwid = tryNwid;
  1176. break;
  1177. }
  1178. }
  1179. if (!nwid)
  1180. return 503;
  1181. }
  1182. network = _db.get("network",nwids,0);
  1183. }
  1184. _initNetwork(network);
  1185. try {
  1186. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1187. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1188. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1189. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1190. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1191. if (b.count("v4AssignMode")) {
  1192. json nv4m;
  1193. json &v4m = b["v4AssignMode"];
  1194. if (v4m.is_string()) { // backward compatibility
  1195. nv4m["zt"] = (_jS(v4m,"") == "zt");
  1196. } else if (v4m.is_object()) {
  1197. nv4m["zt"] = _jB(v4m["zt"],false);
  1198. } else nv4m["zt"] = false;
  1199. network["v4AssignMode"] = nv4m;
  1200. }
  1201. if (b.count("v6AssignMode")) {
  1202. json nv6m;
  1203. json &v6m = b["v6AssignMode"];
  1204. if (!nv6m.is_object()) nv6m = json::object();
  1205. if (v6m.is_string()) { // backward compatibility
  1206. std::vector<std::string> v6ms(Utils::split(_jS(v6m,"").c_str(),",","",""));
  1207. std::sort(v6ms.begin(),v6ms.end());
  1208. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  1209. nv6m["rfc4193"] = false;
  1210. nv6m["zt"] = false;
  1211. nv6m["6plane"] = false;
  1212. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  1213. if (*i == "rfc4193")
  1214. nv6m["rfc4193"] = true;
  1215. else if (*i == "zt")
  1216. nv6m["zt"] = true;
  1217. else if (*i == "6plane")
  1218. nv6m["6plane"] = true;
  1219. }
  1220. } else if (v6m.is_object()) {
  1221. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1222. if (v6m.count("zt")) nv6m["zt"] = _jB(v6m["zt"],false);
  1223. if (v6m.count("6plane")) nv6m["6plane"] = _jB(v6m["6plane"],false);
  1224. } else {
  1225. nv6m["rfc4193"] = false;
  1226. nv6m["zt"] = false;
  1227. nv6m["6plane"] = false;
  1228. }
  1229. network["v6AssignMode"] = nv6m;
  1230. }
  1231. if (b.count("routes")) {
  1232. json &rts = b["routes"];
  1233. if (rts.is_array()) {
  1234. json nrts = json::array();
  1235. for(unsigned long i=0;i<rts.size();++i) {
  1236. json &rt = rts[i];
  1237. if (rt.is_object()) {
  1238. json &target = rt["target"];
  1239. json &via = rt["via"];
  1240. if (target.is_string()) {
  1241. InetAddress t(target.get<std::string>());
  1242. InetAddress v;
  1243. if (via.is_string()) v.fromString(via.get<std::string>());
  1244. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  1245. json tmp;
  1246. tmp["target"] = t.toString();
  1247. if (v.ss_family == t.ss_family)
  1248. tmp["via"] = v.toIpString();
  1249. else tmp["via"] = json();
  1250. nrts.push_back(tmp);
  1251. }
  1252. }
  1253. }
  1254. }
  1255. network["routes"] = nrts;
  1256. }
  1257. }
  1258. if (b.count("ipAssignmentPools")) {
  1259. json &ipp = b["ipAssignmentPools"];
  1260. if (ipp.is_array()) {
  1261. json nipp = json::array();
  1262. for(unsigned long i=0;i<ipp.size();++i) {
  1263. json &ip = ipp[i];
  1264. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1265. InetAddress f(_jS(ip["ipRangeStart"],""));
  1266. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1267. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1268. json tmp = json::object();
  1269. tmp["ipRangeStart"] = f.toIpString();
  1270. tmp["ipRangeEnd"] = t.toIpString();
  1271. nipp.push_back(tmp);
  1272. }
  1273. }
  1274. }
  1275. network["ipAssignmentPools"] = nipp;
  1276. }
  1277. }
  1278. if (b.count("rules")) {
  1279. json &rules = b["rules"];
  1280. if (rules.is_array()) {
  1281. json nrules = json::array();
  1282. for(unsigned long i=0;i<rules.size();++i) {
  1283. json &rule = rules[i];
  1284. if (rule.is_object()) {
  1285. ZT_VirtualNetworkRule ztr;
  1286. if (_parseRule(rule,ztr))
  1287. nrules.push_back(_renderRule(ztr));
  1288. }
  1289. }
  1290. network["rules"] = nrules;
  1291. }
  1292. }
  1293. if (b.count("authTokens")) {
  1294. json &authTokens = b["authTokens"];
  1295. if (authTokens.is_array()) {
  1296. json nat = json::array();
  1297. for(unsigned long i=0;i<authTokens.size();++i) {
  1298. json &token = authTokens[i];
  1299. if (token.is_object()) {
  1300. std::string tstr = token["token"];
  1301. if (tstr.length() > 0) {
  1302. json t = json::object();
  1303. t["token"] = tstr;
  1304. t["expires"] = _jI(token["expires"],0ULL);
  1305. t["maxUsesPerMember"] = _jI(token["maxUsesPerMember"],0ULL);
  1306. nat.push_back(t);
  1307. }
  1308. }
  1309. }
  1310. network["authTokens"] = nat;
  1311. }
  1312. }
  1313. if (b.count("capabilities")) {
  1314. json &capabilities = b["capabilities"];
  1315. if (capabilities.is_array()) {
  1316. std::map< uint64_t,json > ncaps;
  1317. for(unsigned long i=0;i<capabilities.size();++i) {
  1318. json &cap = capabilities[i];
  1319. if (cap.is_object()) {
  1320. json ncap = json::object();
  1321. const uint64_t capId = _jI(cap["id"],0ULL);
  1322. ncap["id"] = capId;
  1323. json &rules = cap["rules"];
  1324. json nrules = json::array();
  1325. if (rules.is_array()) {
  1326. for(unsigned long i=0;i<rules.size();++i) {
  1327. json &rule = rules[i];
  1328. if (rule.is_object()) {
  1329. ZT_VirtualNetworkRule ztr;
  1330. if (_parseRule(rule,ztr))
  1331. nrules.push_back(_renderRule(ztr));
  1332. }
  1333. }
  1334. }
  1335. ncap["rules"] = nrules;
  1336. ncaps[capId] = ncap;
  1337. }
  1338. }
  1339. json ncapsa = json::array();
  1340. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1341. ncapsa.push_back(c->second);
  1342. network["capabilities"] = ncapsa;
  1343. }
  1344. }
  1345. } catch ( ... ) {
  1346. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  1347. responseContentType = "application/json";
  1348. return 400;
  1349. }
  1350. network["id"] = nwids;
  1351. network["nwid"] = nwids; // legacy
  1352. json &rev = network["revision"];
  1353. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1354. network["lastModified"] = now;
  1355. {
  1356. Mutex::Lock _l(_db_m);
  1357. _db.put("network",nwids,network);
  1358. }
  1359. _NetworkMemberInfo nmi;
  1360. _getNetworkMemberInfo(now,nwid,nmi);
  1361. _addNetworkNonPersistedFields(network,now,nmi);
  1362. responseBody = network.dump(2);
  1363. responseContentType = "application/json";
  1364. return 200;
  1365. } // else 404
  1366. } // else 404
  1367. } // else 404
  1368. return 404;
  1369. }
  1370. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1371. const std::vector<std::string> &path,
  1372. const std::map<std::string,std::string> &urlArgs,
  1373. const std::map<std::string,std::string> &headers,
  1374. const std::string &body,
  1375. std::string &responseBody,
  1376. std::string &responseContentType)
  1377. {
  1378. if (path.empty())
  1379. return 404;
  1380. if (path[0] == "network") {
  1381. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1382. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1383. char nwids[24];
  1384. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  1385. json network;
  1386. {
  1387. Mutex::Lock _l(_db_m);
  1388. network = _db.get("network",nwids,0);
  1389. }
  1390. if (!network.size())
  1391. return 404;
  1392. if (path.size() >= 3) {
  1393. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1394. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1395. Mutex::Lock _l(_db_m);
  1396. json member = _db.get("network",nwids,"member",Address(address).toString(),0);
  1397. _db.erase("network",nwids,"member",Address(address).toString());
  1398. if (!member.size())
  1399. return 404;
  1400. responseBody = member.dump(2);
  1401. responseContentType = "application/json";
  1402. return 200;
  1403. }
  1404. } else {
  1405. Mutex::Lock _l(_db_m);
  1406. std::string pfx("network/"); pfx.append(nwids);
  1407. _db.filter(pfx,120000,[](const std::string &n,const json &obj) {
  1408. return false; // delete
  1409. });
  1410. Mutex::Lock _l2(_nmiCache_m);
  1411. _nmiCache.erase(nwid);
  1412. responseBody = network.dump(2);
  1413. responseContentType = "application/json";
  1414. return 200;
  1415. }
  1416. } // else 404
  1417. } // else 404
  1418. return 404;
  1419. }
  1420. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1421. {
  1422. char tmp[65535];
  1423. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1424. if (!test)
  1425. return;
  1426. if (!report)
  1427. return;
  1428. Mutex::Lock _l(self->_circuitTests_m);
  1429. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1430. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1431. self->_node->circuitTestEnd(test);
  1432. ::free((void *)test);
  1433. return;
  1434. }
  1435. Utils::snprintf(tmp,sizeof(tmp),
  1436. "%s{\n"
  1437. "\t\"timestamp\": %llu," ZT_EOL_S
  1438. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1439. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1440. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1441. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1442. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1443. "\t\"flags\": %llu," ZT_EOL_S
  1444. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1445. "\t\"errorCode\": %u," ZT_EOL_S
  1446. "\t\"vendor\": %d," ZT_EOL_S
  1447. "\t\"protocolVersion\": %u," ZT_EOL_S
  1448. "\t\"majorVersion\": %u," ZT_EOL_S
  1449. "\t\"minorVersion\": %u," ZT_EOL_S
  1450. "\t\"revision\": %u," ZT_EOL_S
  1451. "\t\"platform\": %d," ZT_EOL_S
  1452. "\t\"architecture\": %d," ZT_EOL_S
  1453. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1454. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1455. "}",
  1456. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1457. (unsigned long long)report->timestamp,
  1458. (unsigned long long)test->testId,
  1459. (unsigned long long)report->upstream,
  1460. (unsigned long long)report->current,
  1461. (unsigned long long)OSUtils::now(),
  1462. (unsigned long long)report->sourcePacketId,
  1463. (unsigned long long)report->flags,
  1464. report->sourcePacketHopCount,
  1465. report->errorCode,
  1466. (int)report->vendor,
  1467. report->protocolVersion,
  1468. report->majorVersion,
  1469. report->minorVersion,
  1470. report->revision,
  1471. (int)report->platform,
  1472. (int)report->architecture,
  1473. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1474. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1475. cte->second.jsonResults.append(tmp);
  1476. }
  1477. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1478. {
  1479. char pfx[256];
  1480. Utils::snprintf(pfx,sizeof(pfx),"network/%.16llx/member",nwid);
  1481. {
  1482. Mutex::Lock _l(_nmiCache_m);
  1483. std::map<uint64_t,_NetworkMemberInfo>::iterator c(_nmiCache.find(nwid));
  1484. if ((c != _nmiCache.end())&&((now - c->second.nmiTimestamp) < 1000)) { // a short duration cache but limits CPU use on big networks
  1485. nmi = c->second;
  1486. return;
  1487. }
  1488. }
  1489. {
  1490. Mutex::Lock _l(_db_m);
  1491. _db.filter(pfx,120000,[&nmi,&now](const std::string &n,const json &member) {
  1492. try {
  1493. if (_jB(member["authorized"],false)) {
  1494. ++nmi.authorizedMemberCount;
  1495. if (member.count("recentLog")) {
  1496. const json &mlog = member["recentLog"];
  1497. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1498. const json &mlog1 = mlog[0];
  1499. if (mlog1.is_object()) {
  1500. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1501. ++nmi.activeMemberCount;
  1502. }
  1503. }
  1504. }
  1505. if (_jB(member["activeBridge"],false)) {
  1506. nmi.activeBridges.insert(_jS(member["id"],"0000000000"));
  1507. }
  1508. if (member.count("ipAssignments")) {
  1509. const json &mips = member["ipAssignments"];
  1510. if (mips.is_array()) {
  1511. for(unsigned long i=0;i<mips.size();++i) {
  1512. InetAddress mip(_jS(mips[i],""));
  1513. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1514. nmi.allocatedIps.insert(mip);
  1515. }
  1516. }
  1517. }
  1518. } else {
  1519. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(member["lastDeauthorizedTime"],0ULL));
  1520. }
  1521. } catch ( ... ) {}
  1522. return true;
  1523. });
  1524. }
  1525. nmi.nmiTimestamp = now;
  1526. {
  1527. Mutex::Lock _l(_nmiCache_m);
  1528. _nmiCache[nwid] = nmi;
  1529. }
  1530. }
  1531. } // namespace ZeroTier