2
0

EmbeddedNetworkController.cpp 63 KB

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