EmbeddedNetworkController.cpp 61 KB

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